Android: boards and pieces, game numbers, the engine only on the button; fix the download's space check
Some checks are pending
CI / check (push) Waiting to run
CI / windows-build (push) Waiting to run
CI / macos-build (push) Waiting to run

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vrubelroman 2026-10-23 00:27:48 +03:00
parent 028f82a846
commit 3a08ac05c9
22 changed files with 829 additions and 77 deletions

View file

@ -2,6 +2,17 @@
All notable changes are listed here. Versions follow [Semantic Versioning](https://semver.org/).
## [Unreleased]
- Android: **boards and pieces** — Settings → «Board and pieces» offers the 37 boards and
17 piece sets of the desktop app, seen at once on a board above them.
- Android: the games list shows each game's number in the database (it stays the same
when a search narrows the list).
- Android: the engine turns on only with its button in each game, and turns off when you
leave the game or the app goes to the background.
- Android: the engine download no longer says there is not enough space on a phone with
plenty of it (the free space was asked of a folder not made yet).
## [0.11.0] — 2026-10-22
- Android: **add a folder** — every database in it and in the folders inside it (two

View file

@ -68,15 +68,20 @@ val stockfish = tasks.register<Exec>("stockfish") {
outputs.dir(stockfishOut)
}
/// The sample games of the desktop app and the Merida pieces, as app assets.
/// The sample games, the piece sets and the board images of the desktop app, as app
/// assets.
val bundleAssets = tasks.register<Copy>("bundleAssets") {
from(File(repo, "examples")) {
include("*.pgn")
into("examples")
}
from(File(repo, "apps/desktop/assets/pieces/merida")) {
include("*.svg")
into("pieces/merida")
from(File(repo, "apps/desktop/assets/pieces")) {
include("*/*.svg")
into("pieces")
}
from(File(repo, "apps/desktop/assets/boards")) {
include("*.jpg", "*.png")
into("boards")
}
from(stockfishOut.map { it.dir("source") }) {
into("licenses/stockfish")

View file

@ -1,12 +1,16 @@
package io.github.vrubelroman.chesspenguin
import android.app.Application
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import io.github.vrubelroman.chesspenguin.data.EngineFiles
import io.github.vrubelroman.chesspenguin.data.Library
import io.github.vrubelroman.chesspenguin.data.Settings
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import java.util.UUID
/// The app's databases, settings and engine files live as long as the process.
class ChessPenguinApp : Application() {
@ -19,4 +23,13 @@ class ChessPenguinApp : Application() {
/// The games shown on the list of each database (after a search), for paging
/// games from the game screen: database id → game numbers.
val shown = HashMap<String, List<UInt>>()
/// Changes each time the app goes to the background, and in every new process: the
/// engine button of a game holds only for the visit it was pressed in (§8.3).
var visit by mutableStateOf(UUID.randomUUID().toString())
private set
fun leftApp() {
visit = UUID.randomUUID().toString()
}
}

View file

@ -37,4 +37,10 @@ class MainActivity : ComponentActivity() {
}
}
}
override fun onStop() {
super.onStop()
// Gone to the background or closed, not turned.
if (!isChangingConfigurations) (application as ChessPenguinApp).leftApp()
}
}

View file

@ -6,6 +6,7 @@ import androidx.navigation3.runtime.entryProvider
import androidx.navigation3.runtime.rememberNavBackStack
import androidx.navigation3.ui.NavDisplay
import io.github.vrubelroman.chesspenguin.ui.AboutScreen
import io.github.vrubelroman.chesspenguin.ui.BoardStyleScreen
import io.github.vrubelroman.chesspenguin.ui.DatabasesScreen
import io.github.vrubelroman.chesspenguin.ui.SettingsScreen
import io.github.vrubelroman.chesspenguin.ui.GameScreen
@ -24,6 +25,8 @@ import kotlinx.serialization.Serializable
@Serializable data object AboutKey : NavKey
@Serializable data object BoardStyleKey : NavKey
@Composable
fun MainNavigation() {
val backStack = rememberNavBackStack(Databases)
@ -41,7 +44,14 @@ fun MainNavigation() {
GameScreen(key.db, key.place, key.query, onBack = { backStack.removeLastOrNull() }, onSettings = { backStack.add(SettingsKey) })
}
entry<SettingsKey> {
SettingsScreen(onBack = { backStack.removeLastOrNull() }, onAbout = { backStack.add(AboutKey) })
SettingsScreen(
onBack = { backStack.removeLastOrNull() },
onAbout = { backStack.add(AboutKey) },
onBoardStyle = { backStack.add(BoardStyleKey) },
)
}
entry<BoardStyleKey> {
BoardStyleScreen(onBack = { backStack.removeLastOrNull() })
}
entry<AboutKey> {
AboutScreen(onBack = { backStack.removeLastOrNull() })

View file

@ -0,0 +1,78 @@
package io.github.vrubelroman.chesspenguin.data
import androidx.annotation.StringRes
import androidx.compose.ui.graphics.Color
import io.github.vrubelroman.chesspenguin.R
/// The piece sets of the desktop app (apps/desktop/src/assets.rs), drawn from
/// `assets/pieces/<dir>`; the name is the set's own, as on Lichess.
enum class PieceSet(val dir: String) {
Cburnett("cburnett"),
Merida("merida"),
Mpchess("mpchess"),
Chessnut("chessnut"),
Fantasy("fantasy"),
Celtic("celtic"),
Spatial("spatial"),
Rhosgfx("rhosgfx"),
Shapes("shapes"),
KiwenSuwi("kiwen-suwi"),
Firi("firi"),
Pixel("pixel"),
Letter("letter"),
Pirouetti("pirouetti"),
Governor("governor"),
Kosal("kosal"),
Metaltops("metaltops"),
}
/// The boards of the desktop app (assets.rs `BoardThemeId`): two colors, and for some a
/// full-board image (`assets/boards/<file>`, 8×8 squares, a1 dark) drawn instead of them.
/// The colors stay for the coordinates and the previews.
enum class BoardTheme(
@StringRes val label: Int,
val number: Int?,
val light: Color,
val dark: Color,
val texture: String? = null,
) {
Brown(R.string.board_brown, null, rgb(240, 217, 181), rgb(181, 136, 99)),
Blue(R.string.board_blue, null, rgb(222, 227, 230), rgb(140, 162, 173)),
Green(R.string.board_green, null, rgb(255, 255, 221), rgb(134, 166, 102)),
Tournament(R.string.board_tournament, null, rgb(238, 238, 210), rgb(118, 150, 86)),
Sand(R.string.board_sand, null, rgb(240, 228, 196), rgb(200, 168, 110)),
Coral(R.string.board_coral, null, rgb(177, 228, 185), rgb(112, 162, 163)),
Grey(R.string.board_grey, null, rgb(217, 217, 217), rgb(154, 154, 154)),
Purple(R.string.board_purple, null, rgb(232, 224, 240), rgb(159, 144, 176)),
Ic(R.string.board_ic, null, rgb(236, 236, 236), rgb(193, 193, 142)),
Ncf(R.string.board_ncf, null, rgb(187, 207, 255), rgb(84, 119, 202)),
Ice(R.string.board_ice, null, rgb(222, 234, 240), rgb(122, 157, 178)),
Navy(R.string.board_navy, null, rgb(220, 226, 236), rgb(70, 96, 140)),
Mint(R.string.board_mint, null, rgb(222, 241, 230), rgb(118, 178, 148)),
Emerald(R.string.board_emerald, null, rgb(226, 236, 218), rgb(74, 132, 100)),
Orange(R.string.board_orange, null, rgb(250, 228, 196), rgb(208, 139, 72)),
Rose(R.string.board_rose, null, rgb(242, 220, 220), rgb(190, 126, 138)),
Dusk(R.string.board_dusk, null, rgb(204, 186, 176), rgb(112, 102, 122)),
Night(R.string.board_night, null, rgb(128, 136, 146), rgb(68, 74, 84)),
Wood(R.string.board_wood, null, rgb(215, 161, 91), rgb(154, 88, 35), "wood.jpg"),
Wood2(R.string.board_wood, 2, rgb(151, 124, 79), rgb(121, 95, 48), "wood2.jpg"),
Wood3(R.string.board_wood, 3, rgb(186, 173, 157), rgb(129, 94, 56), "wood3.jpg"),
Wood4(R.string.board_wood, 4, rgb(191, 158, 104), rgb(134, 91, 54), "wood4.jpg"),
Maple(R.string.board_maple, null, rgb(224, 190, 146), rgb(180, 111, 60), "maple.jpg"),
Maple2(R.string.board_maple, 2, rgb(222, 193, 151), rgb(167, 114, 85), "maple2.jpg"),
Leather(R.string.board_leather, null, rgb(206, 206, 198), rgb(192, 140, 18), "leather.jpg"),
Marble(R.string.board_marble, null, rgb(126, 150, 128), rgb(97, 120, 97), "marble.jpg"),
BlueMarble(R.string.board_blue_marble, null, rgb(229, 224, 212), rgb(148, 158, 174), "blue-marble.jpg"),
Blue2(R.string.board_blue, 2, rgb(129, 151, 173), rgb(96, 118, 138), "blue2.jpg"),
Blue3(R.string.board_blue, 3, rgb(189, 200, 211), rgb(68, 114, 163), "blue3.jpg"),
Canvas(R.string.board_canvas, null, rgb(203, 206, 223), rgb(114, 130, 156), "canvas2.jpg"),
Metal(R.string.board_metal, null, rgb(177, 177, 177), rgb(119, 119, 119), "metal.jpg"),
Olive(R.string.board_olive, null, rgb(173, 166, 148), rgb(132, 124, 106), "olive.jpg"),
Stone(R.string.board_stone, null, rgb(169, 169, 169), rgb(136, 136, 136), "grey.jpg"),
GreenPlastic(R.string.board_green_plastic, null, rgb(241, 246, 178), rgb(89, 147, 93), "green-plastic.png"),
PurpleDiag(R.string.board_purple_diag, null, rgb(227, 216, 238), rgb(151, 123, 178), "purple-diag.png"),
PinkPyramid(R.string.board_pink_pyramid, null, rgb(237, 238, 191), rgb(242, 117, 117), "pink-pyramid.png"),
Horsey(R.string.board_sketch, null, rgb(239, 222, 198), rgb(151, 112, 81), "horsey.jpg"),
}
private fun rgb(r: Int, g: Int, b: Int) = Color(r, g, b)

View file

@ -5,6 +5,7 @@ import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.net.Uri
import android.os.storage.StorageManager
import io.github.vrubelroman.chesspenguin.BuildConfig
import io.github.vrubelroman.chesspenguin.R
import kotlinx.coroutines.CoroutineScope
@ -89,7 +90,7 @@ class EngineFiles(private val context: Context, private val scope: CoroutineScop
} catch (e: NetFailure) {
NetState.Failed(e.problem)
} catch (e: IOException) {
NetState.Failed(if (dir.usableSpace < BuildConfig.NET_SIZE) NetProblem.NoSpace else NetProblem.Interrupted)
NetState.Failed(if (freeSpace() < BuildConfig.NET_SIZE) NetProblem.NoSpace else NetProblem.Interrupted)
}
if (isActive) _state.value = result
}
@ -100,7 +101,7 @@ class EngineFiles(private val context: Context, private val scope: CoroutineScop
return
}
// The file is downloaded next to the app's files, then checked and moved in.
if (dir.usableSpace < 2 * BuildConfig.NET_SIZE) {
if (freeSpace() < 2 * BuildConfig.NET_SIZE) {
_state.value = NetState.Failed(NetProblem.NoSpace)
return
}
@ -171,7 +172,7 @@ class EngineFiles(private val context: Context, private val scope: CoroutineScop
} catch (e: NetFailure) {
NetState.Failed(e.problem)
} catch (e: IOException) {
NetState.Failed(if (dir.usableSpace < BuildConfig.NET_SIZE) NetProblem.NoSpace else NetProblem.Interrupted)
NetState.Failed(if (freeSpace() < BuildConfig.NET_SIZE) NetProblem.NoSpace else NetProblem.Interrupted)
}
}
downloads.remove(id)
@ -235,6 +236,16 @@ class EngineFiles(private val context: Context, private val scope: CoroutineScop
if (!part.renameTo(net)) throw IOException("cannot move the network into place")
}
/// The space the app can take, with the caches the system would clear for it. Asked
/// of filesDir, which always exists: a folder not made yet (the engine's, before the
/// first download) answers 0.
private fun freeSpace(): Long = try {
val storage = context.getSystemService(StorageManager::class.java)
storage.getAllocatableBytes(storage.getUuidForPath(context.filesDir))
} catch (e: IOException) {
context.filesDir.usableSpace
}
private fun online(): Boolean {
val cm = context.getSystemService(ConnectivityManager::class.java) ?: return true
val caps = cm.getNetworkCapabilities(cm.activeNetwork) ?: return false

View file

@ -14,11 +14,11 @@ enum class Notation { Latin, Figurines, Local }
data class Prefs(
val theme: Theme = Theme.System,
val notation: Notation = Notation.Latin,
val board: BoardTheme = BoardTheme.Green,
val pieces: PieceSet = PieceSet.Merida,
val vibration: Boolean = true,
val animation: Boolean = true,
val bestArrow: Boolean = true,
/// The engine button: once turned on, it stays on in the next game (§8.3).
val engineOn: Boolean = false,
val engineLines: Int = 2,
/// Seconds of thinking per position; 0 = no limit.
val engineSeconds: Int = 20,
@ -32,6 +32,11 @@ fun defaultThreads(): Int = (Runtime.getRuntime().availableProcessors() / 2).coe
class Settings(context: Context) {
private val store = context.getSharedPreferences("settings", Context.MODE_PRIVATE)
private val _prefs = MutableStateFlow(read())
init {
// The engine button was kept here up to 0.11 (it is not remembered any more).
store.edit().remove("engineOn").apply()
}
val prefs: StateFlow<Prefs> = _prefs.asStateFlow()
private fun read(): Prefs {
@ -39,10 +44,11 @@ class Settings(context: Context) {
return Prefs(
theme = enumValueOrNull<Theme>(store.getString("theme", null)) ?: d.theme,
notation = enumValueOrNull<Notation>(store.getString("notation", null)) ?: d.notation,
board = enumValueOrNull<BoardTheme>(store.getString("board", null)) ?: d.board,
pieces = enumValueOrNull<PieceSet>(store.getString("pieces", null)) ?: d.pieces,
vibration = store.getBoolean("vibration", d.vibration),
animation = store.getBoolean("animation", d.animation),
bestArrow = store.getBoolean("bestArrow", d.bestArrow),
engineOn = store.getBoolean("engineOn", d.engineOn),
engineLines = store.getInt("engineLines", d.engineLines),
engineSeconds = store.getInt("engineSeconds", d.engineSeconds),
engineThreads = store.getInt("engineThreads", d.engineThreads),
@ -56,10 +62,11 @@ class Settings(context: Context) {
store.edit()
.putString("theme", p.theme.name)
.putString("notation", p.notation.name)
.putString("board", p.board.name)
.putString("pieces", p.pieces.name)
.putBoolean("vibration", p.vibration)
.putBoolean("animation", p.animation)
.putBoolean("bestArrow", p.bestArrow)
.putBoolean("engineOn", p.engineOn)
.putInt("engineLines", p.engineLines)
.putInt("engineSeconds", p.engineSeconds)
.putInt("engineThreads", p.engineThreads)

View file

@ -32,13 +32,12 @@ val DarkPrimaryContainer = Color(0xFF1A4566)
val DarkError = Color(0xFFF28B82)
val DarkErrorContainer = Color(0xFF5C1A14)
/// Colors of the notation and the board that stay ours whatever the theme.
/// Colors of the notation and the board that stay ours whatever the theme (the
/// squares are the chosen board's, data/BoardStyle.kt).
data class ChessColors(
val dark: Boolean,
val currentMove: Color,
val comment: Color,
val lightSquare: Color,
val darkSquare: Color,
val lastMove: Color,
)
@ -46,8 +45,6 @@ val LightChess = ChessColors(
dark = false,
currentMove = Color(0xFF90D1FF),
comment = Color(0xFF2A5B8A),
lightSquare = Color(0xFFFFFFDD),
darkSquare = Color(0xFF86A666),
lastMove = Color(0x699BC700),
)

View file

@ -34,7 +34,18 @@ private const val SITE = "https://chess.vrubel.xyz"
private val NOTICES = listOf(
"ChessPenguin" to "GPL-3.0-or-later · vrubelroman",
"Stockfish 19" to "GPL-3.0 · The Stockfish developers (see AUTHORS) · github.com/official-stockfish/Stockfish",
"Merida pieces" to "GPLv2+ · Armando Hernandez Marroquin (via Lichess)",
"Pieces cburnett, merida" to "GPLv2+ · Colin M.L. Burnett; Armando Hernandez Marroquin (via Lichess)",
"Pieces mpchess" to "GPLv3+ · Maxime Chupin (via Lichess)",
"Pieces chessnut" to "Apache-2.0 · Alexis Luengas (via Lichess)",
"Pieces fantasy, celtic, spatial" to "MIT · Maurizio Monge (via Lichess)",
"Pieces rhosgfx" to "CC0-1.0 · RhosGFX (via Lichess)",
"Pieces shapes" to "CC BY-SA 4.0 · flugsio (via Lichess)",
"Pieces kiwen-suwi, firi" to "CC BY 4.0 · neverRare; James Faure (via Lichess)",
"Pieces pixel, letter, pirouetti" to "AGPLv3+ · therealqtpi; usolando; pirouetti (via Lichess)",
"Pieces governor" to "AGPLv3+ · the lila authors (via PyChess)",
"Pieces kosal" to "CC BY 4.0 · Kosal Sen, philatype.com (via PyChess)",
"Pieces metaltops" to "GPL · PyChess",
"Board images" to "AGPLv3+ · the lila authors and pirouetti (Lichess)",
"Figurines, Noto Sans Math" to "SIL Open Font License 1.1",
"Jetpack Compose, AndroidX, Kotlin" to "Apache-2.0 · Google, JetBrains",
"UniFFI" to "MPL-2.0 · Mozilla",

View file

@ -2,7 +2,10 @@ package io.github.vrubelroman.chesspenguin.ui
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.BitmapRegionDecoder
import android.graphics.Canvas
import android.graphics.Rect
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.tween
@ -11,7 +14,9 @@ import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
@ -24,6 +29,8 @@ import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
@ -35,7 +42,11 @@ import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.sp
import com.caverock.androidsvg.SVG
import io.github.vrubelroman.chesspenguin.data.BoardTheme
import io.github.vrubelroman.chesspenguin.data.PieceSet
import io.github.vrubelroman.chesspenguin.theme.LocalChessColors
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
/// The 64 squares of a FEN's placement, a8 first: the piece letter or ' '.
fun placement(fen: String): CharArray {
@ -60,17 +71,20 @@ fun squareIndex(square: String?): Int? {
return (7 - rank) * 8 + file
}
/// The Merida pieces of the desktop app, drawn from their SVG at a size once.
/// The pieces of the desktop app's sets, drawn from their SVG at a size once.
class Pieces(private val context: Context) {
private val svgs = HashMap<Char, SVG>()
private val bitmaps = HashMap<Pair<Char, Int>, ImageBitmap>()
private val svgs = HashMap<Pair<PieceSet, Char>, SVG>()
private val bitmaps = HashMap<Triple<PieceSet, Char, Int>, ImageBitmap>()
fun bitmap(piece: Char, size: Int): ImageBitmap? {
fun bitmap(set: PieceSet, piece: Char, size: Int): ImageBitmap? {
if (size <= 0) return null
return bitmaps.getOrPut(piece to size) {
return bitmaps.getOrPut(Triple(set, piece, size)) {
val name = (if (piece.isUpperCase()) "w" else "b") + piece.uppercaseChar()
val svg = svgs.getOrPut(piece) { context.assets.open("pieces/merida/$name.svg").use { SVG.getFromInputStream(it) } }
val svg = svgs.getOrPut(set to piece) { context.assets.open("pieces/${set.dir}/$name.svg").use { SVG.getFromInputStream(it) } }
val bmp = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888)
// Without a viewBox (kiwen-suwi, metaltops) AndroidSVG draws a set at its own
// size, whatever size is asked for.
if (svg.documentViewBox == null) svg.setDocumentViewBox(0f, 0f, svg.documentWidth, svg.documentHeight)
svg.setDocumentWidth(size.toFloat())
svg.setDocumentHeight(size.toFloat())
svg.renderToCanvas(Canvas(bmp))
@ -79,6 +93,32 @@ class Pieces(private val context: Context) {
}
}
/// A board's image (1024 px) read at about `size` px: a phone's board needs no more, and
/// the whole image would take 4 MB.
fun boardImage(context: Context, file: String, size: Int): ImageBitmap? = runCatching {
val bytes = context.assets.open("boards/$file").use { it.readBytes() }
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)
var sample = 1
while (bounds.outWidth / (sample * 2) >= size) sample *= 2
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, BitmapFactory.Options().apply { inSampleSize = sample })?.asImageBitmap()
}.getOrNull()
/// The corner of a board's image with a1: 2×2 squares, for the choice of boards.
fun boardCorner(context: Context, file: String, size: Int): ImageBitmap? = runCatching {
context.assets.open("boards/$file").use { input ->
val decoder = BitmapRegionDecoder.newInstance(input) ?: return null
try {
val q = decoder.width / 4
var sample = 1
while (q / (sample * 2) >= size) sample *= 2
decoder.decodeRegion(Rect(0, decoder.height - q, q, decoder.height), BitmapFactory.Options().apply { inSampleSize = sample })?.asImageBitmap()
} finally {
decoder.recycle()
}
}
}.getOrNull()
/// An arrow on the board: a comment's `[%cal]` or the engine's best move.
data class BoardArrow(val from: String, val to: String, val color: Color, val weight: Float = 1f)
@ -97,7 +137,7 @@ fun markColor(letter: String): Color = when (letter) {
/// The engine's arrows are blue, as on the desktop.
val EngineArrow = Color(0, 48, 136, 160)
/// The board: full width, the colors of the green theme, the last move lit, the
/// The board: full width, the chosen board and pieces, the last move lit, the
/// coordinates inside the edge squares (as on Lichess). It takes no touches in the first
/// version (docs/design/android-ui.md §7.2). A move slides into place (250 ms).
@Composable
@ -107,6 +147,8 @@ fun Board(
lastFrom: String?,
lastTo: String?,
pieces: Pieces,
theme: BoardTheme,
set: PieceSet,
description: String,
modifier: Modifier = Modifier,
arrows: List<BoardArrow> = emptyList(),
@ -115,6 +157,14 @@ fun Board(
animated: Boolean = true,
) {
val colors = LocalChessColors.current
val context = LocalContext.current
// The image of a textured board, read off the main thread; the flat colors until then.
var side by remember { mutableIntStateOf(0) }
val texture by produceState<ImageBitmap?>(null, theme, side) {
value = null
val file = theme.texture ?: return@produceState
if (side > 0) value = withContext(Dispatchers.IO) { boardImage(context, file, side) }
}
val measurer = rememberTextMeasurer()
val squares = remember(fen) { placement(fen) }
val from = squareIndex(lastFrom)
@ -138,6 +188,7 @@ fun Board(
Canvas(
modifier
.aspectRatio(1f)
.onSizeChanged { side = it.width }
.semantics { contentDescription = description },
) {
val sq = size.width / 8f
@ -148,9 +199,14 @@ fun Board(
val (r, c) = if (flipped) (7 - row) to (7 - col) else row to col
return Offset(c * sq, r * sq)
}
val image = texture
if (image != null) {
// The squares of the image are the same seen from either side: it is not turned.
drawImage(image, dstSize = IntSize(size.width.toInt(), size.height.toInt()))
}
for (i in 0 until 64) {
val light = (i / 8 + i % 8) % 2 == 0
drawRect(if (light) colors.lightSquare else colors.darkSquare, cell(i), Size(sq, sq))
if (image == null) drawRect(if (light) theme.light else theme.dark, cell(i), Size(sq, sq))
if (i == from || i == to) drawRect(colors.lastMove, cell(i), Size(sq, sq))
}
for (m in marks) {
@ -181,7 +237,7 @@ fun Board(
for (i in 0 until 64) {
val p = squares[i]
if (p == ' ') continue
val bmp = pieces.bitmap(p, px) ?: continue
val bmp = pieces.bitmap(set, p, px) ?: continue
var at = cell(i)
if (animate && i == to && from != null && slide.value < 1f) {
val start = cell(from)
@ -196,9 +252,9 @@ fun Board(
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),
drawCoord(measurer, ('a' + fileIndex).toString(), coordStyle.copy(color = if (bottomLight) theme.dark else theme.light),
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),
drawCoord(measurer, ('1' + rankIndex).toString(), coordStyle.copy(color = if (leftLight) theme.dark else theme.light),
Offset(with(density) { 2.sp.toPx() }, k * sq + with(density) { 1.sp.toPx() }))
}
for (a in arrows) {

View file

@ -0,0 +1,256 @@
package io.github.vrubelroman.chesspenguin.ui
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.rounded.ArrowBack
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.SecondaryTabRow
import androidx.compose.material3.Tab
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import io.github.vrubelroman.chesspenguin.R
import io.github.vrubelroman.chesspenguin.data.BoardTheme
import io.github.vrubelroman.chesspenguin.data.PieceSet
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
/// A position to see a board and its pieces by: the Ruy Lopez after 3.Bb5.
private const val SAMPLE = "r1bqkbnr/pppp1ppp/2n5/1B2p3/4P3/5N2/PPPP1PPP/RNBQK2R b KQkq - 3 3"
/// "Board and pieces": the boards and the piece sets of the desktop app, chosen at once
/// and seen on a board above them (android-ui.md §9).
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun BoardStyleScreen(onBack: () -> Unit) {
val app = app()
val context = LocalContext.current
val prefs by app.settings.prefs.collectAsState()
val pieces = remember { Pieces(context) }
val landscape = LocalConfiguration.current.orientation == android.content.res.Configuration.ORIENTATION_LANDSCAPE
Scaffold(
topBar = {
TopAppBar(
title = { Text(stringResource(R.string.board_and_pieces)) },
navigationIcon = {
IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Rounded.ArrowBack, stringResource(R.string.back)) }
},
)
},
) { padding ->
val preview: @Composable (Modifier) -> Unit = { modifier ->
Board(
fen = SAMPLE,
flipped = false,
lastFrom = "f1",
lastTo = "b5",
pieces = pieces,
theme = prefs.board,
set = prefs.pieces,
description = boardLabel(prefs.board) + " · " + prefs.pieces.dir,
animated = false,
modifier = modifier,
)
}
val choices: @Composable (Modifier) -> Unit = { modifier ->
Choices(
board = prefs.board,
set = prefs.pieces,
pieces = pieces,
onBoard = { b -> app.settings.update { it.copy(board = b) } },
onSet = { p -> app.settings.update { it.copy(pieces = p) } },
modifier = modifier,
)
}
// The board stays in sight while the choices scroll under it (or beside it).
if (landscape) {
Row(Modifier.fillMaxSize().padding(padding)) {
Box(Modifier.fillMaxSize().weight(1f), contentAlignment = Alignment.Center) {
preview(Modifier.padding(16.dp).fillMaxSize())
}
choices(Modifier.weight(1.4f))
}
} else {
Column(Modifier.fillMaxSize().padding(padding)) {
Box(Modifier.fillMaxWidth().padding(vertical = 12.dp), contentAlignment = Alignment.Center) {
preview(Modifier.fillMaxWidth(0.6f).widthIn(max = 240.dp))
}
choices(Modifier.weight(1f))
}
}
}
}
/// "Wood 2": the board's name in the interface language.
@Composable
fun boardLabel(b: BoardTheme): String = stringResource(b.label) + (b.number?.let { " $it" } ?: "")
/// Two tabs, so that the piece sets are not hidden under 37 boards.
@Composable
private fun Choices(
board: BoardTheme,
set: PieceSet,
pieces: Pieces,
onBoard: (BoardTheme) -> Unit,
onSet: (PieceSet) -> Unit,
modifier: Modifier,
) {
var tab by rememberSaveable { mutableIntStateOf(0) }
Column(modifier) {
SecondaryTabRow(selectedTabIndex = tab) {
Tab(selected = tab == 0, onClick = { tab = 0 }, text = { Text(stringResource(R.string.board)) })
Tab(selected = tab == 1, onClick = { tab = 1 }, text = { Text(stringResource(R.string.pieces_tab)) })
}
LazyVerticalGrid(
GridCells.Adaptive(88.dp),
Modifier.fillMaxSize(),
contentPadding = androidx.compose.foundation.layout.PaddingValues(12.dp),
verticalArrangement = Arrangement.spacedBy(4.dp),
) {
if (tab == 0) {
items(BoardTheme.entries, key = { "b" + it.name }) { b ->
Swatch(b, b == board) { onBoard(b) }
}
} else {
items(PieceSet.entries, key = { "p" + it.name }) { p ->
PieceChoice(p, p == set, board, pieces) { onSet(p) }
}
}
}
}
}
/// The ring around the chosen board or set.
@Composable
private fun Modifier.chosen(selected: Boolean, shape: RoundedCornerShape): Modifier =
if (selected) border(3.dp, MaterialTheme.colorScheme.primary, shape) else this
/// A board as 2×2 squares (the corner of its image), its name under it.
@Composable
private fun Swatch(b: BoardTheme, selected: Boolean, onClick: () -> Unit) {
val context = LocalContext.current
var side by remember { mutableIntStateOf(0) }
val corner by produceState<ImageBitmap?>(null, b, side) {
val file = b.texture ?: return@produceState
if (side > 0) value = withContext(Dispatchers.IO) { boardCorner(context, file, side) }
}
val shape = RoundedCornerShape(6.dp)
Column(
Modifier
.clip(RoundedCornerShape(8.dp))
.selectable(selected = selected, role = Role.RadioButton, onClick = onClick)
.padding(4.dp),
horizontalAlignment = Alignment.CenterHorizontally,
) {
Canvas(
Modifier
.fillMaxWidth()
.aspectRatio(1f)
.chosen(selected, shape)
.padding(if (selected) 5.dp else 0.dp)
.clip(RoundedCornerShape(if (selected) 2.dp else 6.dp))
.onSizeChanged { side = it.width },
) {
val image = corner
if (image != null) {
drawImage(image, dstOffset = IntOffset.Zero, dstSize = IntSize(size.width.toInt(), size.height.toInt()))
} else {
val sq = size.width / 2
// a1 dark at the bottom left, as on the board.
drawRect(b.light, Offset(0f, 0f), Size(sq, sq))
drawRect(b.dark, Offset(sq, 0f), Size(sq, sq))
drawRect(b.dark, Offset(0f, sq), Size(sq, sq))
drawRect(b.light, Offset(sq, sq), Size(sq, sq))
}
}
Label(boardLabel(b), selected)
}
}
/// A set as its white knight on a light square and black queen on a dark one of the
/// chosen board (a dark set stays readable), its name under them.
@Composable
private fun PieceChoice(p: PieceSet, selected: Boolean, board: BoardTheme, pieces: Pieces, onClick: () -> Unit) {
val shape = RoundedCornerShape(6.dp)
Column(
Modifier
.clip(RoundedCornerShape(8.dp))
.selectable(selected = selected, role = Role.RadioButton, onClick = onClick)
.padding(4.dp),
horizontalAlignment = Alignment.CenterHorizontally,
) {
Canvas(
Modifier
.fillMaxWidth()
.aspectRatio(2f)
.chosen(selected, shape)
.padding(if (selected) 5.dp else 0.dp)
.clip(RoundedCornerShape(if (selected) 2.dp else 6.dp)),
) {
val sq = size.height
val px = sq.toInt()
val gap = (size.width - 2 * sq) / 2
drawRect(board.light, Offset(gap, 0f), Size(sq, sq))
drawRect(board.dark, Offset(gap + sq, 0f), Size(sq, sq))
pieces.bitmap(p, 'N', px)?.let { drawImage(it, dstOffset = IntOffset(gap.toInt(), 0), dstSize = IntSize(px, px)) }
pieces.bitmap(p, 'q', px)?.let { drawImage(it, dstOffset = IntOffset((gap + sq).toInt(), 0), dstSize = IntSize(px, px)) }
}
Label(p.dir, selected)
}
}
@Composable
private fun Label(text: String, selected: Boolean) {
Text(
text,
style = MaterialTheme.typography.bodySmall,
color = if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = TextAlign.Center,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.padding(top = 4.dp),
)
}

View file

@ -162,8 +162,13 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o
val status by session.status.collectAsState()
val engineView by session.analysis.collectAsState()
var visible by remember { mutableStateOf(true) }
var sheet by remember { mutableStateOf(false) }
var wantEngine by remember { mutableStateOf(false) }
var sheet by rememberSaveable { mutableStateOf(false) }
var wantEngine by rememberSaveable { mutableStateOf(false) }
// The engine button: off in every game screen opened, on only when pressed, and
// only until the app goes to the background (§8.3). Kept while Settings is open over
// the game and when the phone is turned.
var engineVisit by rememberSaveable { mutableStateOf<String?>(null) }
val engineWanted = engineVisit == app.visit
var expanded by rememberSaveable { mutableStateOf(false) }
var menu by remember { mutableStateOf(false) }
var info by remember { mutableStateOf(false) }
@ -206,7 +211,7 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o
val node = nodes?.getOrNull(current)
val notation = rememberLazyListState()
val engineReady = netState == NetState.Ready
val engineOn = prefs.engineOn && engineReady
val engineOn = engineWanted && engineReady
val position = remember(g, current) { g?.let { enginePosition(it, current) } }
// Only what the engine said about the position on the board.
val analysis = engineView?.takeIf { it.position == position }?.analysis
@ -230,7 +235,7 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o
if (netState == NetState.Ready && wantEngine) {
wantEngine = false
sheet = false
app.settings.update { it.copy(engineOn = true) }
engineVisit = app.visit
if (!files.builtIn) snackbar.showSnackbar(readyText)
}
}
@ -273,8 +278,8 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o
}
fun toggleEngine() {
when {
prefs.engineOn && engineReady -> app.settings.update { it.copy(engineOn = false) }
engineReady -> app.settings.update { it.copy(engineOn = true) }
engineWanted && engineReady -> engineVisit = null
engineReady -> engineVisit = app.visit
files.builtIn -> {
wantEngine = true
files.prepare()
@ -348,6 +353,8 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o
lastFrom = step?.fromSquare ?: node?.fromSquare,
lastTo = step?.toSquare ?: node?.toSquare,
pieces = pieces,
theme = prefs.board,
set = prefs.pieces,
description = description,
arrows = arrows,
marks = marks,

View file

@ -50,6 +50,8 @@ import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.pluralStringResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
@ -173,7 +175,10 @@ fun GamesScreen(db: String, onBack: () -> Unit, onGame: (place: Int, query: Stri
Text(stringResource(R.string.reading), color = MaterialTheme.colorScheme.onSurfaceVariant)
}
games.isEmpty() -> Message(stringResource(R.string.nothing_found), "")
else -> LazyColumn(Modifier.fillMaxSize(), state = list) {
else -> {
// Wide enough for the database's largest number.
val numberWidth = numberWidth(database?.len()?.toInt() ?: games.size)
LazyColumn(Modifier.fillMaxSize(), state = list) {
items(games.size, key = { games[it].toLong() }) { place ->
val chunk = place / CHUNK
val loaded = rows[chunk]
@ -184,9 +189,10 @@ fun GamesScreen(db: String, onBack: () -> Unit, onGame: (place: Int, query: Stri
rows[chunk] = withContext(Dispatchers.Default) { d.rowsOf(part) }
}
}
GameRowView(loaded?.getOrNull(place % CHUNK)) { onGame(place, query) }
GameRowView(games[place].toInt() + 1, numberWidth, loaded?.getOrNull(place % CHUNK)) { onGame(place, query) }
}
}
}
}
}
}
@ -218,18 +224,46 @@ private fun openProblem(e: Throwable): String = when (e) {
else -> ""
}
/// One game: "White – Black" and the result, then event · year · ECO (§6.2). An
/// unfinished game ("*", most book positions) shows no result.
/// The width of the numbers column: the digits of `count`, grouped as shown.
@Composable
private fun GameRowView(row: GameRow?, onClick: () -> Unit) {
Column(
private fun numberWidth(count: Int): androidx.compose.ui.unit.Dp {
val style = MaterialTheme.typography.bodySmall.merge(Tabular)
val measurer = androidx.compose.ui.text.rememberTextMeasurer()
val density = androidx.compose.ui.platform.LocalDensity.current
return remember(count, style, density) {
with(density) { measurer.measure(groupDigits(count.coerceAtLeast(1)), style).size.width.toDp() }
}
}
/// One game: its number in the database, "White – Black" and the result, then event ·
/// year · ECO (§6.2). An unfinished game ("*", most book positions) shows no result.
@Composable
private fun GameRowView(number: Int, numberWidth: androidx.compose.ui.unit.Dp, row: GameRow?, onClick: () -> Unit) {
Row(
Modifier
.fillMaxWidth()
.height(64.dp)
.clickable(enabled = row != null, onClick = onClick)
.padding(horizontal = 16.dp),
verticalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically,
) {
val said = stringResource(R.string.game_number, groupDigits(number))
Text(
groupDigits(number),
style = MaterialTheme.typography.bodySmall.merge(Tabular),
color = MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = TextAlign.End,
maxLines = 1,
modifier = Modifier.width(numberWidth).semantics { contentDescription = said },
)
Spacer(Modifier.width(12.dp))
GameRowText(row, Modifier.weight(1f))
}
}
@Composable
private fun GameRowText(row: GameRow?, modifier: Modifier) {
Column(modifier, verticalArrangement = Arrangement.Center) {
if (row == null) return@Column
Row(verticalAlignment = Alignment.CenterVertically) {
Row(Modifier.weight(1f)) {

View file

@ -50,11 +50,11 @@ import io.github.vrubelroman.chesspenguin.data.NetState
import io.github.vrubelroman.chesspenguin.data.Notation
import io.github.vrubelroman.chesspenguin.data.Theme
/// One screen of groups, changes apply at once (android-ui.md §9). Boards and piece
/// sets are not chosen in the first version (§16).
/// One screen of groups, changes apply at once (android-ui.md §9). The board and the
/// pieces are chosen on a screen of their own, with a board to see them on.
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SettingsScreen(onBack: () -> Unit, onAbout: () -> Unit) {
fun SettingsScreen(onBack: () -> Unit, onAbout: () -> Unit, onBoardStyle: () -> Unit) {
val app = app()
val prefs by app.settings.prefs.collectAsState()
val files = app.engineFiles
@ -115,6 +115,7 @@ fun SettingsScreen(onBack: () -> Unit, onAbout: () -> Unit) {
Toggle(stringResource(R.string.vibration), prefs.vibration) { v -> set { it.copy(vibration = v) } }
Group(stringResource(R.string.group_look))
Item(stringResource(R.string.board_and_pieces), boardLabel(prefs.board) + " · " + prefs.pieces.dir, onBoardStyle)
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) }

View file

@ -108,7 +108,7 @@
<string name="threads">Threads</string>
<string name="memory">Speicher</string>
<string name="megabytes">%1$d MB</string>
<string name="engine_battery">Die Engine verbraucht Akku. Sie stoppt von selbst, wenn sich der Bildschirm ausschaltet.</string>
<string name="engine_battery">Die Engine verbraucht Akku. Sie schaltet sich von selbst aus, wenn Sie die Partie verlassen oder die App in den Hintergrund geht.</string>
<string name="about">Über</string>
<string name="build_full">Stockfish eingebaut</string>
<string name="build_light">Stockfish wird in der App geladen</string>
@ -178,4 +178,37 @@
<string name="choose_all">Alle auswählen</string>
<string name="choose_none">Keine auswählen</string>
<string name="open_missing_part">Die Datei %1$s liegt nicht mehr neben der Datenbank: Sie wurde verschoben oder gelöscht.</string>
<string name="board_and_pieces">Brett und Figuren</string>
<string name="board_brown">Braun</string>
<string name="board_blue">Blau</string>
<string name="board_green">Grün</string>
<string name="board_tournament">Turnier</string>
<string name="board_sand">Sand</string>
<string name="board_coral">Koralle</string>
<string name="board_grey">Grau</string>
<string name="board_purple">Lila</string>
<string name="board_ice">Eis</string>
<string name="board_navy">Marineblau</string>
<string name="board_mint">Minze</string>
<string name="board_emerald">Smaragd</string>
<string name="board_orange">Orange</string>
<string name="board_rose">Rosa</string>
<string name="board_dusk">Dämmerung</string>
<string name="board_night">Nacht</string>
<string name="board_wood">Holz</string>
<string name="board_maple">Ahorn</string>
<string name="board_leather">Leder</string>
<string name="board_marble">Marmor</string>
<string name="board_blue_marble">Blauer Marmor</string>
<string name="board_canvas">Leinwand</string>
<string name="board_metal">Metall</string>
<string name="board_olive">Olive</string>
<string name="board_stone">Stein</string>
<string name="board_green_plastic">Grünes Plastik</string>
<string name="board_purple_diag">Lila Diagonalen</string>
<string name="board_pink_pyramid">Rosa Pyramiden</string>
<string name="board_sketch">Skizze</string>
<string name="board">Brett</string>
<string name="pieces_tab">Figuren</string>
<string name="game_number">Nr. %1$s</string>
</resources>

View file

@ -109,7 +109,7 @@
<string name="threads">Hilos</string>
<string name="memory">Memoria</string>
<string name="megabytes">%1$d MB</string>
<string name="engine_battery">El motor consume batería. Se detiene solo cuando se apaga la pantalla.</string>
<string name="engine_battery">El motor consume batería. Se apaga solo cuando sales de la partida o la aplicación pasa a segundo plano.</string>
<string name="about">Acerca de</string>
<string name="build_full">Stockfish incluido</string>
<string name="build_light">Stockfish se descarga en la aplicación</string>
@ -182,4 +182,37 @@
<string name="choose_all">Marcar todas</string>
<string name="choose_none">Desmarcar todas</string>
<string name="open_missing_part">El archivo %1$s ya no está junto a la base: se movió o se borró.</string>
<string name="board_and_pieces">Tablero y piezas</string>
<string name="board_brown">Marrón</string>
<string name="board_blue">Azul</string>
<string name="board_green">Verde</string>
<string name="board_tournament">Torneo</string>
<string name="board_sand">Arena</string>
<string name="board_coral">Coral</string>
<string name="board_grey">Gris</string>
<string name="board_purple">Morado</string>
<string name="board_ice">Hielo</string>
<string name="board_navy">Azul marino</string>
<string name="board_mint">Menta</string>
<string name="board_emerald">Esmeralda</string>
<string name="board_orange">Naranja</string>
<string name="board_rose">Rosa</string>
<string name="board_dusk">Anochecer</string>
<string name="board_night">Noche</string>
<string name="board_wood">Madera</string>
<string name="board_maple">Arce</string>
<string name="board_leather">Cuero</string>
<string name="board_marble">Mármol</string>
<string name="board_blue_marble">Mármol azul</string>
<string name="board_canvas">Lienzo</string>
<string name="board_metal">Metal</string>
<string name="board_olive">Oliva</string>
<string name="board_stone">Piedra</string>
<string name="board_green_plastic">Plástico verde</string>
<string name="board_purple_diag">Diagonales moradas</string>
<string name="board_pink_pyramid">Pirámides rosas</string>
<string name="board_sketch">Boceto</string>
<string name="board">Tablero</string>
<string name="pieces_tab">Piezas</string>
<string name="game_number">N.º %1$s</string>
</resources>

View file

@ -109,7 +109,7 @@
<string name="threads">Threads</string>
<string name="memory">Mémoire</string>
<string name="megabytes">%1$d Mo</string>
<string name="engine_battery">Le moteur consomme de la batterie. Il s’arrête de lui-même quand l’écran s’éteint.</string>
<string name="engine_battery">Le moteur consomme de la batterie. Il s’éteint de lui-même quand vous quittez la partie ou que l’application passe en arrière-plan.</string>
<string name="about">À propos</string>
<string name="build_full">Stockfish intégré</string>
<string name="build_light">Stockfish téléchargé dans l’application</string>
@ -182,4 +182,37 @@
<string name="choose_all">Tout cocher</string>
<string name="choose_none">Tout décocher</string>
<string name="open_missing_part">Le fichier %1$s n’est plus à côté de la base : il a été déplacé ou supprimé.</string>
<string name="board_and_pieces">Échiquier et pièces</string>
<string name="board_brown">Marron</string>
<string name="board_blue">Bleu</string>
<string name="board_green">Vert</string>
<string name="board_tournament">Tournoi</string>
<string name="board_sand">Sable</string>
<string name="board_coral">Corail</string>
<string name="board_grey">Gris</string>
<string name="board_purple">Violet</string>
<string name="board_ice">Glace</string>
<string name="board_navy">Marine</string>
<string name="board_mint">Menthe</string>
<string name="board_emerald">Émeraude</string>
<string name="board_orange">Orange</string>
<string name="board_rose">Rose</string>
<string name="board_dusk">Crépuscule</string>
<string name="board_night">Nuit</string>
<string name="board_wood">Bois</string>
<string name="board_maple">Érable</string>
<string name="board_leather">Cuir</string>
<string name="board_marble">Marbre</string>
<string name="board_blue_marble">Marbre bleu</string>
<string name="board_canvas">Toile</string>
<string name="board_metal">Métal</string>
<string name="board_olive">Olive</string>
<string name="board_stone">Pierre</string>
<string name="board_green_plastic">Plastique vert</string>
<string name="board_purple_diag">Diagonales violettes</string>
<string name="board_pink_pyramid">Pyramides roses</string>
<string name="board_sketch">Croquis</string>
<string name="board">Échiquier</string>
<string name="pieces_tab">Pièces</string>
<string name="game_number">N° %1$s</string>
</resources>

View file

@ -109,7 +109,7 @@
<string name="threads">Thread</string>
<string name="memory">Memoria</string>
<string name="megabytes">%1$d MB</string>
<string name="engine_battery">Il motore consuma batteria. Si ferma da solo quando lo schermo si spegne.</string>
<string name="engine_battery">Il motore consuma batteria. Si spegne da solo quando esci dalla partita o l’app va in background.</string>
<string name="about">Informazioni</string>
<string name="build_full">Stockfish incluso</string>
<string name="build_light">Stockfish si scarica nell\'app</string>
@ -182,4 +182,37 @@
<string name="choose_all">Seleziona tutti</string>
<string name="choose_none">Deseleziona tutti</string>
<string name="open_missing_part">Il file %1$s non è più accanto al database: è stato spostato o eliminato.</string>
<string name="board_and_pieces">Scacchiera e pezzi</string>
<string name="board_brown">Marrone</string>
<string name="board_blue">Blu</string>
<string name="board_green">Verde</string>
<string name="board_tournament">Torneo</string>
<string name="board_sand">Sabbia</string>
<string name="board_coral">Corallo</string>
<string name="board_grey">Grigio</string>
<string name="board_purple">Viola</string>
<string name="board_ice">Ghiaccio</string>
<string name="board_navy">Blu navy</string>
<string name="board_mint">Menta</string>
<string name="board_emerald">Smeraldo</string>
<string name="board_orange">Arancione</string>
<string name="board_rose">Rosa</string>
<string name="board_dusk">Crepuscolo</string>
<string name="board_night">Notte</string>
<string name="board_wood">Legno</string>
<string name="board_maple">Acero</string>
<string name="board_leather">Pelle</string>
<string name="board_marble">Marmo</string>
<string name="board_blue_marble">Marmo blu</string>
<string name="board_canvas">Tela</string>
<string name="board_metal">Metallo</string>
<string name="board_olive">Oliva</string>
<string name="board_stone">Pietra</string>
<string name="board_green_plastic">Plastica verde</string>
<string name="board_purple_diag">Diagonali viola</string>
<string name="board_pink_pyramid">Piramidi rosa</string>
<string name="board_sketch">Schizzo</string>
<string name="board">Scacchiera</string>
<string name="pieces_tab">Pezzi</string>
<string name="game_number">N. %1$s</string>
</resources>

View file

@ -110,7 +110,7 @@
<string name="threads">Потоки</string>
<string name="memory">Память</string>
<string name="megabytes">%1$d МБ</string>
<string name="engine_battery">Движок расходует заряд. Он сам останавливается, когда гаснет экран.</string>
<string name="engine_battery">Движок расходует заряд. Он сам выключается, когда вы выходите из партии или сворачиваете приложение.</string>
<string name="about">О программе</string>
<string name="build_full">Stockfish уже внутри</string>
<string name="build_light">Stockfish скачивается в приложении</string>
@ -186,4 +186,37 @@
<string name="choose_all">Отметить все</string>
<string name="choose_none">Снять все</string>
<string name="open_missing_part">Рядом с базой больше нет файла %1$s: его переместили или удалили.</string>
<string name="board_and_pieces">Доска и фигуры</string>
<string name="board_brown">Коричневая</string>
<string name="board_blue">Синяя</string>
<string name="board_green">Зелёная</string>
<string name="board_tournament">Турнирная</string>
<string name="board_sand">Песочная</string>
<string name="board_coral">Морская</string>
<string name="board_grey">Серая</string>
<string name="board_purple">Фиолетовая</string>
<string name="board_ice">Лёд</string>
<string name="board_navy">Тёмно-синяя</string>
<string name="board_mint">Мята</string>
<string name="board_emerald">Изумруд</string>
<string name="board_orange">Оранжевая</string>
<string name="board_rose">Розовая</string>
<string name="board_dusk">Сумерки</string>
<string name="board_night">Ночь</string>
<string name="board_wood">Дерево</string>
<string name="board_maple">Клён</string>
<string name="board_leather">Кожа</string>
<string name="board_marble">Мрамор</string>
<string name="board_blue_marble">Синий мрамор</string>
<string name="board_canvas">Холст</string>
<string name="board_metal">Металл</string>
<string name="board_olive">Олива</string>
<string name="board_stone">Камень</string>
<string name="board_green_plastic">Зелёный пластик</string>
<string name="board_purple_diag">Фиолетовые диагонали</string>
<string name="board_pink_pyramid">Розовые пирамиды</string>
<string name="board_sketch">Набросок</string>
<string name="board">Доска</string>
<string name="pieces_tab">Фигуры</string>
<string name="game_number">№ %1$s</string>
</resources>

View file

@ -109,7 +109,7 @@
<string name="threads">Threads</string>
<string name="memory">Memory</string>
<string name="megabytes">%1$d MB</string>
<string name="engine_battery">The engine uses the battery. It stops by itself when the screen turns off.</string>
<string name="engine_battery">The engine uses the battery. It turns off by itself when you leave the game or the app goes to the background.</string>
<string name="about">About</string>
<string name="build_full">Stockfish built in</string>
<string name="build_light">Stockfish downloaded in the app</string>
@ -179,4 +179,39 @@
<string name="choose_all">Tick all</string>
<string name="choose_none">Untick all</string>
<string name="open_missing_part">The file %1$s is not beside the database any more: it was moved or deleted.</string>
<string name="board_and_pieces">Board and pieces</string>
<string name="board_brown">Brown</string>
<string name="board_blue">Blue</string>
<string name="board_green">Green</string>
<string name="board_tournament">Tournament</string>
<string name="board_sand">Sand</string>
<string name="board_coral">Coral</string>
<string name="board_grey">Grey</string>
<string name="board_purple">Purple</string>
<string name="board_ice">Ice</string>
<string name="board_navy">Navy</string>
<string name="board_mint">Mint</string>
<string name="board_emerald">Emerald</string>
<string name="board_orange">Orange</string>
<string name="board_rose">Rose</string>
<string name="board_dusk">Dusk</string>
<string name="board_night">Night</string>
<string name="board_wood">Wood</string>
<string name="board_maple">Maple</string>
<string name="board_leather">Leather</string>
<string name="board_marble">Marble</string>
<string name="board_blue_marble">Blue marble</string>
<string name="board_canvas">Canvas</string>
<string name="board_metal">Metal</string>
<string name="board_olive">Olive</string>
<string name="board_stone">Stone</string>
<string name="board_green_plastic">Green plastic</string>
<string name="board_purple_diag">Purple diagonal</string>
<string name="board_pink_pyramid">Pink pyramid</string>
<string name="board_sketch">Sketch</string>
<string name="board">Board</string>
<string name="board_ic" translatable="false">IC</string>
<string name="board_ncf" translatable="false">NCF</string>
<string name="pieces_tab">Pieces</string>
<string name="game_number">No. %1$s</string>
</resources>

View file

@ -26,7 +26,7 @@
3. **Доска на всю ширину сверху, под ней нотация как на компьютере.** Основная линия идёт в две колонки, комментарии и варианты — блоками во всю ширину. Ленты ходов в одну строку нет (обоснование в §7.3).
4. **Ходы листаются кнопками внизу, под большим пальцем.** Свайпов по доске и по нотации нет. Единственный жест «вбок» — системный «назад».
5. **Соседняя партия открывается стрелками ‹ › в верхней панели.** Перейти к ходу и перейти к партии невозможно перепутать: у кнопок разные места, формы и размеры значков.
6. **Движок включается одной кнопкой.** Он сам останавливается, когда гаснет экран. Старая оценка не показывается для новой позиции ни на миг. В сборке без движка эта же кнопка предлагает его скачать (§8.4).
6. **Движок включается одной кнопкой — в каждой партии заново.** Открытая партия всегда начинается с выключенным движком. Он сам выключается, когда человек выходит из партии, приложение уходит в фон или гаснет экран. Старая оценка не показывается для новой позиции ни на миг. В сборке без движка эта же кнопка предлагает его скачать (§8.4).
7. **Приложение работает без интернета.** Сеть нужна только для облачного файла и для скачивания движка в сборке без него.
8. **Вид — спокойный и аккуратный:** цвета и доска те же, что на компьютере и сайте, Material 3 без украшений (§10).
@ -307,12 +307,12 @@ FAB открывает лист, а не сразу системный выбо
│ ← Мои партии ⌕ ⇅ │ 64
│ 1 248 партий │
├────────────────────────────────────┤
│ Карлсен М. – Каруана Ф. 1-0 │ 64
│ Норвегия · 2025 · C42 ✓ │
│ Иванов П. – Сидоров А. ½-½ │
│ Первенство школы · 2024 · B90 │
│ Alekhine A. – Capablanca J. 0-1 │
│ World Championship · 1927 · D52 ✓ │
│ 1 Карлсен М. – Каруана Ф. 1-0 │ 64
│ Норвегия · 2025 · C42 ✓ │
│ 2 Иванов П. – Сидоров А. ½-½ │
│ Первенство школы · 2024 · B90 │
│ 1248 Alekhine A. – Capablanca 0-1 │
│ World Championship · 1927 · ✓ │
│ … ▐ │ бегунок быстрой прокрутки
└────────────────────────────────────┘
```
@ -321,9 +321,14 @@ FAB открывает лист, а не сразу системный выбо
### 6.2. Строка партии (64 dp)
- **Номер партии в базе** — слева, отдельной колонкой (с 2026-10-23).
- Это номер записи в файле (первая партия — 1), а не место в списке: при сортировке, поиске и фильтрах номер остаётся тем же, поэтому по нему партию можно найти снова и назвать другому человеку («открой 154-ю»).
- 14sp, цифры моноширинные (`tnum`), цвет `onSurfaceVariant`, выравнивание вправо, по центру строки по вертикали. Тысячи разделяются узким пробелом, как в счётчиках (`1 248`).
- Ширина колонки — по самому большому номеру в базе, одна на весь список, чтобы имена не прыгали при прокрутке. После колонки — 16 dp до текста.
- Номер виден и при поиске: он показывает, где найденная партия стоит в базе. «12 из 340» в заголовке экрана «Партия» — другое число, место в текущем порядке (§7.6).
- **Первая строка**, 16sp: «Белые – Чёрные».
- Имя вида «Фамилия, Имя Отчество» сокращается до «Фамилия И.», остальные имена — как в файле.
- Каждое имя обрезается многоточием и занимает не больше половины ширины, чтобы чёрные не пропадали.
- Каждое имя обрезается многоточием и занимает не больше половины ширины текста (без колонки номера), чтобы чёрные не пропадали.
- Справа колонка 40 dp с результатом, цифры моноширинные (`tnum`): `1-0`, `½-½`, `0-1`. Результат стоит на линии первой строки (выравнивание по базовой линии), а не по центру строки 64 dp.
- Результат `*` (партия без итога, учебная позиция) не показывается: в учебниках это столбик звёздочек без смысла.
- Если у чёрных пусто или `?` (позиция из учебника, этюд), первая строка — только то, что записано у белых, без « – ?». Строка без второй строки выравнивается по центру по вертикали.
@ -515,7 +520,7 @@ FAB открывает лист, а не сразу системный выбо
### 7.6. Соседняя партия
- **‹ ›** в верхней панели открывают предыдущую и следующую партию в том порядке, в каком они стояли в «Партиях» при открытии, — с учётом поиска, фильтров и сортировки. «12 из 340» — номер партии в этом порядке.
- Новая партия открывается с начала и сразу отмечается просмотренной. Включённый движок считает её начальную позицию. Если доска была перевёрнута, она такой и остаётся.
- Новая партия открывается с начала и сразу отмечается просмотренной. Это тот же экран, поэтому включённый движок остаётся включённым и считает её начальную позицию. Если доска была перевёрнута, она такой и остаётся.
- На первой партии ‹ неактивна, на последней неактивна ›.
- Партия сменяется плавно (§10.8). Стек экранов не растёт: «назад» ведёт в «Партии».
- Свайпа между партиями нет: случайно потерять место в разобранной партии хуже, чем лишний раз нажать стрелку.
@ -621,12 +626,14 @@ FAB открывает лист, а не сразу системный выбо
- Партия при этом не меняется. Вставить линию как вариант в первой версии нельзя.
- **Время.** По умолчанию движок считает позицию 20 с, потом останавливается: в строке «гл. 26 · пауза» и кнопка «Глубже» (ещё 20 с). Другие значения настройки «Время на позицию»: 10 с, 1 мин, без ограничения.
- **Батарея.**
- Если экран погас, приложение ушло в фон или открыт другой экран, движок останавливается и процесс завершается. При возврате к партии с включённой кнопкой счёт начинается заново.
- Если экран погас или приложение ушло в фон, движок останавливается, процесс завершается, а кнопка выключается: после возврата движок ждёт нажатия.
- Если поверх партии открыты Настройки (меню ⋮) или телефон повернули, процесс тоже останавливается, но кнопка остаётся включённой: после возврата счёт начинается заново сам.
- При включённой экономии заряда движок работает в один поток; один раз показывается снекбар «Экономия заряда: движок работает медленнее».
- **Сбои.** Запуск и остановка идут с таймаутами (`docs/dev/uci.md`).
- Движок не отвечает — «Движок не отвечает» и кнопка «Перезапустить».
- Движок не запускается на этом процессоре — «Движок не запускается на этом телефоне».
- **Кнопка помнит состояние:** если движок включили, он включён и в следующей партии.
- **Кнопка не запоминается между партиями** (с 2026-10-23; раньше состояние хранилось в настройках). Каждый раз, когда партия открывается из списка, движок выключен; включается он только кнопкой. Выход из партии («назад») выключает его. ‹ › внутри партии его не выключают (§7.6).
- Причина: движок, включённый вчера, не должен сам садить батарею при каждом открытии партии, а ребёнок сначала смотрит партию и только потом спрашивает оценку.
- Лицензия Stockfish (GPL-3) и его авторы указаны в «О программе».
### 8.4. Скачивание движка (сборка без движка)
@ -679,18 +686,12 @@ FAB открывает лист, а не сразу системный выбо
Настройки — один экран со списком групп, без вкладок. Изменения применяются сразу.
**Первая версия** (выбора досок и фигур нет, §16; звука пока нет):
**Как сделано сейчас** (звука пока нет; выбор доски и фигур — с 2026-10-23, §9.1):
```
┌────────────────────────────────────┐
│ ← Настройки │
├────────────────────────────────────┤
│ ВНЕШНИЙ ВИД │
│ Тема │
│ Как в системе │
│ Язык │
│ Как в системе │
├────────────────────────────────────┤
│ ПАРТИЯ │
│ Запись ходов │
│ Латинские буквы (K Q R B N) │
@ -698,6 +699,14 @@ FAB открывает лист, а не сразу системный выбо
│ Стрелка лучшего хода [●] │
│ Вибрация [●] │
├────────────────────────────────────┤
│ ВНЕШНИЙ ВИД │
│ Доска и фигуры │ отдельный экран, §9.1
│ Зелёная · merida │
│ Тема │
│ Как в системе │
│ Язык │
│ Как в системе │
├────────────────────────────────────┤
│ ДВИЖОК │
│ Stockfish 19 · встроен │ 14sp, onSurfaceVariant, без нажатия
│ Линий 2 │
@ -713,7 +722,7 @@ FAB открывает лист, а не сразу системный выбо
- Группа называется «Партия» (`s_game_group`, en «Game»): запись ходов, анимация, стрелка и вибрация относятся к просмотру партии, а не к доске.
- Строка «Stockfish 19 · встроен» — состояние, а не пункт: набирается 14sp цветом `onSurfaceVariant`, чтобы не выглядеть нажимаемой.
Полная схема на будущее (с выбором досок и фигур):
Полная схема на будущее (звук, координаты, цвета обоев). Доска и фигуры в ней теперь — одна строка «Доска и фигуры» из §9.1, а не две:
```
┌────────────────────────────────────┐
@ -748,7 +757,7 @@ FAB открывает лист, а не сразу системный выбо
└────────────────────────────────────┘
```
- **Доска и фигуры** выбираются на отдельном экране с сеткой превью. Превью — угол доски 3×3 клетки с фигурами (для фигур — на текущей доске), выбранное отмечено галочкой. Набор тот же, что на компьютере (§10.5).
- **Доска и фигуры** — §9.1.
- **Запись ходов** — диалог с тремя вариантами и образцами, как в `move-notation.md` §2.1: «Латинские буквы (K Q R B N)», «Фигурки», «Русские буквы (Кр Ф Л С К)». Под ними: «Только вид на экране. В PGN и при копировании всегда K Q R B N.» По умолчанию — латинские буквы. В английском интерфейсе третьего варианта нет.
- **Анимация фигур** только включается и выключается. Четыре скорости, как на компьютере, телефону не нужны.
- **Набора звуков** нет: используется набор по умолчанию с компьютера (`sfx`). В беззвучном режиме звука нет.
@ -759,6 +768,38 @@ FAB открывает лист, а не сразу системный выбо
- «Скачать» в настройках открывает тот же лист «Движок Stockfish» (§8.4), а не начинает загрузку молча: в листе есть предупреждение о мобильном интернете и отмена.
- Строка состояния движка зависит от сборки и §8.4: «Stockfish 19 · встроен», «Не скачан · Скачать (80 МБ)», «Скачивается… 23 из 80 МБ» или «Stockfish 19 · скачан» с пунктом «Удалить движок».
### 9.1. Экран «Доска и фигуры»
Пункт «Доска и фигуры» в группе «Внешний вид», первым. Под названием — текущий выбор: «Зелёная · merida» (имя доски, точка, имя набора). Открывает отдельный экран; «назад» возвращает в Настройки.
```
┌────────────────────────────────────┐
│ ← Доска и фигуры │
├────────────────────────────────────┤
│ ┌──────────┐ │ превью: испанская партия после 3.Сb5,
│ │ ♜ ♝♛♚♝♞♜ │ │ подсвечен ход f1–b5; не нажимается
│ │ …… │ │
│ └──────────┘ │
│ Доска │ Фигуры │ вкладки (SecondaryTabRow)
├────────────────────────────────────┤
│ [▚] [▚] [▚] [▚] │ «Доска»: 2×2 клетки или угол картинки
│ Коричн. Синяя Зелёная Турнирная │
│ … │ 37 досок
│ │ «Фигуры»: белый конь на светлой клетке,
│ │ чёрный ферзь на тёмной; 17 наборов
└────────────────────────────────────┘
```
- **Превью стоит на месте**, сетка прокручивается под ним. В портрете — по центру, 60 % ширины экрана, но не больше 240 dp, с полями 12 dp сверху и снизу. В альбомной ориентации превью занимает левую часть (поля 16 dp), сетка — правую.
- Превью — настоящая доска приложения (`Board`) с выбранными доской и фигурами, без анимации и без касаний. Для TalkBack — «Доска: Зелёная · merida».
- **Сетка** — `LazyVerticalGrid`, ячейки от 88 dp (на телефоне 360–412 dp — четыре в ряд), поля 12 dp по бокам. Над сеткой две вкладки, «Доска» и «Фигуры» (en Board / Pieces): наборы не прячутся под 37 досками. Порядок — как на компьютере (§10.5).
- **Доска** — квадрат: 2×2 клетки её цветов (a1 тёмная, слева внизу) или, у текстурных, левый нижний угол картинки 2×2 клетки. Скругление 6 dp. Под ним название доски, `bodySmall`, не больше двух строк. Одинаковые названия различаются номером: «Дерево», «Дерево 2», «Дерево 3».
- **Набор фигур** (вкладка «Фигуры») — прямоугольник 2:1: белый конь на светлой и чёрный ферзь на тёмной клетке **выбранной доски** (так тёмные наборы остаются видны, и человек сразу видит итог). Под ним имя набора как на компьютере и на Lichess — латиницей, строчными (`cburnett`, `kiwen-suwi`); имена наборов не переводятся.
- **Выбор применяется сразу** и сохраняется, кнопок «Готово» и «Отмена» нет. Превью, а за ним и доска в партии меняются мгновенно.
- **Выбранный элемент** — кольцо 3 dp цветом `primary` вокруг образца (образец внутри уменьшается на 5 dp, чтобы кольцо не налезало на клетки) и подпись цветом `primary`. Остальные подписи — `onSurfaceVariant`.
- Каждый элемент — `selectable` с ролью «переключатель» (`Role.RadioButton`): TalkBack читает «Зелёная, выбрано, переключатель». Вкладки TalkBack читает как вкладки.
- По умолчанию — «Зелёная» и merida (§10.5).
## 10. Внешний вид
Цель — «просто, понятно, симпатично». Средства: те же цвета, доски и фигуры, что на компьютере и сайте, Material 3 с тональными поверхностями вместо теней, крупная доска как главный предмет экрана и немного аккуратного движения. Никаких фоновых картинок, градиентов, эмодзи и тем «под дерево» в интерфейсе: фактура бывает только у доски.
@ -843,7 +884,7 @@ FAB открывает лист, а не сразу системный выбо
### 10.5. Доски и фигуры
- Те же файлы и цвета, что на компьютере: темы досок из `assets.rs` (`BoardThemeId`: цветные и текстурные из `apps/desktop/assets/boards`) и 17 наборов фигур из `apps/desktop/assets/pieces`. Порядок и названия — как в настройках компьютера.
- Те же файлы и цвета, что на компьютере: темы досок из `assets.rs` (`BoardThemeId`: цветные и текстурные из `apps/desktop/assets/boards`) и 17 наборов фигур из `apps/desktop/assets/pieces`. Порядок и названия — как в настройках компьютера; названия досок переведены на шесть языков интерфейса, имена наборов — нет. Выбор — §9.1.
- **По умолчанию на телефоне — доска «Зелёная» (`Green`: `#FFFFDD` / `#86A666`) и фигуры Merida.** Так играет сам владелец. Плоская зелёная доска спокойна, хорошо читается на солнце и не спорит с цветными стрелками, а Merida привычна по книгам. На компьютере значения по умолчанию остаются прежними.
- Текстурные доски на телефоне масштабируются под размер доски один раз и кэшируются как картинка.
- Цвета стрелок и полей из комментариев (зелёный, красный, жёлтый, синий) и стрелка движка — как в `board.rs`.
@ -905,7 +946,7 @@ FAB открывает лист, а не сразу системный выбо
2. **Вибрация со смыслом.** На каждом шаге лёгкий тик (`CLOCK_TICK`), в начале и в конце партии — чуть сильнее (`CONFIRM`): понятно, что дальше ходов нет, даже не глядя.
3. **Результат как печать.** После последнего хода — строка результата в скруглённой плашке `surfaceContainerHigh` по центру: «1-0 · Победили белые».
4. **Пингвин на пустых экранах.** Тот же значок встречает на пустом экране «Базы» и в «Ничего не найдено» (там в половинном размере, 48 dp). Никакой другой графики нет.
5. **Превью — на настоящей доске.** В выборе фигур превью стоит на выбранной доске, в выборе досок — с выбранными фигурами: человек видит итог, а не образец.
5. **Превью — на настоящей доске.** Над выбором стоит доска с позицией и выбранными доской и фигурами, а образцы фигур нарисованы на клетках выбранной доски: человек видит итог, а не образец (§9.1).
6. **Тихая вежливость.** Подсказка про кнопки показывается один раз. «Убрать из списка» отменяется. Движок сам себя выключает. Ничего не всплывает без причины.
## 11. Состояния и ошибки
@ -967,7 +1008,8 @@ FAB открывает лист, а не сразу системный выбо
| новый ход после ◀ ▶ (объявление) | «4… конь f6» | “4… knight f6” |
| взятие, шах, мат, рокировка | «слон берёт f7, шах»; «мат»; «короткая рокировка» | “bishop takes f7, check”; “checkmate”; “short castling” |
| плашка оценки | «Оценка плюс 0,4, глубина 22» / «Мат в 3 хода» | “Evaluation plus 0.4, depth 22” / “Mate in 3” |
| строка партии | «Карлсен – Каруана, 1-0, Норвегия, 2025, C42, просмотрена» | “Carlsen – Caruana, 1-0, Norway, 2025, C42, viewed” |
| строка партии | «№ 12, Карлсен – Каруана, 1-0, Норвегия, 2025, C42, просмотрена» | “No. 12, Carlsen – Caruana, 1-0, Norway, 2025, C42, viewed” |
| образец доски или набора (§9.1) | «Зелёная, выбрано, переключатель» / «merida, не выбрано, переключатель» | “Green, selected, radio button” / “merida, not selected, radio button” |
| кнопка «Движок» | «Движок, выключен» / «Движок, не скачан» | “Engine, off” / “Engine, not downloaded” |
| ‹ › | «Предыдущая партия» / «Следующая партия» | “Previous game” / “Next game” |
@ -1201,7 +1243,8 @@ FAB открывает лист, а не сразу системный выбо
| Ключ | RU | EN |
|---|---|---|
| `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 |
| `board_and_pieces` / `board` / `pieces_tab` | Доска и фигуры / Доска / Фигуры | Board and pieces / Board / Pieces |
| `board_*` (названия досок) | Коричневая, Синяя, Зелёная, Турнирная, … Дерево, Клён, … Набросок; IC и NCF не переводятся | Brown, Blue, Green, Tournament, … Wood, Maple, … Sketch |
| `s_notation` | Запись ходов | Move notation |
| `s_latin` / `s_figurine` / `s_local` | Латинские буквы (K Q R B N) / Фигурки / Русские буквы (Кр Ф Л С К) | Letters (K Q R B N) / Figurines / — (не показывается в английском) |
| `s_notation_note` | Только вид на экране. В PGN и при копировании всегда K Q R B N. | Display only. PGN and copied text always use K Q R B N. |
@ -1213,7 +1256,7 @@ FAB открывает лист, а не сразу системный выбо
| `s_eng_builtin` / `s_eng_downloaded` / `s_eng_missing` / `s_eng_downloading` | Stockfish 19 · встроен / Stockfish 19 · скачан / Не скачан · Скачать ({size}) / Скачивается… {done} из {total} | Stockfish 19 · built in / Stockfish 19 · downloaded / Not downloaded · Download ({size}) / Downloading… {done} of {total} |
| `s_lines` / `s_time` / `s_more` / `s_threads` / `s_memory` | Линий / Время на позицию / Дополнительно / Потоки / Память | Lines / Time per position / More / Threads / Memory |
| `s_time_inf` | Без ограничения | No limit |
| `s_battery` | Движок расходует заряд. Он сам останавливается, когда гаснет экран. | The engine uses battery. It stops by itself when the screen turns off. |
| `s_battery` | Движок расходует заряд. Он сам выключается, когда вы выходите из партии или гаснет экран. | The engine uses battery. It turns off by itself when you leave the game or the screen turns off. |
| `s_about` | О программе | About |
| `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 |
@ -1259,7 +1302,7 @@ FAB открывает лист, а не сразу системный выбо
## 16. Решения владельца (2026-10-22)
1. Тема по умолчанию — «Как в системе».
2. Зелёная доска и Merida — для всех. **В первой версии выбора досок, фигур и тем нет** (раздел настроек «Доска» откладывается); возможность менять их — задача следующих версий.
2. Зелёная доска и Merida — для всех по умолчанию. ~~В первой версии выбора досок, фигур и тем нет~~ — **заменено 2026-10-23:** доски и наборы фигур компьютера выбираются на экране «Доска и фигуры» (§9.1).
3. Подписи сборок: «Stockfish уже внутри · ≈ 95 МБ» и «Stockfish скачивается в приложении · ≈ 15 МБ» (en «Stockfish built in» / «Stockfish downloaded in the app»).
## 17. Ревью первой реализации (2026-10-22)
@ -1283,3 +1326,9 @@ FAB открывает лист, а не сразу системный выбо
- §4.1 — строки «Файл» и «Папка» на прозрачном фоне; сноска про корень памяти и «Загрузки»; вставка из буфера отложена.
- §4.3 — поиск на два уровня вглубь, пара `.cbh` + `.cbv` — одна строка; «уже в списке» и «неполная»; «Добавить N» и «Готово»; пустая папка с «Выбрать другую»; одна база — тоже списком.
- §3.2, §14.1 — «ещё не открывалась · формат словом», без размера.
## 19. Доска и фигуры, номера партий, движок (2026-10-23)
- §9, §9.1, §10.5, §10.9, §16 — выбор доски и набора фигур на отдельном экране с превью; решение §16.2 о «первой версии без выбора» заменено.
- §6.1, §6.2, §12.3 — номер партии в базе слева в строке списка, виден и при поиске.
- §0, §7.6, §8.3, §14.6 — кнопка «Движок» больше не запоминается: каждая партия открывается с выключенным движком; выход из партии, фон и погасший экран его выключают; поворот, Настройки поверх партии и ‹ › — нет.