diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 110df8c..f08b4ca 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -129,8 +129,49 @@ jobs: name: macos path: dist/* + android: + needs: version + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-java@v5 + with: + distribution: temurin + java-version: "21" + - uses: dtolnay/rust-toolchain@stable + with: + targets: aarch64-linux-android,x86_64-linux-android + - uses: Swatinem/rust-cache@v2 + - name: Android NDK and platform, cargo-ndk + run: | + yes | "${ANDROID_HOME}/cmdline-tools/latest/bin/sdkmanager" --install "ndk;30.0.16248370" "platforms;android-37.0" > /dev/null + cargo install cargo-ndk --version 4.1.2 --locked + # Two APKs: Stockfish built in, and Stockfish downloaded in the app + # (androidApp/scripts/release.sh, which also builds Stockfish from its source). + # The signing key comes from the repository secrets. + - name: Signed APKs + env: + KEYSTORE_BASE64: ${{ secrets.ANDROID_KEYSTORE_BASE64 }} + CP_KEYSTORE_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }} + CP_KEY_ALIAS: chesspenguin + CP_KEY_PASSWORD: ${{ secrets.ANDROID_KEY_PASSWORD }} + run: | + if [[ -z "${KEYSTORE_BASE64}" ]]; then + echo "::error::The Android signing key is not in the repository secrets" + exit 1 + fi + export CP_KEYSTORE="${RUNNER_TEMP}/release.jks" + echo "${KEYSTORE_BASE64}" | base64 -d > "${CP_KEYSTORE}" + export ANDROID_NDK_HOME="${ANDROID_HOME}/ndk/30.0.16248370" + androidApp/scripts/release.sh + rm -f "${CP_KEYSTORE}" + - uses: actions/upload-artifact@v7 + with: + name: android + path: androidApp/dist/*.apk + publish: - needs: [version, linux, flatpak, windows, macos] + needs: [version, linux, flatpak, windows, macos, android] if: github.ref_type == 'tag' runs-on: ubuntu-24.04 steps: @@ -139,7 +180,7 @@ jobs: with: path: dist merge-multiple: true - - name: Stockfish source (GPL-3.0 source offer for the engine bundled in the Flatpak) + - name: Stockfish source (GPL-3.0 source offer for the engine bundled in the Flatpak and Android) run: packaging/stockfish.sh source dist - name: Checksums run: cd dist && sha256sum * > SHA256SUMS.txt diff --git a/CHANGELOG.md b/CHANGELOG.md index 1518824..39bdcb9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,15 @@ All notable changes are listed here. Versions follow [Semantic Versioning](https://semver.org/). +## [Unreleased] + +- **ChessPenguin for Android** (12 and newer): add databases of the same formats (PGN, ChessBase + `.cbv`, `.zip`/`.7z` archives), the desktop's sample games from the first start, a list of + games with a search, the game with the notation under the board (variations, comments, NAG, + comment arrows), paging games, and Stockfish 19 with its evaluation, lines and a preview of + a line on the board. Two APKs: Stockfish built in, or Stockfish downloaded in the app. + Files are only read, never changed. + ## [0.9.0] — 2026-10-22 The 0.8 series together — the reference tab, games from Lichess and Chess.com, self-update, diff --git a/README.md b/README.md index 0492e32..64f4181 100644 --- a/README.md +++ b/README.md @@ -63,6 +63,7 @@ Packages for every release are on the [Releases](https://github.com/vrubelroman/ | Flatpak | `flatpak install --user ChessPenguin--x86_64.flatpak` | | Windows | unzip `ChessPenguin--windows-x86_64.zip`, run `ChessPenguin.exe` | | macOS (Apple Silicon) | open `ChessPenguin--macos-arm64.dmg`, drag ChessPenguin to Applications | +| Android 12+ | open `ChessPenguin--android.apk` (Stockfish built in) or `…-android-noengine.apk` (Stockfish downloaded in the app) on the phone | On macOS the app is not signed by Apple yet: the first time, right-click ChessPenguin in Applications and choose **Open** (on macOS 15: System Settings → Privacy & Security → Open Anyway). @@ -72,6 +73,9 @@ official Stockfish 19 (about 80 MB, checked before use, installed for your accou button is also in **Settings → Engines**. A `stockfish` installed on the system is found automatically, any other UCI engine can be added from a file. The Flatpak includes Stockfish. +The **Android app** views databases and games (the same formats), with the notation under +the board and Stockfish. The two APKs install over each other; databases and settings are kept. + ### Build from source Rust 1.97 or newer. On Debian/Ubuntu: `sudo apt install pkg-config libasound2-dev libxkbcommon-dev libwayland-dev`. @@ -94,8 +98,12 @@ cargo run --release -p chesspenguin -- examples/classics.pgn - `crates/chess-core` — game tree, tolerant PGN import/export. - `crates/uci` — UCI engine process supervisor. - `apps/desktop` — the egui application. +- `crates/mobile-api`, `androidApp` — the core for the Android app and the app itself. - `packaging/` — desktop entry, AppStream metadata, icons, deb/rpm, AppImage and Flatpak recipes. +The Android app is `androidApp/` (Kotlin, Jetpack Compose) over the same Rust core +(`crates/mobile-api`, UniFFI); `androidApp/scripts/release.sh` builds the two signed APKs. + Releases are built by GitHub Actions when a `v*` tag is pushed (see `.github/workflows/release.yml`). ## License diff --git a/README.ru.md b/README.ru.md index 15fe1d2..1c176ac 100644 --- a/README.ru.md +++ b/README.ru.md @@ -48,6 +48,10 @@ Stockfish 19 (около 80 МБ, проверяется перед запуск в **Настройки → Движки**. Установленный в системе `stockfish` находится сам, другие UCI-движки добавляются из файла. Во Flatpak Stockfish уже есть. +**Android 12+:** приложение для просмотра баз и партий (те же форматы), нотация под доской, Stockfish. +Две сборки: `ChessPenguin-<версия>-android.apk` — Stockfish уже внутри, `…-android-noengine.apk` — +Stockfish скачивается в приложении. Ставятся одна поверх другой, базы и настройки сохраняются. + Сборка из исходников: Rust 1.97+, затем `cargo run --release -p chesspenguin` или `./scripts/install.sh` для установки в `~/.local` вместе со Stockfish (`--no-stockfish` — без него). diff --git a/androidApp/.gitignore b/androidApp/.gitignore index aa724b7..f4bbe68 100644 --- a/androidApp/.gitignore +++ b/androidApp/.gitignore @@ -13,3 +13,5 @@ .externalNativeBuild .cxx local.properties +/dist +.env diff --git a/androidApp/app/build.gradle.kts b/androidApp/app/build.gradle.kts index 1125e3f..a8d8fc1 100644 --- a/androidApp/app/build.gradle.kts +++ b/androidApp/app/build.gradle.kts @@ -16,6 +16,12 @@ 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 version of the workspace (Cargo.toml): the phone and the desktop are one release. +val version: String = Regex("""(?m)^version = "([^"]+)"""") + .find(File(repo, "Cargo.toml").readText())!!.groupValues[1] +val versionNumber: Int = version.split('.').map { it.takeWhile(Char::isDigit).toInt() } + .let { (major, minor, patch) -> major * 10000 + minor * 100 + patch } + /// The core for the phones (arm64) and the emulator (x86_64). val cargoBuild = tasks.register("cargoBuild") { workingDir = repo @@ -99,8 +105,8 @@ android { applicationId = "io.github.vrubelroman.chesspenguin" minSdk = 31 targetSdk = 36 - versionCode = 1 - versionName = "0.1.0" + versionCode = versionNumber + versionName = version ndk { abiFilters += listOf("arm64-v8a", "x86_64") } @@ -115,12 +121,32 @@ android { ) } + // The release key is never in the repository: CP_KEYSTORE, CP_KEYSTORE_PASSWORD, + // CP_KEY_ALIAS, CP_KEY_PASSWORD come from the environment (scripts/release.sh, CI). + val keystore = System.getenv("CP_KEYSTORE") + signingConfigs { + if (keystore != null) { + create("release") { + storeFile = File(keystore) + storePassword = System.getenv("CP_KEYSTORE_PASSWORD") + keyAlias = System.getenv("CP_KEY_ALIAS") + keyPassword = System.getenv("CP_KEY_PASSWORD") + } + } + } + buildTypes { release { - isMinifyEnabled = false + isMinifyEnabled = true + isShrinkResources = true proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro") + signingConfig = signingConfigs.findByName("release") } } + // The languages of the interface; the libraries' other translations stay out. + androidResources { + localeFilters += listOf("en", "ru") + } compileOptions { sourceCompatibility = JavaVersion.VERSION_17 targetCompatibility = JavaVersion.VERSION_17 diff --git a/androidApp/app/proguard-rules.pro b/androidApp/app/proguard-rules.pro new file mode 100644 index 0000000..e533f6f --- /dev/null +++ b/androidApp/app/proguard-rules.pro @@ -0,0 +1,6 @@ +# The Rust core is reached through JNA (UniFFI): JNA finds the native functions and +# the structures by reflection, so neither may be renamed or removed. +-keep class com.sun.jna.** { *; } +-keep class * implements com.sun.jna.** { *; } +-keep class uniffi.mobile_api.** { *; } +-dontwarn java.awt.** diff --git a/androidApp/app/src/main/AndroidManifest.xml b/androidApp/app/src/main/AndroidManifest.xml index 36ad798..473f472 100644 --- a/androidApp/app/src/main/AndroidManifest.xml +++ b/androidApp/app/src/main/AndroidManifest.xml @@ -9,7 +9,9 @@ android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:windowSoftInputMode="adjustResize" - android:theme="@style/Theme.ChessPenguin"> + android:theme="@style/Theme.ChessPenguin" + android:localeConfig="@xml/locales_config" + android:enableOnBackInvokedCallback="true"> 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 index 9fd66ad..3bb97af 100644 --- 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 @@ -34,6 +34,7 @@ val DarkErrorContainer = Color(0xFF5C1A14) /// Colors of the notation and the board that stay ours whatever the theme. data class ChessColors( + val dark: Boolean, val currentMove: Color, val comment: Color, val lightSquare: Color, @@ -42,6 +43,7 @@ data class ChessColors( ) val LightChess = ChessColors( + dark = false, currentMove = Color(0xFF90D1FF), comment = Color(0xFF2A5B8A), lightSquare = Color(0xFFFFFFDD), @@ -50,17 +52,31 @@ val LightChess = ChessColors( ) val DarkChess = LightChess.copy( + dark = true, 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 +/// Move assessments in the colors of Lichess (as on the desktop). On a light background +/// they are darkened to stay readable (contrast at least 4.5:1). +fun nagColor(nag: Int, dark: Boolean): Color? = if (dark) { + when (nag) { + 1 -> Color(0xFF629C2E) // ! + 2 -> Color(0xFFE68F00) // ? + 3 -> Color(0xFF22AC9A) // !! + 4 -> Color(0xFFDF5353) // ?? + 5 -> Color(0xFFEA45D8) // !? + 6 -> Color(0xFF56B4E9) // ?! + else -> null + } +} else { + when (nag) { + 1 -> Color(0xFF4E7F22) + 2 -> Color(0xFFA35F00) + 3 -> Color(0xFF12806F) + 4 -> Color(0xFFC23B3B) + 5 -> Color(0xFFB0259F) + 6 -> Color(0xFF1F72A8) + else -> null + } } 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 index b6087d2..9dcd556 100644 --- 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 @@ -180,17 +180,6 @@ fun Board( ) } } - // 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 @@ -202,6 +191,18 @@ fun Board( } drawImage(bmp, dstOffset = IntOffset(at.x.toInt(), at.y.toInt()), dstSize = IntSize(px, px)) } + // Over the pieces, so that b, c, f, g stay readable (as on Lichess). + // 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 (a in arrows) { val f = squareIndex(a.from) ?: continue val t = squareIndex(a.to) ?: continue 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 index cd316e7..dd51534 100644 --- 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 @@ -126,7 +126,7 @@ private fun LineRow( .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), + .padding(start = 16.dp, end = if (first) 0.dp else 16.dp), verticalAlignment = Alignment.CenterVertically, ) { EvalPlaque(line) @@ -155,7 +155,8 @@ private fun LineRow( ) if (first && status == EngineStatus.Paused) { TextButton(onClick = onDeeper) { Text(stringResource(R.string.deeper)) } - } else if (first && canExpand) { + } + if (first && canExpand) { IconButton(onClick = onExpand) { Icon( if (expanded) Icons.Rounded.ExpandLess else Icons.Rounded.ExpandMore, @@ -178,7 +179,7 @@ private fun EvalPlaque(line: EngineLine?) { .height(28.dp) .clip(RoundedCornerShape(8.dp)) .background(bg) - .border(1.dp, MaterialTheme.colorScheme.outlineVariant, RoundedCornerShape(8.dp)), + .border(1.dp, MaterialTheme.colorScheme.outline, RoundedCornerShape(8.dp)), contentAlignment = Alignment.Center, ) { Text( @@ -204,7 +205,7 @@ fun PreviewBar(step: Int, total: Int, onClose: () -> Unit) { Row( Modifier .fillMaxWidth() - .height(40.dp) + .height(48.dp) .background(MaterialTheme.colorScheme.primaryContainer) .padding(start = 16.dp), verticalAlignment = Alignment.CenterVertically, @@ -259,7 +260,7 @@ fun EngineSheet(state: NetState, metered: Boolean, onDownload: () -> Unit, onCan 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)) } + if (state.problem != NetProblem.NoSpace) 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)) } 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 index 6aab596..0c27053 100644 --- 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 @@ -1,9 +1,15 @@ package io.github.vrubelroman.chesspenguin.ui import android.content.Context +import android.content.Intent import android.view.HapticFeedbackConstants import androidx.activity.compose.BackHandler import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.indication +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.interaction.PressInteraction +import androidx.compose.foundation.verticalScroll import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.Arrangement @@ -22,8 +28,6 @@ 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 @@ -31,9 +35,13 @@ 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.MoreVert +import androidx.compose.material.icons.rounded.PlayArrow import androidx.compose.material.icons.rounded.SwapVert +import androidx.compose.material3.AlertDialog import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.FilterChip import androidx.compose.material3.HorizontalDivider @@ -46,7 +54,9 @@ import androidx.compose.material3.SnackbarHost import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.Surface import androidx.compose.material3.Text +import androidx.compose.material3.TextButton import androidx.compose.material3.TopAppBar +import androidx.compose.material3.ripple import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect @@ -61,6 +71,7 @@ import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.scale import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.input.pointer.pointerInput @@ -152,6 +163,16 @@ fun GameScreen(db: String, startPlace: Int, onBack: () -> Unit, onSettings: () - var sheet by remember { mutableStateOf(false) } var wantEngine by remember { mutableStateOf(false) } var expanded by rememberSaveable { mutableStateOf(false) } + var menu by remember { mutableStateOf(false) } + var info by remember { mutableStateOf(false) } + @Suppress("DEPRECATION") + val clipboard = androidx.compose.ui.platform.LocalClipboardManager.current + val copiedText = stringResource(R.string.copied) + suspend fun pgnText(): String? { + val index = games?.getOrNull(place) ?: return null + val database = app.library.database(db).getOrNull() ?: return null + return withContext(Dispatchers.Default) { database.pgn(index) } + } val lifecycle = LocalLifecycleOwner.current.lifecycle DisposableEffect(lifecycle) { val observer = LifecycleEventObserver { _, e -> @@ -267,7 +288,7 @@ fun GameScreen(db: String, startPlace: Int, onBack: () -> Unit, onSettings: () - ) if (total > 0) { Text( - joinKnown(stringResource(R.string.game_of, place + 1, total), g?.let { shortResult(it.result) } ?: ""), + joinKnown(stringResource(R.string.game_of, place + 1, total), g?.let { shortResult(it.result) }?.takeIf { it != "*" } ?: ""), style = MaterialTheme.typography.bodyMedium.merge(Tabular), color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -281,13 +302,81 @@ fun GameScreen(db: String, startPlace: Int, onBack: () -> Unit, onSettings: () - 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)) } + 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.game_info)) }, enabled = g != null, onClick = { + menu = false + info = true + }) + DropdownMenuItem(text = { Text(stringResource(R.string.copy_pgn)) }, enabled = g != null, onClick = { + menu = false + scope.launch { + pgnText()?.let { + clipboard.setText(AnnotatedString(it)) + snackbar.showSnackbar(copiedText) + } + } + }) + DropdownMenuItem(text = { Text(stringResource(R.string.copy_fen)) }, enabled = node != null, onClick = { + menu = false + (preview?.let { it.line.steps[it.step].fen } ?: node?.fen)?.let { + clipboard.setText(AnnotatedString(it)) + scope.launch { snackbar.showSnackbar(copiedText) } + } + }) + DropdownMenuItem(text = { Text(stringResource(R.string.share_game)) }, enabled = g != null, onClick = { + menu = false + scope.launch { + pgnText()?.let { text -> + val send = Intent(Intent.ACTION_SEND).setType("text/plain").putExtra(Intent.EXTRA_TEXT, text) + context.startActivity(Intent.createChooser(send, null)) + } + } + }) + DropdownMenuItem(text = { Text(stringResource(R.string.settings)) }, onClick = { + menu = false + onSettings() + }) + } + } }, ) }, snackbarHost = { SnackbarHost(snackbar) }, + // In the bottom bar, so that snackbars stand above the move buttons. + bottomBar = { + Column { + val p = preview + 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.Rounded.PlayArrow, stringResource(R.string.move_back), canBack, Modifier.weight(1.5f), 32, repeat = true, mirrored = true) { back() } + BarButton(Icons.Rounded.PlayArrow, stringResource(R.string.move_forward), canForward, Modifier.weight(1.5f), 32, repeat = true) { forward() } + BarButton(Icons.Rounded.LastPage, stringResource(R.string.to_end), canForward, Modifier.weight(1f)) { end() } + } + } + } + }, ) { padding -> - Column(Modifier.fillMaxSize().padding(top = padding.calculateTopPadding())) { + Column(Modifier.fillMaxSize().padding(top = padding.calculateTopPadding(), bottom = padding.calculateBottomPadding())) { val p = preview val step = p?.let { it.line.steps[it.step] } val fen = step?.fen ?: node?.fen ?: START @@ -347,7 +436,7 @@ fun GameScreen(db: String, startPlace: Int, onBack: () -> Unit, onSettings: () - }, notation = line, ) - } else if (wantEngine && netState is NetState.Loading) { + } else if (wantEngine && files.builtIn && 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) @@ -365,33 +454,29 @@ fun GameScreen(db: String, startPlace: Int, onBack: () -> Unit, onSettings: () - 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 (info && g != null) { + AlertDialog( + onDismissRequest = { info = false }, + title = { Text(stringResource(R.string.game_info)) }, + text = { + Column(Modifier.verticalScroll(rememberScrollState())) { + g.tags.filter { it.value.isNotBlank() && it.value != "?" }.forEach { t -> + Row(Modifier.padding(vertical = 4.dp)) { + Text(t.name, Modifier.width(96.dp), color = MaterialTheme.colorScheme.onSurfaceVariant, style = MaterialTheme.typography.bodyMedium) + Text(t.value, style = MaterialTheme.typography.bodyMedium) + } + } + if (g.notes.isNotEmpty()) { + Text(stringResource(R.string.notes), Modifier.padding(top = 12.dp), style = MaterialTheme.typography.labelLarge) + g.notes.forEach { Text(it, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) } + } + } + }, + confirmButton = { TextButton(onClick = { info = false }) { Text(stringResource(R.string.close)) } }, + ) + } if (sheet) { EngineSheet( state = netState, @@ -418,6 +503,13 @@ private const val START = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - @Composable private fun EngineButton(on: Boolean, needsDownload: Boolean, loading: NetState.Loading?, modifier: Modifier, onClick: () -> Unit) { val label = stringResource(R.string.engine) + val state = stringResource( + when { + needsDownload -> R.string.engine_state_missing + on -> R.string.engine_state_on + else -> R.string.engine_state_off + }, + ) val action by rememberUpdatedState(onClick) val color = if (on) MaterialTheme.colorScheme.primary else LocalContentColor.current Column( @@ -426,10 +518,10 @@ private fun EngineButton(on: Boolean, needsDownload: Boolean, loading: NetState. .semantics { contentDescription = label role = Role.Switch - stateDescription = if (on) "on" else "off" + stateDescription = state onClick { action(); true } } - .pointerInput(Unit) { detectTapGestures { action() } }, + .clickable(onClick = action), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center, ) { @@ -484,10 +576,12 @@ private fun BarButton( modifier: Modifier, iconSize: Int = 24, repeat: Boolean = false, + mirrored: Boolean = false, onClick: () -> Unit, ) { val action by rememberUpdatedState(onClick) val on by rememberUpdatedState(enabled) + val interaction = remember { MutableInteractionSource() } val color = if (enabled) LocalContentColor.current else MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f) Box( modifier @@ -498,27 +592,34 @@ private fun BarButton( if (!enabled) disabled() onClick { action(); true } } + .indication(interaction, ripple(bounded = false, radius = 32.dp)) .pointerInput(repeat) { - detectTapGestures(onPress = { + detectTapGestures(onPress = { at -> if (!on) return@detectTapGestures + val press = PressInteraction.Press(at) + interaction.emit(press) action() - if (!repeat) return@detectTapGestures coroutineScope { - val job = launch { - delay(400) - while (on) { - action() - delay(120) + val job = if (repeat) { + launch { + delay(400) + while (on) { + action() + delay(120) + } } + } else { + null } tryAwaitRelease() - job.cancel() + job?.cancel() } + interaction.emit(PressInteraction.Release(press)) }) }, contentAlignment = Alignment.Center, ) { - Icon(icon, null, tint = color, modifier = Modifier.size(iconSize.dp)) + Icon(icon, null, tint = color, modifier = Modifier.size(iconSize.dp).then(if (mirrored) Modifier.scale(-1f, 1f) else Modifier)) } } 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 index c64b41d..5a264dc 100644 --- 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 @@ -126,8 +126,13 @@ fun GamesScreen(db: String, onBack: () -> Unit, onGame: (Int) -> Unit) { Text(entry?.name ?: "", maxLines = 1, overflow = TextOverflow.Ellipsis) database?.let { d -> val n = d.len().toInt() + val found = shown?.size Text( - pluralStringResource(R.plurals.games_count, n, groupDigits(n)), + if (query.isNotEmpty() && found != null) { + stringResource(R.string.found_of, groupDigits(found), groupDigits(n)) + } else { + pluralStringResource(R.plurals.games_count, n, groupDigits(n)) + }, style = MaterialTheme.typography.bodyMedium.merge(Tabular), color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -188,20 +193,21 @@ private fun Message(title: String, detail: String) { } } -/// One game: "White – Black" and the result, then event · year · ECO (§6.2). +/// One game: "White – Black" and the result, then event · year · ECO (§6.2). An +/// unfinished game ("*", most book positions) shows no result. @Composable private fun GameRowView(row: GameRow?, onClick: () -> Unit) { - Row( + Column( Modifier .fillMaxWidth() .height(64.dp) .clickable(enabled = row != null, onClick = onClick) .padding(horizontal = 16.dp), - verticalAlignment = Alignment.CenterVertically, + verticalArrangement = Arrangement.Center, ) { - Column(Modifier.weight(1f)) { - if (row == null) return@Column - Row { + if (row == null) return@Column + Row(verticalAlignment = Alignment.CenterVertically) { + Row(Modifier.weight(1f)) { Text( shortName(row.white), style = MaterialTheme.typography.bodyLarge, @@ -221,22 +227,25 @@ private fun GameRowView(row: GameRow?, onClick: () -> Unit) { ) } } - val details = joinKnown(row.event, year(row.date), row.eco) - if (details.isNotEmpty()) { + val result = shortResult(row.result) + if (result != "*") { Text( - details, - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - maxLines = 1, - overflow = TextOverflow.Ellipsis, + result, + style = MaterialTheme.typography.bodyLarge.merge(Tabular), + textAlign = TextAlign.End, + modifier = Modifier.width(48.dp).padding(start = 8.dp), ) } } - Text( - row?.let { shortResult(it.result) } ?: "", - style = MaterialTheme.typography.bodyLarge.merge(Tabular), - textAlign = TextAlign.End, - modifier = Modifier.width(48.dp).padding(start = 8.dp), - ) + 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, + ) + } } } 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 index 191aac6..89bd6cc 100644 --- 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 @@ -158,7 +158,8 @@ private fun variationText( append(label(n, number, san)) } if (n.nagSymbols.isNotEmpty()) { - val c = n.nags.firstOrNull()?.let { nagColor(it.toInt()) } ?: onSurface + // On the highlighted move the sign takes the text color. + val c = if (id == current) onSurface else n.nags.firstOrNull()?.let { nagColor(it.toInt(), chess.dark) } ?: onSurface withStyle(SpanStyle(color = c)) { append(n.nagSymbols) } } } @@ -222,7 +223,7 @@ fun Notation( lineHeight = 22.sp, modifier = Modifier .fillMaxWidth() - .padding(horizontal = 8.dp, vertical = 4.dp) + .padding(horizontal = 16.dp, vertical = 4.dp) .clip(RoundedCornerShape(12.dp)) .background(MaterialTheme.colorScheme.surfaceContainerLow) .padding(horizontal = 12.dp, vertical = 8.dp), @@ -231,7 +232,7 @@ fun Notation( is Item.Variation -> Box( Modifier .fillMaxWidth() - .padding(start = (8 + 16 * (item.depth - 1)).dp, end = 8.dp, top = 2.dp, bottom = 2.dp), + .padding(start = (16 + 16 * (item.depth - 1)).dp, end = 16.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)) @@ -275,8 +276,8 @@ private fun MovesRow( 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)) + MoveCell(game, row.white, true, current, chess, san, onMove, Modifier.weight(1f)) + MoveCell(game, row.black, false, current, chess, san, onMove, Modifier.weight(1f)) } } @@ -284,6 +285,7 @@ private fun MovesRow( private fun MoveCell( game: GameData, id: Int?, + white: Boolean, current: Int, chess: ChessColors, san: (String) -> AnnotatedString, @@ -300,7 +302,8 @@ private fun MoveCell( contentAlignment = Alignment.CenterStart, ) { if (id == null) { - Text("…", color = MaterialTheme.colorScheme.onSurfaceVariant, fontSize = 17.sp, modifier = Modifier.padding(horizontal = 8.dp)) + // "4. … Nf6": only White's empty cell says that a move is there. + if (white) Text("…", color = MaterialTheme.colorScheme.onSurfaceVariant, fontSize = 17.sp, modifier = Modifier.padding(horizontal = 8.dp)) } else { val n = game.nodes[id] Row( @@ -316,7 +319,11 @@ private fun MoveCell( n.nagSymbols, fontSize = 17.sp, fontWeight = FontWeight.Medium, - color = n.nags.firstOrNull()?.let { nagColor(it.toInt()) } ?: MaterialTheme.colorScheme.onSurfaceVariant, + color = if (selected) { + MaterialTheme.colorScheme.onSurface + } else { + n.nags.firstOrNull()?.let { nagColor(it.toInt(), chess.dark) } ?: 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 index b6e955a..3e7047e 100644 --- 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 @@ -27,6 +27,7 @@ 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.getValue import androidx.compose.runtime.mutableStateOf @@ -56,6 +57,7 @@ fun SettingsScreen(onBack: () -> Unit, onAbout: () -> Unit) { val set = app.settings::update var choice by remember { mutableStateOf(null) } var deleting by remember { mutableStateOf(false) } + var sheet by remember { mutableStateOf(false) } val lang = uiLanguage() val scroll = TopAppBarDefaults.pinnedScrollBehavior() val size = (BuildConfig.NET_SIZE / 1_000_000).toInt() @@ -92,12 +94,7 @@ fun SettingsScreen(onBack: () -> Unit, onAbout: () -> Unit) { }, ) { 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) } - } - } + Group(stringResource(R.string.group_game)) val notationNow = notationNames.firstOrNull { it.first == prefs.notation } ?: notationNames.first() Item(stringResource(R.string.notation), notationNow.second) { choice = Choice( @@ -108,23 +105,30 @@ fun SettingsScreen(onBack: () -> Unit, onAbout: () -> Unit) { ) { 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_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) } + } + } + Group(stringResource(R.string.group_engine)) when { - files.builtIn -> Item(stringResource(R.string.engine_built_in), null, null) + files.builtIn -> Status(stringResource(R.string.engine_built_in)) net == NetState.Ready -> { - Item(stringResource(R.string.engine_downloaded), null, null) + Status(stringResource(R.string.engine_downloaded)) 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) + Item(stringResource(R.string.engine_downloading, (l.done / 1_000_000).toInt(), (l.total / 1_000_000).toInt()), null) { sheet = true } } - else -> Item(stringResource(R.string.engine_missing, size), null) { files.prepare() } + // The same sheet as in a game: the size, mobile data, cancel (§9). + else -> Item(stringResource(R.string.engine_missing, size), null) { sheet = true } } 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) } } @@ -183,6 +187,19 @@ fun SettingsScreen(onBack: () -> Unit, onAbout: () -> Unit) { confirmButton = { TextButton(onClick = { choice = null }) { Text(stringResource(R.string.cancel)) } }, ) } + if (sheet) { + EngineSheet( + state = net, + metered = remember(sheet) { files.metered() }, + onDownload = { files.prepare() }, + onCancel = { + files.cancel() + sheet = false + }, + onDismiss = { sheet = false }, + ) + } + LaunchedEffect(net) { if (net == NetState.Ready) sheet = false } if (deleting) { AlertDialog( onDismissRequest = { deleting = false }, @@ -225,6 +242,17 @@ private fun Item(title: String, value: String?, onClick: (() -> Unit)?) { } } +/// A line that tells, not a button. +@Composable +private fun Status(text: String) { + Text( + text, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp), + ) +} + @Composable private fun Toggle(title: String, value: Boolean, onChange: (Boolean) -> Unit) { Row( diff --git a/androidApp/app/src/main/res/drawable-nodpi/penguin.png b/androidApp/app/src/main/res/drawable-nodpi/penguin.png index f57a3c8..63b1296 100644 Binary files a/androidApp/app/src/main/res/drawable-nodpi/penguin.png 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 deleted file mode 100644 index 07d5da9..0000000 --- a/androidApp/app/src/main/res/drawable/ic_launcher_background.xml +++ /dev/null @@ -1,170 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/androidApp/app/src/main/res/drawable/ic_launcher_foreground.xml b/androidApp/app/src/main/res/drawable/ic_launcher_foreground.xml deleted file mode 100644 index 2b068d1..0000000 --- a/androidApp/app/src/main/res/drawable/ic_launcher_foreground.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - - - - \ No newline at end of file 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 index 6f3b755..be43858 100644 --- a/androidApp/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml +++ b/androidApp/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -1,6 +1,5 @@ - - - - \ 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 index 6f3b755..be43858 100644 --- 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 @@ -1,6 +1,5 @@ - - - - \ 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 deleted file mode 100644 index c209e78..0000000 Binary files a/androidApp/app/src/main/res/mipmap-hdpi/ic_launcher.webp and /dev/null differ diff --git a/androidApp/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.webp b/androidApp/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.webp new file mode 100644 index 0000000..15982ac Binary files /dev/null and b/androidApp/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.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 deleted file mode 100644 index b2dfe3d..0000000 Binary files a/androidApp/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp and /dev/null 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 deleted file mode 100644 index 4f0f1d6..0000000 Binary files a/androidApp/app/src/main/res/mipmap-mdpi/ic_launcher.webp and /dev/null differ diff --git a/androidApp/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.webp b/androidApp/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.webp new file mode 100644 index 0000000..4c4dbb8 Binary files /dev/null and b/androidApp/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.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 deleted file mode 100644 index 62b611d..0000000 Binary files a/androidApp/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp and /dev/null 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 deleted file mode 100644 index 948a307..0000000 Binary files a/androidApp/app/src/main/res/mipmap-xhdpi/ic_launcher.webp and /dev/null differ diff --git a/androidApp/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.webp b/androidApp/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.webp new file mode 100644 index 0000000..7dc4077 Binary files /dev/null and b/androidApp/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.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 deleted file mode 100644 index 1b9a695..0000000 Binary files a/androidApp/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp and /dev/null 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 deleted file mode 100644 index 28d4b77..0000000 Binary files a/androidApp/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp and /dev/null differ diff --git a/androidApp/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.webp b/androidApp/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.webp new file mode 100644 index 0000000..aa8ef7e Binary files /dev/null and b/androidApp/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.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 deleted file mode 100644 index 9287f50..0000000 Binary files a/androidApp/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp and /dev/null 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 deleted file mode 100644 index aa7d642..0000000 Binary files a/androidApp/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp and /dev/null differ diff --git a/androidApp/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.webp b/androidApp/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.webp new file mode 100644 index 0000000..e3d20ca Binary files /dev/null and b/androidApp/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.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 deleted file mode 100644 index 9126ae3..0000000 Binary files a/androidApp/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp and /dev/null differ diff --git a/androidApp/app/src/main/res/values-night/themes.xml b/androidApp/app/src/main/res/values-night/themes.xml new file mode 100644 index 0000000..ccd27c6 --- /dev/null +++ b/androidApp/app/src/main/res/values-night/themes.xml @@ -0,0 +1,8 @@ + + + + diff --git a/androidApp/app/src/main/res/values-ru/strings.xml b/androidApp/app/src/main/res/values-ru/strings.xml index 8277ff1..f240de3 100644 --- a/androidApp/app/src/main/res/values-ru/strings.xml +++ b/androidApp/app/src/main/res/values-ru/strings.xml @@ -35,11 +35,11 @@ %1$d из %2$d Предыдущая партия Следующая партия - Перевернуть + Перевернуть доску В начало Ход назад Ход вперёд - В конец + В конец линии Дальше: Это просмотр партии. Ходы листаются кнопками ◀ ▶ внизу. Доска, позиция после %1$s @@ -83,7 +83,6 @@ Настройки Внешний вид - Доска Движок Тема Как в системе @@ -114,9 +113,21 @@ %1$d МБ Движок расходует заряд. Он сам останавливается, когда гаснет экран. О программе - Stockfish внутри - Stockfish скачивается + Stockfish уже внутри + Stockfish скачивается в приложении Просмотр шахматных баз: PGN, ChessBase, архивы. Файлы только читаются и никогда не меняются. - Лицензии + Лицензии и авторы Сайт и исходный код + + Сведения о партии + Копировать PGN + Копировать FEN + Поделиться партией + Скопировано + Замечания + включён + выключен + не скачан + Найдено %1$s из %2$s + Партия diff --git a/androidApp/app/src/main/res/values/ic_launcher_colors.xml b/androidApp/app/src/main/res/values/ic_launcher_colors.xml new file mode 100644 index 0000000..ce2ad72 --- /dev/null +++ b/androidApp/app/src/main/res/values/ic_launcher_colors.xml @@ -0,0 +1,5 @@ + + + + #EAF2F9 + diff --git a/androidApp/app/src/main/res/values/strings.xml b/androidApp/app/src/main/res/values/strings.xml index b8e9f6f..f5114d3 100644 --- a/androidApp/app/src/main/res/values/strings.xml +++ b/androidApp/app/src/main/res/values/strings.xml @@ -3,8 +3,8 @@ Classic games Alekhine - Your databases will be here - Add a PGN file or an archive .zip/.7z — from the phone or a cloud. + Your databases will appear here + Add a PGN file or a .zip/.7z archive — from your phone or the cloud. Add database Open sample games not opened yet · %1$s @@ -15,8 +15,8 @@ %1$s · %2$s Menu Rename - Remove from the list - The name on the list. The file does not change. + Remove from list + The name in the list. The file is not changed. Cancel Save Database removed from the list @@ -34,13 +34,13 @@ %1$d of %2$d Previous game Next game - Flip + Flip board To the start Move back Move forward - To the end + To the end of the line Next: - This is a game viewer. Moves are stepped with the ◀ ▶ buttons below. + This is a game viewer. Step through the moves with ◀ ▶ below. Board, position after %1$s Board, starting position White won @@ -50,12 +50,12 @@ Engine Thinking… - d. %1$d + depth %1$d paused Deeper More lines Fewer lines - The engine is not answering + The engine is not responding The engine does not start on this phone Restart Engine line · move %1$d of %2$d @@ -63,7 +63,7 @@ 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. + No Wi-Fi now: the download will use mobile data. Not now Download Downloaded %1$d of %2$d MB @@ -71,9 +71,9 @@ Download cancelled The engine is ready No internet. Connect to a network and try again. - The download was interrupted. What came is kept. + The download was interrupted. The downloaded part is kept. Not enough space: %1$d MB needed. - The engine file was damaged in the download. Download it again. + The engine file was damaged during the download. Download it again. Try again Continue Download again @@ -81,18 +81,17 @@ Preparing the engine… Settings - Look - Board + Appearance Engine Theme - As in the system + System default 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. + Display only. PGN always uses K Q R B N. Piece animation Best-move arrow Vibration @@ -101,7 +100,7 @@ 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 the engine? You can download it again. Delete Lines Time per position @@ -111,11 +110,23 @@ Threads Memory %1$d MB - The engine uses the battery. It stops by itself when the screen goes dark. + The engine uses the battery. It stops by itself when the screen turns off. About Stockfish built in Stockfish downloaded in the app A viewer of chess databases: PGN, ChessBase, archives. Files are only read, never changed. - Licenses + Licenses and authors Website and source code + + Game details + Copy PGN + Copy FEN + Share game + Copied + Notes + on + off + not downloaded + Found %1$s of %2$s + Game diff --git a/androidApp/app/src/main/res/values/themes.xml b/androidApp/app/src/main/res/values/themes.xml index f2372f3..5bbd611 100644 --- a/androidApp/app/src/main/res/values/themes.xml +++ b/androidApp/app/src/main/res/values/themes.xml @@ -1,5 +1,9 @@ - - + diff --git a/androidApp/app/src/main/res/xml/locales_config.xml b/androidApp/app/src/main/res/xml/locales_config.xml new file mode 100644 index 0000000..1052e83 --- /dev/null +++ b/androidApp/app/src/main/res/xml/locales_config.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/androidApp/scripts/release.sh b/androidApp/scripts/release.sh new file mode 100755 index 0000000..a2fd540 --- /dev/null +++ b/androidApp/scripts/release.sh @@ -0,0 +1,27 @@ +#!/usr/bin/env bash +# Builds the two signed release APKs into androidApp/dist: +# ChessPenguin--android.apk Stockfish built in ("full") +# ChessPenguin--android-noengine.apk Stockfish downloaded in the app ("light") +# The key comes from the environment or from ~/.config/chesspenguin/android/.env. +set -euo pipefail +cd "$(dirname "$0")/.." +env_file="${CP_SIGNING_ENV:-$HOME/.config/chesspenguin/android/.env}" +if [[ -z "${CP_KEYSTORE:-}" && -f "${env_file}" ]]; then + set -a + # shellcheck disable=SC1090 + source "${env_file}" + set +a +fi +: "${CP_KEYSTORE:?no release key: set CP_KEYSTORE and the passwords, or CP_SIGNING_ENV}" +./gradlew --console=plain assembleFullRelease assembleLightRelease +version="$(sed -n 's/^version = "\(.*\)"/\1/p' ../Cargo.toml | head -n1)" +mkdir -p dist +cp app/build/outputs/apk/full/release/app-full-release.apk "dist/ChessPenguin-${version}-android.apk" +cp app/build/outputs/apk/light/release/app-light-release.apk "dist/ChessPenguin-${version}-android-noengine.apk" +build_tools="$(ls -d "${ANDROID_HOME:-$HOME/Android/Sdk}"/build-tools/* | sort -V | tail -n1)" +for apk in dist/ChessPenguin-"${version}"-android*.apk; do + "${build_tools}/apksigner" verify "${apk}" + "${build_tools}/zipalign" -c -P 16 4 "${apk}" +done +(cd dist && sha256sum ChessPenguin-"${version}"-android*.apk > ChessPenguin-"${version}"-android.sha256) +ls -l dist diff --git a/crates/mobile-api/src/lib.rs b/crates/mobile-api/src/lib.rs index e8ea8cf..a3190b2 100644 --- a/crates/mobile-api/src/lib.rs +++ b/crates/mobile-api/src/lib.rs @@ -316,6 +316,11 @@ impl Database { } /// The game `index`, ready to show. + /// The game `index` as PGN text, as it is in the file (to copy or share). + pub fn pgn(&self, index: u32) -> Option { + self.db.raw_text(index as usize) + } + pub fn game(&self, index: u32) -> Result { let parsed = self .db @@ -499,6 +504,7 @@ mod tests { ] ); assert!(g.nodes[0].uci.is_empty()); + assert!(db.pgn(0).unwrap().contains("[%cal Ge2e4,Rd7d5]")); } #[test] diff --git a/docs/design/android-ui.md b/docs/design/android-ui.md index c7cafe0..7ddf44b 100644 --- a/docs/design/android-ui.md +++ b/docs/design/android-ui.md @@ -1,6 +1,6 @@ # ChessPenguin для Android: интерфейс -Статус: спецификация дизайнера для реализации, редакция 2 от 2026-10-22. Она учитывает решения владельца из `docs/decisions.md` §16: только просмотр, Android 12 и новее, две APK, базы до ~1 млн партий. Оставшиеся вопросы — в §16. Где спецификация расходится с ранними набросками и с `docs/research/android-stack.md` по интерфейсу, действует она. Стек — Kotlin + Jetpack Compose (Material 3). +Статус: спецификация дизайнера для реализации, редакция 2 от 2026-10-22, с правками после ревью первой реализации (§17). Она учитывает решения владельца из `docs/decisions.md` §16: только просмотр, Android 12 и новее, две APK, базы до ~1 млн партий. Оставшиеся вопросы — в §16. Где спецификация расходится с ранними набросками и с `docs/research/android-stack.md` по интерфейсу, действует она. Стек — Kotlin + Jetpack Compose (Material 3). Опирается на настольную версию: @@ -78,7 +78,7 @@ ``` - Приложение — одна активность; экраны лежат в стеке. «Назад» (жест или ← в верхней панели) всегда возвращает на шаг: Партия → Партии → Базы → выход. -- «Назад» сначала закрывает самое верхнее: клавиатуру → лист или меню → предпросмотр линии движка → поле поиска (запрос остаётся в силе) → экран. +- «Назад» сначала закрывает самое верхнее: клавиатуру → лист или меню → предпросмотр линии движка → поле поиска (вместе с запросом) → экран. - После возврата в «Партии» поиск, фильтры, сортировка и прокрутка остаются прежними. Строка последней просмотренной партии (в том числе открытой через ‹ ›) прокручивается в видимую часть и на 1 с подсвечивается. - Приложение всегда открывается на экране «Базы»: так ребёнок каждый раз начинает с понятного места. @@ -114,7 +114,8 @@ └────────────────────────────────────┘ ``` -- «Открыть примеры партий» добавляет две базы из `examples/` («Классические партии» и «Алехин») и открывает первую. Сами примеры при первом запуске не появляются: пусть человек сразу увидит, где добавлять своё. +- **Примеры уже в списке при первом запуске** — две базы из `examples/` («Классические партии» и «Алехин»), с именами на языке интерфейса, пока их не переименовали. Так приложение с первой секунды показывает, что умеет, а FAB «Добавить базу» виден сразу (правка после ревью: раньше примеры добавлялись кнопкой). +- Пустой экран появляется, только если человек убрал из списка всё. Тогда «Открыть примеры партий» возвращает примеры и открывает первый. - Кнопки FAB на пустом экране нет: главное действие и так в центре. ### 3.2. Список баз @@ -292,7 +293,9 @@ FAB открывает лист, а не сразу системный выбо - **Первая строка**, 16sp: «Белые – Чёрные». - Имя вида «Фамилия, Имя Отчество» сокращается до «Фамилия И.», остальные имена — как в файле. - Каждое имя обрезается многоточием и занимает не больше половины ширины, чтобы чёрные не пропадали. - - Справа колонка 40 dp с результатом, цифры моноширинные (`tnum`): `1-0`, `½-½`, `0-1`, `*`. + - Справа колонка 40 dp с результатом, цифры моноширинные (`tnum`): `1-0`, `½-½`, `0-1`. Результат стоит на линии первой строки (выравнивание по базовой линии), а не по центру строки 64 dp. + - Результат `*` (партия без итога, учебная позиция) не показывается: в учебниках это столбик звёздочек без смысла. + - Если у чёрных пусто или `?` (позиция из учебника, этюд), первая строка — только то, что записано у белых, без « – ?». Строка без второй строки выравнивается по центру по вертикали. - **Вторая строка**, 14sp цветом `onSurfaceVariant`: турнир · год · ECO. Пустые значения и `?` пропускаются вместе с точкой. Справа «✓», если партия уже просмотрена. - Эло, тур и число ходов на телефоне не показываются: они есть в «Сведениях», а на 360 dp им нет места без мелкого шрифта. - **Текстовая глава книги** (ChessBase): вместо результата значок «¶», первая строка — название главы, вторая — «Текст». Нажатие открывает режим чтения (§7.9). @@ -302,7 +305,7 @@ FAB открывает лист, а не сразу системный выбо - ⌕ раскрывает в верхней панели поле поиска (M3 search bar), клавиатура открывается сразу. Подсказка в поле: «Игрок, турнир, ECO, год». Поиск идёт по мере ввода, с задержкой 150 мс. - Вторая строка заголовка — «Найдено 34 из 1 248». Если ничего нет: «Ничего не найдено» и кнопка «Сбросить поиск». -- «Назад» закрывает поле, но запрос остаётся в силе. Под именем базы тогда видно «⌕ карлсен ✕»; ✕ сбрасывает запрос. +- «Назад» и ✕ закрывают поле и сбрасывают запрос (упрощение после ревью: состояние «запрос есть, поля нет» ребёнку непонятно). При возврате из «Партии» поиск остаётся открытым с тем же запросом. ### 6.4. Сортировка @@ -436,7 +439,8 @@ FAB открывает лист, а не сразу системный выбо - **Основная линия** — три колонки: номер хода 40 dp (`onSurfaceVariant`), затем ходы белых и чёрных поровну на остаток ширины. - Высота строки 48 dp; вся ячейка хода — зона нажатия. - Ходы 17sp. -- **Комментарий** — блок во всю ширину между строками (§10.4). Если комментарий стоит после хода белых, ход чёрных переносится на новую строку: `4. … Кf6`. +- **Комментарий** — блок во всю ширину между строками (§10.4). Если комментарий стоит после хода белых, ход чёрных переносится на новую строку: `4. … Кf6`. Многоточие ставится только в пустой ячейке белых; пустая ячейка чёрных в строке перед комментарием остаётся пустой. +- **Левый край.** Блок комментария и линия варианта начинаются в 16 dp от края экрана, как строки списков; текст в них — ещё через 12 dp. - **Вариант** — блок во всю ширину сплошным текстом: `4.d4 exd4 5.O-O Сe7 (5…Кxe4 6.Лe1)`. - Отступ 16 dp на каждый уровень вложенности, не больше трёх уровней. Слева вертикальная линия 2 dp цвета `outlineVariant`. - Комментарии внутри варианта набираются курсивом в той же строке. @@ -489,7 +493,8 @@ FAB открывает лист, а не сразу системный выбо ### 7.7. Верхняя панель и меню ⋮ - ← ведёт к «Партиям». -- Заголовок в две строки: «Белые – Чёрные» (фамилии, 18sp) и «12 из 340 · 1-0» (13sp). Касание заголовка открывает «Сведения». +- Заголовок в две строки: «Белые – Чёрные» (фамилии, 16sp, 500) и «12 из 340 · 1-0» (14sp, `onSurfaceVariant`). Результат `*` во второй строке не пишется. Касание заголовка открывает «Сведения». +- Справа в панели ровно три значка: ‹ › и ⋮. Настройки — пункт меню ⋮, отдельной шестерёнки на этом экране нет. - Меню ⋮: - «Сведения о партии»; - «Копировать PGN»; @@ -548,7 +553,7 @@ FAB открывает лист, а не сразу системный выбо - Сборка с движком поверх сборки без движка: при первом запуске скачанная нейросеть удаляется, место освобождается. - Сборка без движка поверх сборки с движком: движок снова предлагается скачать. - Технически в сборке «без движка» программа Stockfish (1–2 МБ) всё равно внутри, а скачивается его нейросеть (данные, не код; см. `android-stack.md` §5). Пользователь этого не видит: для него скачивается «движок». -- В «О программе» после версии указана сборка: «0.9.0 · Stockfish внутри» или «0.9.0 · Stockfish скачивается». +- В «О программе» после версии указана сборка теми же словами, что на сайте (§16): «0.9.0 · Stockfish уже внутри» или «0.9.0 · Stockfish скачивается в приложении». - **Подписи на сайте и в релизе на GitHub:** | Файл | RU | EN | @@ -566,18 +571,20 @@ FAB открывает лист, а не сразу системный выбо ``` │ ▐+0.4▌ гл.22 14.Кd5 Сxd5 15.exd5 … ▾│ ``` - - Плашка оценки 52 dp. При перевесе белых она светлая (`#F5F5F0`, текст `#1C1D1F`), при перевесе чёрных — тёмная (`#26282B`, текст `#E8E8E8`). Значения: «+0.4», «−1.2», «#3», «#−2», цифры моноширинные. + - Плашка оценки 56×28 dp, рамка 1 dp цвета `outline`, чтобы светлая плашка не сливалась со строкой. При перевесе белых она светлая (`#F5F5F0`, текст `#1C1D1F`), при перевесе чёрных — тёмная (`#26282B`, текст `#E8E8E8`). Значения: «+0.4», «−1.2», «#3», «#−2», цифры моноширинные. - По верхнему краю строки полоса 3 dp: доля белых слева, а при перевёрнутой доске справа. - Глубина «гл. 22» цветом `onSurfaceVariant`. - Лучшая линия — в записи ходов из настроек, хвост обрезается многоточием. - - ▾ раскрывает строку: до 3 линий по 40 dp, сколько задано в «Линий» (по умолчанию 2). Нотация при этом становится короче. ▴ сворачивает обратно. + - ▾ раскрывает строку: до 3 линий по 40 dp, сколько задано в «Линий» (по умолчанию 2). Нотация при этом становится короче. ▴ сворачивает обратно. ▾ остаётся и на паузе, рядом с «Глубже». + - Стрелка второй линии рисуется тем же цветом, но бледнее (прозрачность 35 % против 63 % у лучшей) — находка реализации. + - В сборке с движком при первом включении, пока движок распаковывается, на месте строки — «Готовлю движок…» с маленьким индикатором. - На телефоне в портрете вертикальной шкалы оценки нет: она отняла бы ширину у доски. В альбомной ориентации и на планшете шкала 12 dp стоит слева от доски, как на компьютере. ### 8.3. Правила - **Новая позиция — пустая строка.** При любом переходе строка показывает «Считаю…» и пустую плашку, пока движок не ответит про новую позицию. Старая оценка не показывается ни на миг. - **Предпросмотр линии.** - - Касание линии показывает на доске её первый ход. Над нотацией появляется полоса «Линия движка · ход 1 из 12 [✕]». + - Касание линии показывает на доске её первый ход. Над нотацией появляется полоса 48 dp «Линия движка · ход 1 из 12 [✕]» (фон `primaryContainer`, текст `onPrimaryContainer`). Показанный ход подсвечивается в тексте линии заливкой текущего хода. - Пока полоса видна, ◀ ▶ листают эту линию, а ⏮ возвращает к позиции партии. - Из предпросмотра выводят ✕, «назад» и касание хода в нотации. - Партия при этом не меняется. Вставить линию как вариант в первой версии нельзя. @@ -634,12 +641,49 @@ FAB открывает лист, а не сразу системный выбо - Если загрузка не закончена, кнопка «Движок» открывает лист с её состоянием. Строка движка в партии не появляется, пока движок не готов. - В Настройках у скачанного движка строка «Stockfish 19 · скачан» и пункт «Удалить движок (освободит 80 МБ)», с подтверждением: «Удалить движок? Его можно скачать снова.» — «Отмена» / «Удалить». +- Все размеры в листе, в настройках и в ошибках берутся из сборки (`{size}`, сейчас 98 МБ), а не пишутся числом 80. - Источник файла и его сумма закреплены в приложении. Это решение разработчика, как в `engine-download.md`; в интерфейсе адрес не показывается. ## 9. Настройки Настройки — один экран со списком групп, без вкладок. Изменения применяются сразу. +**Первая версия** (выбора досок и фигур нет, §16; звука пока нет): + +``` +┌────────────────────────────────────┐ +│ ← Настройки │ +├────────────────────────────────────┤ +│ ВНЕШНИЙ ВИД │ +│ Тема │ +│ Как в системе │ +│ Язык │ +│ Как в системе │ +├────────────────────────────────────┤ +│ ПАРТИЯ │ +│ Запись ходов │ +│ Латинские буквы (K Q R B N) │ +│ Анимация фигур [●] │ +│ Стрелка лучшего хода [●] │ +│ Вибрация [●] │ +├────────────────────────────────────┤ +│ ДВИЖОК │ +│ Stockfish 19 · встроен │ 14sp, onSurfaceVariant, без нажатия +│ Линий 2 │ +│ Время на позицию 20 с │ +│ Дополнительно │ Потоки, Память — диалог или подэкран +│ Движок расходует заряд. Он сам │ +│ останавливается, когда гаснет экран.│ +├────────────────────────────────────┤ +│ О программе │ +└────────────────────────────────────┘ +``` + +- Группа называется «Партия» (`s_game_group`, en «Game»): запись ходов, анимация, стрелка и вибрация относятся к просмотру партии, а не к доске. +- Строка «Stockfish 19 · встроен» — состояние, а не пункт: набирается 14sp цветом `onSurfaceVariant`, чтобы не выглядеть нажимаемой. + +Полная схема на будущее (с выбором досок и фигур): + ``` ┌────────────────────────────────────┐ │ ← Настройки │ @@ -681,6 +725,7 @@ FAB открывает лист, а не сразу системный выбо - **Цвета обоев** — §10.3. - **Язык:** «Как в системе» и шесть языков компьютера (English, Русский, Français, Deutsch, Español, Italiano). Язык задаётся через `AppCompatDelegate.setApplicationLocales`: на Android 13+ тот же выбор виден в системных настройках приложения, на Android 12 работает внутри приложения. Если язык системы не из этих шести, интерфейс на английском. - **Движок → Дополнительно:** «Потоки» — от 1 до числа ядер, по умолчанию половина, но не больше 4. «Память» — 16, 32, 64, 128 или 256 МБ, по умолчанию 64. +- «Скачать» в настройках открывает тот же лист «Движок Stockfish» (§8.4), а не начинает загрузку молча: в листе есть предупреждение о мобильном интернете и отмена. - Строка состояния движка зависит от сборки и §8.4: «Stockfish 19 · встроен», «Не скачан · Скачать (80 МБ)», «Скачивается… 23 из 80 МБ» или «Stockfish 19 · скачан» с пунктом «Удалить движок». ## 10. Внешний вид @@ -705,7 +750,7 @@ FAB открывает лист, а не сразу системный выбо | Роль | Где | sp | |---|---|---| | `titleLarge` | заголовки экранов, листов, пустых состояний | 22 / 28 / 400 | -| заголовок партии, 1-я строка | верхняя панель «Партии» | 18 / 24 / 500 | +| заголовок партии, 1-я строка | верхняя панель «Партия» (`titleMedium`) | 16 / 24 / 500 | | `bodyLarge` | имя базы, строка партии, пункты настроек | 16 / 24 / 400 | | `bodyMedium` | вторые строки, подписи | 14 / 20 / 400 | | `labelLarge` | кнопки, чипы | 14 / 20 / 500 | @@ -745,7 +790,9 @@ FAB открывает лист, а не сразу системный выбо | `errorContainer` | `#FCE4E1` | `#5C1A14` | | текущий ход (заливка) | `#90D1FF` | `#005C80` | | текст комментария | `#2A5B8A` | `#9EC4E0` | -| NAG `!` `?` `!!` `??` `!?` `?!` | цвета `assessment_color`, одинаковые в обеих темах | +| NAG `!` `?` `!!` `??` `!?` `?!` | `#4E7F22` `#A35F00` `#12806F` `#C23B3B` `#B0259F` `#1F72A8` | цвета `assessment_color` (Lichess): `#629C2E` `#E68F00` `#22AC9A` `#DF5353` `#EA45D8` `#56B4E9` | + +Цвета Lichess на белом фоне дают контраст 2,3–3,8:1, поэтому в светлой теме те же оттенки затемнены до 4,8–5,8:1. На заливке текущего хода значок NAG набирается цветом текста хода (`onSurface`): цветной значок на голубой заливке не читается ни в одной теме (1,4–3,2:1). Контраст текста и фона не ниже 4,5:1, включая `onSurfaceVariant` и цвет комментария. Разработчик проверяет это на обеих темах. @@ -777,7 +824,7 @@ FAB открывает лист, а не сразу системный выбо | Действие | Symbol | |---|---| | назад по экрану | `arrow_back` | -| ход назад / вперёд | `arrow_left` / `arrow_right` (залитые треугольники) | +| ход назад / вперёд | `play_arrow`, для «назад» отражённый (залитые треугольники 32 dp). `arrow_left`/`arrow_right` слишком узкие: даже в 44 dp треугольник около 9×14 dp и выглядит слабее ⏮ ⏭ | | в начало / в конец линии | `first_page` / `last_page` | | предыдущая / следующая партия | `chevron_left` / `chevron_right` (тонкие уголки, только в верхней панели) | | перевернуть доску | `swap_vert` | @@ -1066,6 +1113,7 @@ FAB открывает лист, а не сразу системный выбо | `prev_game` / `next_game` | Предыдущая партия / Следующая партия | Previous game / Next game | | `nav_start` / `nav_back` / `nav_fwd` / `nav_end` | В начало / Назад / Вперёд / В конец линии | To start / Back / Forward / To the end of the line | | `flip` | Перевернуть доску | Flip board | +| `eng_state_on` / `eng_state_off` / `eng_state_missing` | включён / выключен / не скачан | on / off / not downloaded | | `next_moves` | Дальше: | Next: | | `board_hint` | Это просмотр партии. Ходы листаются кнопками ◀ ▶ внизу. | This is a game viewer. Step through the moves with ◀ ▶ below. | | `menu_info` | Сведения о партии | Game details | @@ -1088,7 +1136,8 @@ FAB открывает лист, а не сразу системный выбо |---|---|---| | `engine` | Движок | Engine | | `eng_thinking` | Считаю… | Thinking… | -| `eng_depth` / `eng_paused` | гл. {d} / гл. {d} · пауза | d {d} / d {d} · paused | +| `eng_depth` / `eng_paused` | гл. {d} / гл. {d} · пауза | depth {d} / depth {d} · paused | +| `eng_preparing` | Готовлю движок… | Preparing the engine… | | `eng_deeper` | Глубже | Deeper | | `eng_preview` | Линия движка · ход {i} из {n} | Engine line · move {i} of {n} | | `eng_saver` | Экономия заряда: движок работает медленнее | Battery saver: the engine runs slower | @@ -1115,7 +1164,7 @@ FAB открывает лист, а не сразу системный выбо | Ключ | RU | EN | |---|---|---| -| `s_board_group` / `s_sound_group` / `s_look_group` / `s_engine_group` | Доска / Звук и отклик / Внешний вид / Движок | Board / Sound and feedback / Appearance / Engine | +| `s_board_group` / `s_sound_group` / `s_look_group` / `s_engine_group` / `s_game_group` | Доска / Звук и отклик / Внешний вид / Движок / Партия | Board / Sound and feedback / Appearance / Engine / Game | | `s_board` / `s_pieces` | Доска / Фигуры | Board / Pieces | | `s_notation` | Запись ходов | Move notation | | `s_latin` / `s_figurine` / `s_local` | Латинские буквы (K Q R B N) / Фигурки / Русские буквы (Кр Ф Л С К) | Letters (K Q R B N) / Figurines / — (не показывается в английском) | @@ -1130,7 +1179,7 @@ FAB открывает лист, а не сразу системный выбо | `s_time_inf` | Без ограничения | No limit | | `s_battery` | Движок расходует заряд. Он сам останавливается, когда гаснет экран. | The engine uses battery. It stops by itself when the screen turns off. | | `s_about` | О программе | About | -| `about_version_full` / `about_version_light` | {v} · Stockfish внутри / {v} · Stockfish скачивается | {v} · Stockfish built in / {v} · Stockfish downloaded | +| `about_version_full` / `about_version_light` | {v} · Stockfish уже внутри / {v} · Stockfish скачивается в приложении | {v} · Stockfish built in / {v} · Stockfish downloaded in the app | | `about_licenses` | Лицензии и авторы | Licenses and authors | ## 15. Первая версия и дальше @@ -1176,3 +1225,20 @@ FAB открывает лист, а не сразу системный выбо 1. Тема по умолчанию — «Как в системе». 2. Зелёная доска и Merida — для всех. **В первой версии выбора досок, фигур и тем нет** (раздел настроек «Доска» откладывается); возможность менять их — задача следующих версий. 3. Подписи сборок: «Stockfish уже внутри · ≈ 95 МБ» и «Stockfish скачивается в приложении · ≈ 15 МБ» (en «Stockfish built in» / «Stockfish downloaded in the app»). + +## 17. Ревью первой реализации (2026-10-22) + +Что изменено в этой спецификации по итогам ревью `androidApp/` (этап 1) и снимков с эмулятора: + +- §3.1 — примеры в списке с первого запуска (как сделано в реализации), пустой экран — только когда список очищен. +- §2.1, §6.3 — «назад» закрывает поиск вместе с запросом. +- §6.2 — результат `*` не показывается; результат на линии первой строки; без « – ?» у пустых чёрных. +- §7.3 — многоточие только в пустой ячейке белых; левый край блоков 16 dp. +- §7.7, §10.2 — заголовок партии 16sp/500 и 14sp; в верхней панели ‹ › ⋮, настройки — в меню. +- §8.1, §14.6 — подпись сборки в «О программе» словами владельца. +- §8.2, §8.3 — плашка 56×28 с рамкой `outline`; ▾ остаётся на паузе; бледная стрелка второй линии; «Готовлю движок…»; полоса предпросмотра 48 dp и подсветка хода в линии. +- §8.4, §9 — размер из сборки; «Скачать» в настройках открывает лист; схема настроек первой версии с группой «Партия». +- §10.3 — тёмные варианты цветов NAG для светлой темы; NAG на заливке текущего хода цветом текста. +- §10.6 — ◀ ▶ значком `play_arrow` 32 dp. +- §14.4, §14.5 — состояния кнопки «Движок» для TalkBack, «depth» вместо «d» в английском. + diff --git a/website/server/src/main.rs b/website/server/src/main.rs index cf75177..c321a03 100644 --- a/website/server/src/main.rs +++ b/website/server/src/main.rs @@ -37,6 +37,9 @@ pub const PLATFORMS: &[(&str, &str)] = &[ ("appimage", ".AppImage"), ("flatpak", ".flatpak"), ("tarball", "-linux-x86_64.tar.gz"), + // Android: Stockfish built in, and Stockfish downloaded in the app. + ("android", "-android.apk"), + ("android-noengine", "-android-noengine.apk"), ("checksums", "SHA256SUMS.txt"), ]; diff --git a/website/server/src/site.rs b/website/server/src/site.rs index cfd8f6a..9e4b811 100644 --- a/website/server/src/site.rs +++ b/website/server/src/site.rs @@ -230,7 +230,7 @@ impl Site { "@context": "https://schema.org", "@type": "SoftwareApplication", "name": "ChessPenguin", - "operatingSystem": "Windows, macOS, Linux", + "operatingSystem": "Windows, macOS, Linux, Android", "applicationCategory": "GameApplication", "license": "https://www.gnu.org/licenses/gpl-3.0.html", "softwareVersion": release.map(|r| r.version.clone()), diff --git a/website/site/i18n/de.json b/website/site/i18n/de.json index 04478eb..784126e 100644 --- a/website/site/i18n/de.json +++ b/website/site/i18n/de.json @@ -1,6 +1,6 @@ { - "meta_title": "ChessPenguin — kostenloses Programm für Schachdatenbanken unter Windows, macOS und Linux", - "meta_description": "Kostenloses Open-Source-Programm für Schachdatenbanken. Öffnen Sie PGN-Dateien und ChessBase-Datenbanken, lesen Sie kommentierte Partien und analysieren Sie sie mit Stockfish. Für Windows, macOS und Linux.", + "meta_title": "ChessPenguin — kostenloses Programm für Schachdatenbanken unter Windows, macOS, Linux und Android", + "meta_description": "Kostenloses Open-Source-Programm für Schachdatenbanken. Öffnen Sie PGN-Dateien und ChessBase-Datenbanken, lesen Sie kommentierte Partien und analysieren Sie sie mit Stockfish. Für Windows, macOS, Linux und Android.", "skip": "Zum Inhalt", "nav_label": "Abschnitte", "nav_screenshots": "Screenshots", @@ -9,7 +9,7 @@ "nav_support": "Support", "language": "Sprache", "header_download": "Download", - "hero_title": "Das kostenlose Programm für Schachdatenbanken unter Windows, macOS und Linux", + "hero_title": "Das kostenlose Programm für Schachdatenbanken unter Windows, macOS, Linux und Android", "hero_subtitle": "Öffnen Sie PGN-Dateien und ChessBase-Datenbanken, lesen Sie kommentierte Partien und analysieren Sie sie mit Stockfish. Schnell, nativ und Open Source.", "btn_windows": "Für Windows herunterladen", "btn_macos": "Für macOS herunterladen", @@ -26,7 +26,7 @@ "mac_requires": "Erfordert einen Mac mit Apple-Chip (M1 oder neuer) und macOS 11 oder neuer.", "mac_intel_warning": "Dieser Mac scheint einen Intel-Prozessor zu haben. Die aktuelle Version läuft nur auf Apple-Chips.", "chromeos": "für Linux unter ChromeOS", - "mobile_text": "ChessPenguin ist ein Programm für Computer mit Windows, macOS oder Linux. Öffnen Sie diese Seite auf Ihrem Computer, um es herunterzuladen.", + "mobile_text": "ChessPenguin läuft unter Windows, macOS, Linux und Android. Für iPhone und iPad gibt es noch keine Version — öffnen Sie diese Seite auf Ihrem Computer.", "share_link": "Link teilen", "copy_link": "Link kopieren", "link_copied": "Link kopiert", @@ -163,5 +163,16 @@ "alt12": "Das Fenster Lichess und Chess.com: ein auf beiden Seiten gefundener Nickname mit der Zahl der Partien, bereit zum Herunterladen in eine Datenbank.", "shot12": "Partien beliebiger Spieler von Lichess und Chess.com, nach Nickname, in einer Datenbank.", "alt13": "Brett- und Figureneinstellungen im hellen Design: Figurensätze, Zugnotation und Bretter, das gewählte Brett hinter dem Fenster.", - "shot13": "Ganz nach Ihrem Geschmack: 17 Figurensätze, 37 Bretter, Züge in Buchstaben oder Figurinen, Figurenanimation, dunkles und helles Design." + "shot13": "Ganz nach Ihrem Geschmack: 17 Figurensätze, 37 Bretter, Züge in Buchstaben oder Figurinen, Figurenanimation, dunkles und helles Design.", + "btn_android": "Für Android herunterladen", + "and_requires": "Benötigt Android 12 oder neuer.", + "and_intro": "Zwei Varianten derselben App: Datenbanken und Partien ansehen, Züge durchblättern und mit Stockfish analysieren. Die App liest Ihre Dateien nur.", + "and_full_title": "Stockfish eingebaut", + "and_full_text": "Bewertung und beste Züge sofort, ohne Internet.", + "and_light_title": "Stockfish wird in der App geladen", + "and_light_text": "Eine kleinere Datei; die Engine (98 MB) wird in der App geladen, wenn Sie sie brauchen.", + "and_step1": "Öffnen Sie die heruntergeladene Datei auf dem Telefon.", + "and_step2": "Wenn Android fragt, erlauben Sie die Installation von Apps aus dem Browser oder Dateimanager.", + "and_note": "Benötigt Android 12 oder neuer. Jede Variante lässt sich über die andere installieren; Datenbanken und Einstellungen bleiben erhalten.", + "next_android": "Öffnen Sie die Datei auf dem Telefon und erlauben Sie die Installation, wenn Android fragt." } diff --git a/website/site/i18n/en.json b/website/site/i18n/en.json index 4f551a8..440aa0a 100644 --- a/website/site/i18n/en.json +++ b/website/site/i18n/en.json @@ -1,6 +1,6 @@ { - "meta_title": "ChessPenguin — free chess database software for Windows, macOS and Linux", - "meta_description": "Free, open-source program for chess databases. Open PGN files and ChessBase databases, read annotated games and analyse them with Stockfish. For Windows, macOS and Linux.", + "meta_title": "ChessPenguin — free chess database software for Windows, macOS, Linux and Android", + "meta_description": "Free, open-source program for chess databases. Open PGN files and ChessBase databases, read annotated games and analyse them with Stockfish. For Windows, macOS, Linux and Android.", "skip": "Skip to content", "nav_label": "Sections", "nav_screenshots": "Screenshots", @@ -9,7 +9,7 @@ "nav_support": "Support", "language": "Language", "header_download": "Download", - "hero_title": "Free chess database software for Windows, macOS and Linux", + "hero_title": "Free chess database software for Windows, macOS, Linux and Android", "hero_subtitle": "Open PGN and ChessBase files, read annotated games, and analyse them with Stockfish. Fast, native and open source.", "btn_windows": "Download for Windows", "btn_macos": "Download for macOS", @@ -26,7 +26,7 @@ "mac_requires": "Requires a Mac with Apple silicon (M1 or later) and macOS 11 or later.", "mac_intel_warning": "This Mac seems to have an Intel processor. The current build runs only on Apple silicon.", "chromeos": "for Linux on ChromeOS", - "mobile_text": "ChessPenguin is a desktop app for Windows, macOS and Linux. Open this page on your computer to download it.", + "mobile_text": "ChessPenguin runs on Windows, macOS, Linux and Android. There is no iPhone or iPad version yet — open this page on your computer.", "share_link": "Share link", "copy_link": "Copy link", "link_copied": "Link copied", @@ -163,5 +163,16 @@ "alt12": "The Lichess and Chess.com window: a nickname found on both sites, with the number of games, ready to download into one database.", "shot12": "Anyone's games from Lichess and Chess.com, by nickname, in one database.", "alt13": "Board and piece settings in the light theme: piece sets, move notation and boards, the chosen board behind the window.", - "shot13": "Make it yours: 17 piece sets, 37 boards, moves in letters or figurines, piece animation, dark and light themes." + "shot13": "Make it yours: 17 piece sets, 37 boards, moves in letters or figurines, piece animation, dark and light themes.", + "btn_android": "Download for Android", + "and_requires": "Requires Android 12 or newer.", + "and_intro": "Two builds of one app: browse databases and games, step through the moves and analyse them with Stockfish. The app only reads your files.", + "and_full_title": "Stockfish built in", + "and_full_text": "Evaluation and best moves right away, no internet needed.", + "and_light_title": "Stockfish downloaded in the app", + "and_light_text": "A smaller file; the engine (98 MB) is downloaded in the app when you need it.", + "and_step1": "Open the downloaded file on your phone.", + "and_step2": "If Android asks, allow installing apps from your browser or file manager.", + "and_note": "Requires Android 12 or newer. Either build installs over the other; databases and settings are kept.", + "next_android": "Open the file on your phone and allow the installation if Android asks." } diff --git a/website/site/i18n/es.json b/website/site/i18n/es.json index 704aacd..eb3194e 100644 --- a/website/site/i18n/es.json +++ b/website/site/i18n/es.json @@ -1,6 +1,6 @@ { - "meta_title": "ChessPenguin — programa gratuito para bases de datos de ajedrez en Windows, macOS y Linux", - "meta_description": "Programa gratuito y de código abierto para bases de datos de ajedrez. Abre archivos PGN y bases de ChessBase, lee partidas comentadas y analízalas con Stockfish. Para Windows, macOS y Linux.", + "meta_title": "ChessPenguin — programa gratuito para bases de datos de ajedrez en Windows, macOS, Linux y Android", + "meta_description": "Programa gratuito y de código abierto para bases de datos de ajedrez. Abre archivos PGN y bases de ChessBase, lee partidas comentadas y analízalas con Stockfish. Para Windows, macOS, Linux y Android.", "skip": "Ir al contenido", "nav_label": "Secciones", "nav_screenshots": "Capturas", @@ -9,7 +9,7 @@ "nav_support": "Soporte", "language": "Idioma", "header_download": "Descargar", - "hero_title": "El programa gratuito para bases de datos de ajedrez en Windows, macOS y Linux", + "hero_title": "El programa gratuito para bases de datos de ajedrez en Windows, macOS, Linux y Android", "hero_subtitle": "Abre archivos PGN y bases de ChessBase, lee partidas comentadas y analízalas con Stockfish. Rápida, nativa y de código abierto.", "btn_windows": "Descargar para Windows", "btn_macos": "Descargar para macOS", @@ -26,7 +26,7 @@ "mac_requires": "Requiere un Mac con chip de Apple (M1 o posterior) y macOS 11 o posterior.", "mac_intel_warning": "Este Mac parece tener un procesador Intel. La versión actual solo funciona en chips de Apple.", "chromeos": "para Linux en ChromeOS", - "mobile_text": "ChessPenguin es una aplicación para ordenadores con Windows, macOS o Linux. Abre esta página en tu ordenador para descargarla.", + "mobile_text": "ChessPenguin funciona en Windows, macOS, Linux y Android. Todavía no hay versión para iPhone ni iPad: abre esta página en tu ordenador.", "share_link": "Compartir enlace", "copy_link": "Copiar enlace", "link_copied": "Enlace copiado", @@ -163,5 +163,16 @@ "alt12": "La ventana de Lichess y Chess.com: un nombre encontrado en los dos sitios, con el número de partidas, listo para descargar en una base.", "shot12": "Las partidas de cualquier jugador de Lichess y Chess.com, por su nombre, en una sola base.", "alt13": "Ajustes de tablero y piezas en el tema claro: juegos de piezas, notación de jugadas y tableros, con el tablero elegido detrás de la ventana.", - "shot13": "A tu gusto: 17 juegos de piezas, 37 tableros, jugadas con letras o figuras, animación de piezas, temas oscuro y claro." + "shot13": "A tu gusto: 17 juegos de piezas, 37 tableros, jugadas con letras o figuras, animación de piezas, temas oscuro y claro.", + "btn_android": "Descargar para Android", + "and_requires": "Requiere Android 12 o posterior.", + "and_intro": "Dos versiones de la misma aplicación: explora bases y partidas, recorre las jugadas y analízalas con Stockfish. La aplicación solo lee tus archivos.", + "and_full_title": "Stockfish incluido", + "and_full_text": "Evaluación y mejores jugadas al instante, sin internet.", + "and_light_title": "Stockfish se descarga en la aplicación", + "and_light_text": "Un archivo más pequeño; el motor (98 MB) se descarga en la aplicación cuando lo necesites.", + "and_step1": "Abre el archivo descargado en tu teléfono.", + "and_step2": "Si Android lo pide, permite instalar aplicaciones desde el navegador o el gestor de archivos.", + "and_note": "Requiere Android 12 o posterior. Cada versión se instala sobre la otra; las bases y los ajustes se conservan.", + "next_android": "Abre el archivo en tu teléfono y permite la instalación si Android lo pide." } diff --git a/website/site/i18n/fr.json b/website/site/i18n/fr.json index a959846..7246a40 100644 --- a/website/site/i18n/fr.json +++ b/website/site/i18n/fr.json @@ -1,6 +1,6 @@ { - "meta_title": "ChessPenguin — logiciel gratuit pour bases de données d'échecs sur Windows, macOS et Linux", - "meta_description": "Logiciel gratuit et open source pour les bases de données d'échecs. Ouvrez des fichiers PGN et des bases ChessBase, lisez des parties commentées et analysez-les avec Stockfish. Pour Windows, macOS et Linux.", + "meta_title": "ChessPenguin — logiciel gratuit pour bases de données d'échecs sur Windows, macOS, Linux et Android", + "meta_description": "Logiciel gratuit et open source pour les bases de données d'échecs. Ouvrez des fichiers PGN et des bases ChessBase, lisez des parties commentées et analysez-les avec Stockfish. Pour Windows, macOS, Linux et Android.", "skip": "Aller au contenu", "nav_label": "Sections", "nav_screenshots": "Captures", @@ -9,7 +9,7 @@ "nav_support": "Assistance", "language": "Langue", "header_download": "Télécharger", - "hero_title": "Le logiciel gratuit pour vos bases d'échecs, sur Windows, macOS et Linux", + "hero_title": "Le logiciel gratuit pour vos bases d'échecs, sur Windows, macOS, Linux et Android", "hero_subtitle": "Ouvrez des fichiers PGN et des bases ChessBase, lisez des parties commentées et analysez-les avec Stockfish. Rapide, natif et open source.", "btn_windows": "Télécharger pour Windows", "btn_macos": "Télécharger pour macOS", @@ -26,7 +26,7 @@ "mac_requires": "Nécessite un Mac avec puce Apple (M1 ou plus récent) et macOS 11 ou plus récent.", "mac_intel_warning": "Ce Mac semble avoir un processeur Intel. La version actuelle ne fonctionne que sur les puces Apple.", "chromeos": "pour Linux sur ChromeOS", - "mobile_text": "ChessPenguin est une application pour ordinateur sous Windows, macOS ou Linux. Ouvrez cette page sur votre ordinateur pour la télécharger.", + "mobile_text": "ChessPenguin fonctionne sous Windows, macOS, Linux et Android. Il n'existe pas encore de version pour iPhone et iPad — ouvrez cette page sur votre ordinateur.", "share_link": "Partager le lien", "copy_link": "Copier le lien", "link_copied": "Lien copié", @@ -163,5 +163,16 @@ "alt12": "La fenêtre Lichess et Chess.com : un pseudo trouvé sur les deux sites, avec le nombre de parties, prêt à être téléchargé dans une base.", "shot12": "Les parties de n'importe quel joueur sur Lichess et Chess.com, par pseudo, dans une seule base.", "alt13": "Réglages de l'échiquier et des pièces en thème clair : jeux de pièces, notation des coups et échiquiers, l'échiquier choisi derrière la fenêtre.", - "shot13": "À votre goût : 17 jeux de pièces, 37 échiquiers, coups en lettres ou en figurines, animation des pièces, thèmes sombre et clair." + "shot13": "À votre goût : 17 jeux de pièces, 37 échiquiers, coups en lettres ou en figurines, animation des pièces, thèmes sombre et clair.", + "btn_android": "Télécharger pour Android", + "and_requires": "Android 12 ou plus récent requis.", + "and_intro": "Deux versions d'une même application : parcourez vos bases et vos parties, faites défiler les coups et analysez-les avec Stockfish. L'application ne fait que lire vos fichiers.", + "and_full_title": "Stockfish intégré", + "and_full_text": "Évaluation et meilleurs coups tout de suite, sans internet.", + "and_light_title": "Stockfish téléchargé dans l'application", + "and_light_text": "Un fichier plus petit ; le moteur (98 Mo) se télécharge dans l'application quand vous en avez besoin.", + "and_step1": "Ouvrez le fichier téléchargé sur votre téléphone.", + "and_step2": "Si Android le demande, autorisez l'installation d'applications depuis votre navigateur ou votre gestionnaire de fichiers.", + "and_note": "Android 12 ou plus récent requis. Chaque version s'installe par-dessus l'autre ; les bases et les réglages sont conservés.", + "next_android": "Ouvrez le fichier sur votre téléphone et autorisez l'installation si Android le demande." } diff --git a/website/site/i18n/it.json b/website/site/i18n/it.json index 9b463cb..a822374 100644 --- a/website/site/i18n/it.json +++ b/website/site/i18n/it.json @@ -1,6 +1,6 @@ { - "meta_title": "ChessPenguin — programma gratuito per database di scacchi su Windows, macOS e Linux", - "meta_description": "Programma gratuito e open source per database di scacchi. Apri file PGN e database ChessBase, leggi partite commentate e analizzale con Stockfish. Per Windows, macOS e Linux.", + "meta_title": "ChessPenguin — programma gratuito per database di scacchi su Windows, macOS, Linux e Android", + "meta_description": "Programma gratuito e open source per database di scacchi. Apri file PGN e database ChessBase, leggi partite commentate e analizzale con Stockfish. Per Windows, macOS, Linux e Android.", "skip": "Vai al contenuto", "nav_label": "Sezioni", "nav_screenshots": "Screenshot", @@ -9,7 +9,7 @@ "nav_support": "Supporto", "language": "Lingua", "header_download": "Scarica", - "hero_title": "Il programma gratuito per database di scacchi su Windows, macOS e Linux", + "hero_title": "Il programma gratuito per database di scacchi su Windows, macOS, Linux e Android", "hero_subtitle": "Apri file PGN e database ChessBase, leggi partite commentate e analizzale con Stockfish. Veloce, nativo e open source.", "btn_windows": "Scarica per Windows", "btn_macos": "Scarica per macOS", @@ -26,7 +26,7 @@ "mac_requires": "Richiede un Mac con chip Apple (M1 o successivo) e macOS 11 o successivo.", "mac_intel_warning": "Questo Mac sembra avere un processore Intel. La versione attuale funziona solo sui chip Apple.", "chromeos": "per Linux su ChromeOS", - "mobile_text": "ChessPenguin è un'app per computer con Windows, macOS o Linux. Apri questa pagina sul computer per scaricarla.", + "mobile_text": "ChessPenguin funziona su Windows, macOS, Linux e Android. Non c'è ancora una versione per iPhone e iPad: apri questa pagina sul computer.", "share_link": "Condividi il link", "copy_link": "Copia il link", "link_copied": "Link copiato", @@ -163,5 +163,16 @@ "alt12": "La finestra Lichess e Chess.com: un nickname trovato su entrambi i siti, con il numero di partite, pronto da scaricare in un database.", "shot12": "Le partite di qualsiasi giocatore da Lichess e Chess.com, per nickname, in un unico database.", "alt13": "Impostazioni di scacchiera e pezzi nel tema chiaro: set di pezzi, notazione delle mosse e scacchiere, con la scacchiera scelta dietro la finestra.", - "shot13": "Come piace a te: 17 set di pezzi, 37 scacchiere, mosse in lettere o figurine, animazione dei pezzi, tema scuro e chiaro." + "shot13": "Come piace a te: 17 set di pezzi, 37 scacchiere, mosse in lettere o figurine, animazione dei pezzi, tema scuro e chiaro.", + "btn_android": "Scarica per Android", + "and_requires": "Richiede Android 12 o successivo.", + "and_intro": "Due versioni della stessa app: sfoglia database e partite, scorri le mosse e analizzale con Stockfish. L'app legge soltanto i tuoi file.", + "and_full_title": "Stockfish incluso", + "and_full_text": "Valutazione e mosse migliori subito, senza internet.", + "and_light_title": "Stockfish si scarica nell'app", + "and_light_text": "Un file più piccolo; il motore (98 MB) si scarica nell'app quando serve.", + "and_step1": "Apri il file scaricato sul telefono.", + "and_step2": "Se Android lo chiede, consenti l'installazione di app dal browser o dal file manager.", + "and_note": "Richiede Android 12 o successivo. Ciascuna versione si installa sopra l'altra; database e impostazioni restano.", + "next_android": "Apri il file sul telefono e consenti l'installazione se Android lo chiede." } diff --git a/website/site/i18n/ru.json b/website/site/i18n/ru.json index 6cc5a47..8df2889 100644 --- a/website/site/i18n/ru.json +++ b/website/site/i18n/ru.json @@ -1,6 +1,6 @@ { - "meta_title": "ChessPenguin — бесплатная программа для работы с шахматными базами на Windows, macOS и Linux", - "meta_description": "Бесплатная программа с открытым кодом для работы с шахматными базами. Открывайте PGN и базы ChessBase, читайте аннотированные партии и анализируйте их со Stockfish. Для Windows, macOS и Linux.", + "meta_title": "ChessPenguin — бесплатная программа для работы с шахматными базами на Windows, macOS, Linux и Android", + "meta_description": "Бесплатная программа с открытым кодом для работы с шахматными базами. Открывайте PGN и базы ChessBase, читайте аннотированные партии и анализируйте их со Stockfish. Для Windows, macOS, Linux и Android.", "skip": "К содержимому", "nav_label": "Разделы", "nav_screenshots": "Скриншоты", @@ -9,7 +9,7 @@ "nav_support": "Поддержка", "language": "Язык", "header_download": "Скачать", - "hero_title": "Бесплатная программа для работы с шахматными базами на Windows, macOS и Linux", + "hero_title": "Бесплатная программа для работы с шахматными базами на Windows, macOS, Linux и Android", "hero_subtitle": "Открывайте PGN и базы ChessBase, читайте аннотированные партии и анализируйте их со Stockfish. Быстро, нативно и с открытым кодом.", "btn_windows": "Скачать для Windows", "btn_macos": "Скачать для macOS", @@ -26,7 +26,7 @@ "mac_requires": "Нужен Mac с процессором Apple (M1 или новее) и macOS 11 или новее.", "mac_intel_warning": "Похоже, в этом Mac процессор Intel. Текущая сборка работает только на процессорах Apple.", "chromeos": "для Linux в ChromeOS", - "mobile_text": "ChessPenguin — программа для компьютера с Windows, macOS или Linux. Откройте эту страницу на компьютере, чтобы скачать её.", + "mobile_text": "ChessPenguin работает на Windows, macOS, Linux и Android. Для iPhone и iPad версии пока нет — откройте эту страницу на компьютере.", "share_link": "Поделиться ссылкой", "copy_link": "Скопировать ссылку", "link_copied": "Ссылка скопирована", @@ -163,5 +163,16 @@ "alt12": "Окно Lichess и Chess.com: ник найден на обоих сайтах, видно число партий, их можно скачать в одну базу.", "shot12": "Партии любого игрока с Lichess и Chess.com по нику — в одну базу.", "alt13": "Настройки досок и фигур в светлой теме: наборы фигур, запись ходов и доски, за окном — выбранная доска.", - "shot13": "Под себя: 17 наборов фигур, 37 досок, ходы буквами или фигурками, анимация фигур, тёмная и светлая темы." + "shot13": "Под себя: 17 наборов фигур, 37 досок, ходы буквами или фигурками, анимация фигур, тёмная и светлая темы.", + "btn_android": "Скачать для Android", + "and_requires": "Нужен Android 12 или новее.", + "and_intro": "Две сборки одного приложения: смотрите базы и партии, листайте ходы и анализируйте их со Stockfish. Ваши файлы приложение только читает.", + "and_full_title": "Stockfish уже внутри", + "and_full_text": "Оценка и лучшие ходы сразу, без интернета.", + "and_light_title": "Stockfish скачивается в приложении", + "and_light_text": "Файл меньше; движок (98 МБ) скачивается в приложении, когда понадобится.", + "and_step1": "Откройте скачанный файл на телефоне.", + "and_step2": "Если Android спросит, разрешите установку приложений из браузера или файлового менеджера.", + "and_note": "Нужен Android 12 или новее. Сборки ставятся одна поверх другой, базы и настройки сохраняются.", + "next_android": "Откройте файл на телефоне и разрешите установку, если Android спросит." } diff --git a/website/site/index.html b/website/site/index.html index 811b89f..44fc9f9 100644 --- a/website/site/index.html +++ b/website/site/index.html @@ -57,6 +57,7 @@ {{t:btn_choose_2}} +
  • Arch
  • AppImage
  • Flatpak
  • +
  • Android
  • {{t:free_line}}

    @@ -134,6 +136,7 @@ +
    @@ -200,6 +203,21 @@
    +
    +

    Android

    +

    {{t:and_intro}}

    +
    +

    {{t:and_full_title}}

    .apk · {size:android}{{t:row_download}}
    +

    {{t:and_full_text}}

    +
    +
    +

    {{t:and_light_title}}

    .apk · {size:android-noengine}{{t:row_download}}
    +

    {{t:and_light_text}}

    +
    +
    1. {{t:and_step1}}
    2. {{t:and_step2}}
    +

    {{t:and_note}}

    +
    +

    {{t:all_releases}} ↗ · {{t:source_code}} ↗

    diff --git a/website/static/js/site.js b/website/static/js/site.js index d041b37..15e142c 100644 --- a/website/static/js/site.js +++ b/website/static/js/site.js @@ -13,7 +13,8 @@ var ua = navigator.userAgent || ""; var platform = (navigator.userAgentData && navigator.userAgentData.platform) || navigator.platform || ""; var touchMac = /Mac/.test(platform) && navigator.maxTouchPoints > 1; - if (/iPhone|iPod|iPad|Android/i.test(ua) || touchMac) return { os: "mobile" }; + if (/Android/i.test(ua)) return { os: "android", slug: "android" }; + if (/iPhone|iPod|iPad/i.test(ua) || touchMac) return { os: "mobile" }; if (/CrOS/.test(ua)) return { os: "linux", slug: "deb", chromeos: true }; if (/Win/.test(platform) || /Windows/.test(ua)) return { os: "windows", slug: "windows" }; if (/Mac/.test(platform) || /Macintosh/.test(ua)) return { os: "macos", slug: "macos" }; @@ -25,7 +26,7 @@ return { os: "unknown" }; } var sys = detect(); - var FORMAT = { windows: ".zip", deb: ".deb", rpm: ".rpm", appimage: "AppImage" }; + var FORMAT = { windows: ".zip", deb: ".deb", rpm: ".rpm", appimage: "AppImage", android: "APK" }; function intelMac() { try { @@ -60,11 +61,12 @@ var asset = CP.assets[sys.slug]; btn.href = "/download/" + sys.slug; btn.dataset.platform = sys.slug; - l1.textContent = t(sys.os === "windows" ? "btn_windows" : sys.os === "macos" ? "btn_macos" : "btn_linux"); + l1.textContent = t({ windows: "btn_windows", macos: "btn_macos", android: "btn_android" }[sys.os] || "btn_linux"); var parts = [CP.version ? t("btn_version").replace("{version}", CP.version) : t("btn_latest")]; if (asset) parts.push(asset.size); parts.push(sys.os === "macos" ? t("apple_silicon") : FORMAT[sys.slug]); if (sys.chromeos) parts.push(t("chromeos")); + if (sys.os === "android") parts.push(t("and_full_title")); l2.textContent = parts.join(" · "); if (sys.os === "macos") { var note = $("hero-note"); @@ -73,6 +75,12 @@ else note.textContent = t("mac_requires"); $("hero-mac").hidden = false; } + if (sys.os === "android") { + var req = $("hero-note"); + req.hidden = false; + req.textContent = t("and_requires"); + $("hero-android").hidden = false; + } if (sys.os === "linux") { $("hero-links").hidden = true; var formats = $("hero-formats"); @@ -121,6 +129,7 @@ again.appendChild(a1); again.appendChild(document.createTextNode(" · ")); again.appendChild(a2); panel.appendChild(again); if (platform === "windows") panel.appendChild(el("p", null, t("next_windows"))); + else if (platform === "android" || platform === "android-noengine") panel.appendChild(el("p", null, t("next_android"))); else if (platform === "macos") { // Gatekeeper warns about every app not signed by Apple: say so before it happens. panel.appendChild(el("h4", null, t("next_macos_title"))); @@ -199,7 +208,7 @@ select(tabs[(j + tabs.length) % tabs.length], true); }); }); - var mine = { windows: "tab-windows", macos: "tab-macos", linux: "tab-linux" }[sys.os]; + var mine = { windows: "tab-windows", macos: "tab-macos", linux: "tab-linux", android: "tab-android" }[sys.os]; if (mine) { $(mine).querySelector("small").hidden = false; select($(mine)); @@ -218,7 +227,7 @@ var id = location.hash.slice(1); if (!id || /^screenshot-/.test(id)) return; if (id.indexOf("download-") === 0) { - var panelId = id.replace(/^(download-(windows|macos|linux)).*/, "$1"); + var panelId = id.replace(/^(download-(windows|macos|linux|android)).*/, "$1"); var tab = tabs.filter(function (x) { return x.getAttribute("aria-controls") === panelId; })[0]; if (tab) select(tab); var target = $(id);