Android: add a folder — every database in it, ChessBase databases (.cbh) too
Some checks are pending
CI / check (push) Waiting to run
CI / windows-build (push) Waiting to run
CI / macos-build (push) Waiting to run

«Добавить базу» offers a file or a folder. A folder is looked through two levels down;
the databases found are offered with tick boxes: PGN, archives, .cbv and ChessBase sets
(.cbh with the files beside it, names in any case), each a separate entry. A .cbv beside
its own set is not offered twice, a set without its .cbg is shown but not added, and
databases already on the list (also picked as a file) are marked. The folder's read
permission is kept while one of its databases is on the list or can still be restored
with Undo, and access no entry uses is given back at start. A moved file or a missing
.cbg is said in plain words. Reviewed by the designer and the tester.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vrubelroman 2026-10-22 22:27:14 +03:00
parent 356384b13e
commit a8978c765b
15 changed files with 826 additions and 69 deletions

View file

@ -4,7 +4,12 @@ All notable changes are listed here. Versions follow [Semantic Versioning](https
## [Unreleased]
- Keys in a game: ↑ goes to the end, ↓ to the start (as End and Home); variations are
- Android: **add a folder** — every database in it and in the folders inside it (two
levels) is offered with a tick box: PGN files, archives, ChessBase archives (`.cbv`) and
ChessBase databases (`.cbh` with the files beside it), which a single picked file could
not open. A ChessBase database without its `.cbg` is shown but not added; databases
already on the list are marked. Picking the folder again offers what is new.
- Desktop, keys in a game: ↑ goes to the end, ↓ to the start (as End and Home); variations are
switched with Shift+↑/↓. Escape first closes what is open (a preview of an engine line,
a picked-up piece); then it goes back to the game this one was opened from, or to the
library. A window, menu or dialog over the game keeps Escape for itself, and a game with

View file

@ -3,6 +3,7 @@ package io.github.vrubelroman.chesspenguin.data
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.DocumentsContract
import android.provider.OpenableColumns
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
@ -15,7 +16,9 @@ import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import uniffi.mobile_api.ApiException
import uniffi.mobile_api.Database
import uniffi.mobile_api.FolderFile
import uniffi.mobile_api.openBytes
import uniffi.mobile_api.openChessbase
import uniffi.mobile_api.openFile
import java.io.File
import java.util.UUID
@ -26,8 +29,12 @@ enum class Source {
/// One of the sample games of the desktop app, inside the app (assets/examples).
Sample,
/// A file the user picked; read in place through its persisted permission.
/// A file the user picked, or found in a picked folder; read in place through its
/// persisted permission (of the file, or of the folder: [DbEntry.tree]).
File,
/// A ChessBase database (`.cbh` with `.cbg`, `.cba`, … beside it) in a picked folder.
ChessBase,
}
/// A database on the list. The file itself is never changed.
@ -36,16 +43,61 @@ data class DbEntry(
val id: String,
val name: String,
val source: Source,
/// The asset path of a sample, the content URI of a file.
/// The asset path of a sample, the content URI of a file; for a ChessBase database,
/// the URI of the folder it is in.
val location: String,
/// The file's name, for its extension (PGN, .zip, .7z, .cbv).
/// The file's name, for its extension (PGN, .zip, .7z, .cbv, .cbh).
val fileName: String,
/// The picked folder whose permission covers this database (none for a picked file).
val tree: String? = null,
/// The file's size when it was added: with the name, how the same file is known when
/// it is picked again through another way (a folder, or on its own).
val size: Long? = null,
val games: Int? = null,
val format: String? = null,
/// A sample shows the name of the current language until it is renamed (displayName).
val renamed: Boolean = false,
)
/// A database found in a picked folder, offered to be added.
data class Found(
val name: String,
val fileName: String,
/// What [DbEntry.location] becomes.
val location: String,
val source: Source,
/// Where it lies inside the picked folder ("" at its top), shown with the name.
val path: String,
val size: Long? = null,
/// A ChessBase database without its games file (`.cbg`): it cannot be opened.
val incomplete: Boolean = false,
/// Already on the list.
val added: Boolean = false,
)
/// A file of a ChessBase database is not beside its `.cbh` any more.
class MissingPart(val file: String) : Exception(file)
/// Names as people sort them: "g2" before "g10", letters without case.
fun naturalOrder(a: String, b: String): Int {
val chunk = Regex("\\d+|\\D+")
val x = chunk.findAll(a.lowercase()).map { it.value }.toList()
val y = chunk.findAll(b.lowercase()).map { it.value }.toList()
for (i in 0 until minOf(x.size, y.size)) {
val (p, q) = x[i] to y[i]
val c = if (p[0].isDigit() && q[0].isDigit()) {
compareValuesBy(p, q, { it.trimStart('0').length }, { it.trimStart('0') })
} else {
p.compareTo(q)
}
if (c != 0) return c
}
return x.size - y.size
}
/// What a picked folder holds.
data class FolderScan(val tree: Uri, val name: String, val found: List<Found>)
/// The databases on the list and the open ones (docs/design/android-ui.md §3).
class Library(private val context: Context) {
private val file = File(context.filesDir, "library.json")
@ -57,6 +109,25 @@ class Library(private val context: Context) {
private val open = HashMap<String, Database>()
private val lock = Mutex()
/// Taken off the list, "Undo" still offered: their access is kept.
private val pending = ArrayList<DbEntry>()
init {
releaseUnused()
}
/// Gives back the access to files and folders no database on the list uses (a
/// folder picked, then the app closed before anything was added from it; the app
/// closed while "Undo" was offered).
private fun releaseUnused() {
val used = _entries.value.mapNotNull { it.tree ?: it.location.takeIf { _ -> it.source != Source.Sample } }.toSet()
for (p in context.contentResolver.persistedUriPermissions) {
if (p.uri.toString() !in used) {
runCatching { context.contentResolver.releasePersistableUriPermission(p.uri, Intent.FLAG_GRANT_READ_URI_PERMISSION) }
}
}
}
private fun load(): List<DbEntry> {
if (!file.exists()) return samples().also { save(it) }
return runCatching { json.decodeFromString<List<DbEntry>>(file.readText()) }.getOrDefault(emptyList())
@ -95,17 +166,23 @@ class Library(private val context: Context) {
runCatching {
context.contentResolver.takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
_entries.value.firstOrNull { it.location == uri.toString() }?.let {
val fileName = displayName(uri) ?: "database.pgn"
val size = fileSize(uri)
_entries.value.firstOrNull { it.location == uri.toString() || sameFile(it, fileName, size) }?.let {
// The entry keeps its own way to the file; the new permission is not needed.
if (it.location != uri.toString()) {
runCatching { context.contentResolver.releasePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION) }
}
open.remove(it.id)?.close()
return it
}
val fileName = displayName(uri) ?: "database.pgn"
val entry = DbEntry(
id = UUID.randomUUID().toString(),
name = fileName.substringBeforeLast('.'),
source = Source.File,
location = uri.toString(),
fileName = fileName,
size = size,
)
update { it + entry }
return entry
@ -120,6 +197,7 @@ class Library(private val context: Context) {
val i = list.indexOfFirst { it.id == id }
if (i < 0) return null
val e = list[i]
pending += e
update { it.filterNot { x -> x.id == id } }
open.remove(id)?.close()
return i to e
@ -127,16 +205,168 @@ class Library(private val context: Context) {
/// Gives the access to a removed file back to the system, once "Undo" is gone.
fun forget(entry: DbEntry) {
if (entry.source != Source.File || _entries.value.any { it.location == entry.location }) return
pending.remove(entry)
if (entry.source == Source.Sample) return
// The permission of a folder is given back with the last of its databases, also
// counting those whose "Undo" is still offered.
val granted = entry.tree ?: entry.location
if ((_entries.value + pending).any { (it.tree ?: it.location) == granted }) return
runCatching {
context.contentResolver.releasePersistableUriPermission(Uri.parse(entry.location), Intent.FLAG_GRANT_READ_URI_PERMISSION)
context.contentResolver.releasePersistableUriPermission(Uri.parse(granted), Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
}
/// Keeps the read permission of a picked folder, for the databases added from it
/// (given back by [forgetFolder] when none is).
fun keepFolder(tree: Uri) {
runCatching {
context.contentResolver.takePersistableUriPermission(tree, Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
}
/// Looks for databases in a picked folder and in the folders inside it (two levels
/// down): PGN files, archives, ChessBase archives (.cbv) and ChessBase databases.
suspend fun scanFolder(tree: Uri): FolderScan = withContext(Dispatchers.IO) {
val rootId = DocumentsContract.getTreeDocumentId(tree)
val rootName = childName(DocumentsContract.buildDocumentUriUsingTree(tree, rootId)) ?: ""
val list = _entries.value
val found = ArrayList<Found>()
fun visit(dirId: String, path: String, depth: Int) {
val children = children(tree, dirId)
val names = children.filter { !it.dir }.map { it.name }.toSet()
fun has(name: String) = names.any { it.equals(name, ignoreCase = true) }
for (c in children.sortedWith { a, b -> naturalOrder(a.name, b.name) }) {
if (c.dir) continue
val ext = c.name.substringAfterLast('.', "").lowercase()
val stem = c.name.substringBeforeLast('.')
when (ext) {
"pgn", "zip", "7z", "cbv" -> {
// A ChessBase archive beside its unpacked database is the same
// database: the unpacked one is offered.
if (ext == "cbv" && has("$stem.cbh") && has("$stem.cbg")) continue
val uri = DocumentsContract.buildDocumentUriUsingTree(tree, c.id).toString()
val added = list.any { it.location == uri || sameFile(it, c.name, c.size) }
found += Found(stem, c.name, uri, Source.File, path, size = c.size, added = added)
}
"cbh" -> {
val dir = DocumentsContract.buildDocumentUriUsingTree(tree, dirId).toString()
found += Found(
stem, c.name, dir, Source.ChessBase, path,
incomplete = !has("$stem.cbg"),
added = list.any { it.source == Source.ChessBase && it.location == dir && it.fileName == c.name },
)
}
}
}
if (depth < 2) {
for (c in children.filter { it.dir }.sortedWith { a, b -> naturalOrder(a.name, b.name) }) {
visit(c.id, if (path.isEmpty()) c.name else "$path/${c.name}", depth + 1)
}
}
}
visit(rootId, "", 0)
FolderScan(tree, rootName, found)
}
/// Gives a scanned folder's permission back when none of its databases is on the list.
fun forgetFolder(tree: Uri) {
if ((_entries.value + pending).any { it.tree == tree.toString() }) return
runCatching {
context.contentResolver.releasePersistableUriPermission(tree, Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
}
/// Puts the chosen databases of a folder on the list, at its end.
fun addFound(tree: Uri, chosen: List<Found>) = update { list ->
list + chosen.filter { !it.added && !it.incomplete }.map {
DbEntry(
id = UUID.randomUUID().toString(),
name = it.name,
source = it.source,
location = it.location,
fileName = it.fileName,
tree = tree.toString(),
size = it.size,
)
}
}
private class Child(val id: String, val name: String, val dir: Boolean, val size: Long?)
private fun children(tree: Uri, dirId: String): List<Child> {
val uri = DocumentsContract.buildChildDocumentsUriUsingTree(tree, dirId)
val columns = arrayOf(
DocumentsContract.Document.COLUMN_DOCUMENT_ID,
DocumentsContract.Document.COLUMN_DISPLAY_NAME,
DocumentsContract.Document.COLUMN_MIME_TYPE,
DocumentsContract.Document.COLUMN_SIZE,
)
return runCatching {
context.contentResolver.query(uri, columns, null, null, null)?.use { c ->
buildList {
while (c.moveToNext()) {
val name = c.getString(1) ?: continue
val size = if (c.isNull(3)) null else c.getLong(3)
add(Child(c.getString(0), name, c.getString(2) == DocumentsContract.Document.MIME_TYPE_DIR, size))
}
}
}
}.getOrNull() ?: emptyList()
}
private fun childName(uri: Uri): String? = runCatching {
context.contentResolver.query(uri, arrayOf(DocumentsContract.Document.COLUMN_DISPLAY_NAME), null, null, null)?.use { c ->
if (c.moveToFirst()) c.getString(0) else null
}
}.getOrNull()
/// A file for reading. A file deleted from a picked folder makes the provider throw
/// IllegalArgumentException ("is not a child of the tree"): it is a missing file.
private fun openDocument(uri: Uri): android.os.ParcelFileDescriptor = try {
context.contentResolver.openFileDescriptor(uri, "r") ?: throw java.io.FileNotFoundException(uri.toString())
} catch (e: IllegalArgumentException) {
throw java.io.FileNotFoundException(e.message)
}
/// The files of a ChessBase database: those beside its `.cbh` with the same name.
private fun openChessBase(e: DbEntry): Database {
val tree = Uri.parse(e.tree ?: throw ApiException.Io(detail = "no access to the folder"))
val dirId = DocumentsContract.getDocumentId(Uri.parse(e.location))
val stem = e.fileName.substringBeforeLast('.')
// Names may differ in case (sets copied from Windows: "Base.CBH", "base.cbg").
val parts = children(tree, dirId).filter { !it.dir && it.name.substringBeforeLast('.').equals(stem, ignoreCase = true) }
if (parts.none { it.name.equals(e.fileName, ignoreCase = true) }) throw java.io.FileNotFoundException(e.fileName)
if (parts.none { it.name.substringAfterLast('.').equals("cbg", ignoreCase = true) }) throw MissingPart("$stem.cbg")
// All opened first: a file that cannot be opened leaves none of them open.
val opened = ArrayList<Pair<String, android.os.ParcelFileDescriptor>>()
try {
for (c in parts) {
val pfd = openDocument(DocumentsContract.buildDocumentUriUsingTree(tree, c.id))
opened += c.name to pfd
}
} catch (t: Throwable) {
opened.forEach { it.second.close() }
throw t
}
// The descriptors go over to the core, which closes them.
return openChessbase(e.fileName, opened.map { (name, pfd) -> FolderFile(name, pfd.detachFd()) })
}
fun restore(place: Int, entry: DbEntry) {
pending.remove(entry)
update { it.toMutableList().apply { add(place.coerceIn(0, size), entry) } }
}
/// The same file on the list, picked through another way (its URI differs).
private fun sameFile(e: DbEntry, fileName: String, size: Long?) =
e.source == Source.File && size != null && e.size == size && e.fileName == fileName
private fun fileSize(uri: Uri): Long? = runCatching {
context.contentResolver.query(uri, arrayOf(OpenableColumns.SIZE), null, null, null)?.use { c ->
if (c.moveToFirst() && !c.isNull(0)) c.getLong(0) else null
}
}.getOrNull()
private fun displayName(uri: Uri): String? = runCatching {
context.contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { c ->
if (c.moveToFirst()) c.getString(0) else null
@ -151,11 +381,8 @@ class Library(private val context: Context) {
runCatching {
when (e.source) {
Source.Sample -> openBytes(e.fileName, context.assets.open(e.location).use { it.readBytes() })
Source.File -> {
val pfd = context.contentResolver.openFileDescriptor(Uri.parse(e.location), "r")
?: throw ApiException.Io(detail = "no access to the file")
openFile(e.fileName, pfd.detachFd())
}
Source.File -> openFile(e.fileName, openDocument(Uri.parse(e.location)).detachFd())
Source.ChessBase -> openChessBase(e)
}
}
}

View file

@ -0,0 +1,193 @@
package io.github.vrubelroman.chesspenguin.ui
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.selection.toggleable
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Description
import androidx.compose.material.icons.outlined.Folder
import androidx.compose.material3.Button
import androidx.compose.material3.Checkbox
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.ListItem
import androidx.compose.material3.ListItemDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.pluralStringResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.heading
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import io.github.vrubelroman.chesspenguin.R
import io.github.vrubelroman.chesspenguin.data.FolderScan
import io.github.vrubelroman.chesspenguin.data.Found
import io.github.vrubelroman.chesspenguin.data.Source
/// "Add a database": a file, or every database in a folder.
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AddSheet(onFile: () -> Unit, onFolder: () -> Unit, onDismiss: () -> Unit) {
ModalBottomSheet(onDismissRequest = onDismiss) {
Column(Modifier.navigationBarsPadding().padding(bottom = 24.dp)) {
Text(
stringResource(R.string.add_database),
style = MaterialTheme.typography.titleLarge,
modifier = Modifier.padding(horizontal = 24.dp, vertical = 8.dp).semantics { heading() },
)
ListItem(
headlineContent = { Text(stringResource(R.string.add_file)) },
supportingContent = { Text(stringResource(R.string.add_file_hint)) },
leadingContent = { Icon(Icons.Outlined.Description, null) },
colors = ListItemDefaults.colors(containerColor = Color.Transparent),
modifier = Modifier.clickable(role = Role.Button, onClick = onFile).padding(horizontal = 8.dp),
)
ListItem(
headlineContent = { Text(stringResource(R.string.add_folder)) },
supportingContent = { Text(stringResource(R.string.add_folder_hint)) },
leadingContent = { Icon(Icons.Outlined.Folder, null) },
colors = ListItemDefaults.colors(containerColor = Color.Transparent),
modifier = Modifier.clickable(role = Role.Button, onClick = onFolder).padding(horizontal = 8.dp),
)
// The system picker only says "Can't use this folder" in English, and gives
// nothing back: so it is said before.
Text(
stringResource(R.string.add_tree_hint),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(horizontal = 24.dp, vertical = 8.dp),
)
}
}
}
/// The databases found in a picked folder, to tick and add; `scan` is null while the
/// folder is being looked through.
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun FolderSheet(scan: FolderScan?, onAdd: (List<Found>) -> Unit, onPickAnother: () -> Unit, onDismiss: () -> Unit) {
// Open in full at once: the buttons under the list are always on the screen.
ModalBottomSheet(onDismissRequest = onDismiss, sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)) {
Column(Modifier.navigationBarsPadding().padding(horizontal = 24.dp).padding(bottom = 24.dp)) {
if (scan == null) {
Row(Modifier.fillMaxWidth().height(96.dp), verticalAlignment = Alignment.CenterVertically) {
CircularProgressIndicator(Modifier.size(24.dp), strokeWidth = 3.dp)
Spacer(Modifier.size(16.dp))
Text(stringResource(R.string.folder_scanning), style = MaterialTheme.typography.bodyLarge)
}
return@Column
}
val addable = scan.found.filter { !it.added && !it.incomplete }
if (scan.found.isEmpty()) {
Text(stringResource(R.string.folder_empty_title), style = MaterialTheme.typography.titleLarge, modifier = Modifier.semantics { heading() })
Spacer(Modifier.height(8.dp))
Text(
stringResource(R.string.folder_empty_text),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Spacer(Modifier.height(24.dp))
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End)) {
TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) }
Button(onClick = onPickAnother) { Text(stringResource(R.string.pick_another)) }
}
return@Column
}
// Everything that can be added is ticked at first.
var chosen by remember(scan) { mutableStateOf(addable.toSet()) }
Text(
pluralStringResource(R.plurals.folder_found, scan.found.size, scan.found.size, scan.name),
style = MaterialTheme.typography.titleLarge,
modifier = Modifier.semantics { heading() },
)
if (addable.size > 1) {
val all = chosen.size == addable.size
TextButton(onClick = { chosen = if (all) emptySet() else addable.toSet() }, contentPadding = PaddingValues(0.dp)) {
Text(stringResource(if (all) R.string.choose_none else R.string.choose_all))
}
}
Spacer(Modifier.height(8.dp))
LazyColumn(Modifier.weight(1f, fill = false)) {
itemsIndexed(scan.found) { _, f ->
FoundRow(f, f in chosen) { on -> chosen = if (on) chosen + f else chosen - f }
}
}
Spacer(Modifier.height(16.dp))
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End)) {
if (addable.isEmpty()) {
// Everything there is already on the list (or cannot be opened).
Button(onClick = onDismiss) { Text(stringResource(R.string.done)) }
} else {
TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) }
Button(onClick = { onAdd(scan.found.filter { it in chosen }) }, enabled = chosen.isNotEmpty()) {
Text(if (chosen.isEmpty()) stringResource(R.string.add) else pluralStringResource(R.plurals.add_chosen, chosen.size, chosen.size))
}
}
}
}
}
}
@Composable
private fun FoundRow(f: Found, checked: Boolean, onChange: (Boolean) -> Unit) {
val enabled = !f.added && !f.incomplete
val label = when {
f.source == Source.ChessBase -> "CB"
else -> f.fileName.substringAfterLast('.', "").uppercase().let { if (it == "CBV") "CB" else it }
}
val note = when {
f.added -> stringResource(R.string.folder_added)
f.incomplete -> stringResource(R.string.folder_incomplete)
else -> f.fileName
}
Row(
Modifier
.fillMaxWidth()
.heightIn(min = 64.dp)
.toggleable(value = checked || f.added, enabled = enabled, role = Role.Checkbox, onValueChange = onChange),
verticalAlignment = Alignment.CenterVertically,
) {
Checkbox(checked = checked || f.added, onCheckedChange = null, enabled = enabled)
Spacer(Modifier.size(12.dp))
FormatBadge(label, error = f.incomplete)
Column(Modifier.weight(1f).padding(start = 16.dp)) {
Text(f.name, style = MaterialTheme.typography.bodyLarge, maxLines = 1, overflow = TextOverflow.Ellipsis)
val where = if (f.path.isEmpty()) note else "${f.path} · $note"
Text(
where,
style = MaterialTheme.typography.bodyMedium,
color = if (f.incomplete) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
)
}
Box(Modifier.size(8.dp))
}
}

View file

@ -52,6 +52,15 @@ fun badge(e: DbEntry): String {
}
}
/// The format of a database in words, as the core names it once it is opened.
fun formatName(e: DbEntry): String = when (e.fileName.substringAfterLast('.', "").lowercase()) {
"cbh" -> "ChessBase"
"cbv" -> "ChessBase CBV"
"zip" -> "ZIP"
"7z" -> "7z"
else -> "PGN"
}
@Composable
fun FormatBadge(text: String, error: Boolean = false) {
Box(

View file

@ -50,6 +50,9 @@ import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
@ -64,6 +67,7 @@ import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import io.github.vrubelroman.chesspenguin.R
import io.github.vrubelroman.chesspenguin.data.DbEntry
import io.github.vrubelroman.chesspenguin.data.FolderScan
import io.github.vrubelroman.chesspenguin.data.Source
import kotlinx.coroutines.launch
@ -80,7 +84,25 @@ fun DatabasesScreen(onOpen: (String) -> Unit, onSettings: () -> Unit) {
val pick = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
if (uri != null) onOpen(library.addFile(uri).id)
}
val add = { pick.launch(arrayOf("*/*")) }
var choosing by remember { mutableStateOf(false) }
// The folder sheet: shown while `folderOpen`, `scan` null while looking through it.
// The picked folder outlives a rotation; it is then looked through again.
var folderOpen by rememberSaveable { mutableStateOf(false) }
var folder by rememberSaveable { mutableStateOf<android.net.Uri?>(null) }
var scan by remember { mutableStateOf<FolderScan?>(null) }
LaunchedEffect(folderOpen, folder) {
val tree = folder
if (folderOpen && tree != null && scan?.tree != tree) scan = library.scanFolder(tree)
}
val pickFolder = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocumentTree()) { tree ->
if (tree != null) {
scan = null
library.keepFolder(tree)
folder = tree
folderOpen = true
}
}
val add = { choosing = true }
var renaming by remember { mutableStateOf<DbEntry?>(null) }
val list = rememberLazyListState()
val expanded by remember { derivedStateOf { list.firstVisibleItemIndex == 0 } }
@ -104,7 +126,10 @@ fun DatabasesScreen(onOpen: (String) -> Unit, onSettings: () -> Unit) {
snackbarHost = { SnackbarHost(snackbar) },
floatingActionButton = {
if (entries.isNotEmpty()) {
val addLabel = stringResource(R.string.add_database)
ExtendedFloatingActionButton(
// Folded while the list is scrolled: its label is still read out.
modifier = Modifier.semantics { contentDescription = addLabel },
onClick = add,
expanded = expanded,
icon = { Icon(Icons.Rounded.Add, null) },
@ -147,6 +172,46 @@ fun DatabasesScreen(onOpen: (String) -> Unit, onSettings: () -> Unit) {
}
}
}
val context = androidx.compose.ui.platform.LocalContext.current
if (choosing) {
AddSheet(
onFile = {
choosing = false
pick.launch(arrayOf("*/*"))
},
onFolder = {
choosing = false
pickFolder.launch(null)
},
onDismiss = { choosing = false },
)
}
if (folderOpen) {
FolderSheet(
scan,
onAdd = { chosen ->
val s = scan ?: return@FolderSheet
library.addFound(s.tree, chosen)
folderOpen = false
val n = chosen.count { !it.added && !it.incomplete }
scope.launch {
snackbar.currentSnackbarData?.dismiss()
snackbar.showSnackbar(context.resources.getQuantityString(R.plurals.added_count, n, n))
}
// Nothing added: the folder's permission goes back.
if (n == 0) library.forgetFolder(s.tree)
},
onPickAnother = {
folderOpen = false
folder?.let { library.forgetFolder(it) }
pickFolder.launch(null)
},
onDismiss = {
folderOpen = false
folder?.let { library.forgetFolder(it) }
},
)
}
renaming?.let { e ->
RenameDialog(displayName(e), onDismiss = { renaming = null }, onSave = {
library.rename(e.id, it)
@ -190,7 +255,7 @@ private fun DatabaseRow(e: DbEntry, onOpen: () -> Unit, onRename: () -> Unit, on
val format = badge(e)
val subtitle = e.games?.let {
stringResource(R.string.games_with_format, pluralStringResource(R.plurals.games_count, it, groupDigits(it)), e.format ?: format)
} ?: stringResource(R.string.not_opened, format)
} ?: stringResource(R.string.not_opened, formatName(e))
Row(
modifier
.fillMaxWidth()

View file

@ -210,6 +210,7 @@ private fun Message(title: String, detail: String, action: (@Composable () -> Un
/// Why a database did not open, in plain words with the next step (§11).
@Composable
private fun openProblem(e: Throwable): String = when (e) {
is io.github.vrubelroman.chesspenguin.data.MissingPart -> stringResource(R.string.open_missing_part, e.file)
is SecurityException, is java.io.FileNotFoundException, is ApiException.Io -> stringResource(R.string.open_no_access)
is ApiException.Corrupt -> stringResource(R.string.open_corrupt)
is ApiException.Empty -> stringResource(R.string.open_empty)

View file

@ -3,7 +3,7 @@
<string name="sample_alekhine">Aljechin</string>
<string name="empty_title">Hier erscheinen Ihre Datenbanken</string>
<string name="empty_text">Fügen Sie eine PGN-Datei oder ein .zip/.7z-Archiv hinzu — vom Telefon oder aus der Cloud.</string>
<string name="empty_text">Fügen Sie eine Datei oder einen Ordner mit Datenbanken hinzu: PGN, ChessBase, .zip- und .7z-Archive — vom Telefon oder aus der Cloud.</string>
<string name="add_database">Datenbank hinzufügen</string>
<string name="open_samples">Beispielpartien öffnen</string>
<string name="not_opened">noch nicht geöffnet · %1$s</string>
@ -150,4 +150,32 @@
<string name="open_corrupt">Die Datei ist beschädigt oder keine Schachdatenbank.</string>
<string name="open_empty">Im Archiv ist keine PGN- oder ChessBase-Datenbank.</string>
<string name="open_unsupported">Diese Art von Datenbank kann nicht gelesen werden: %1$s</string>
<string name="add_file">Datei</string>
<string name="add_file_hint">PGN, .cbv, .zip oder .7z</string>
<string name="add_folder">Ordner</string>
<string name="add_folder_hint">Alle Datenbanken in einem Ordner, auch ChessBase (.cbh)</string>
<string name="folder_scanning">Datenbanken werden gesucht…</string>
<string name="folder_empty_title">Keine Datenbanken in diesem Ordner</string>
<string name="folder_empty_text">Gefunden werden PGN-Dateien, ChessBase-Datenbanken (.cbh, .cbv) und .zip- oder .7z-Archive – im Ordner und in zwei Ebenen von Unterordnern.</string>
<string name="folder_added">schon in der Liste</string>
<string name="folder_incomplete">die .cbg-Datei fehlt: die Partien lassen sich nicht öffnen</string>
<plurals name="folder_found">
<item quantity="one">%1$d Datenbank in „%2$s“</item>
<item quantity="other">%1$d Datenbanken in „%2$s“</item>
</plurals>
<plurals name="add_chosen">
<item quantity="one">%1$d hinzufügen</item>
<item quantity="other">%1$d hinzufügen</item>
</plurals>
<plurals name="added_count">
<item quantity="one">%1$d Datenbank hinzugefügt</item>
<item quantity="other">%1$d Datenbanken hinzugefügt</item>
</plurals>
<string name="add_tree_hint">Android lässt weder den Speicherstamm noch „Downloads“ selbst auswählen — nur einen Ordner darin.</string>
<string name="pick_another">Anderen wählen</string>
<string name="done">Fertig</string>
<string name="add">Hinzufügen</string>
<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>
</resources>

View file

@ -3,7 +3,7 @@
<string name="sample_alekhine">Alekhine</string>
<string name="empty_title">Aquí aparecerán tus bases</string>
<string name="empty_text">Añade un archivo PGN o un archivo comprimido .zip/.7z — desde el teléfono o la nube.</string>
<string name="empty_text">Añade un archivo o una carpeta de bases: PGN, ChessBase, archivos .zip y .7z — desde el teléfono o la nube.</string>
<string name="add_database">Añadir base</string>
<string name="open_samples">Abrir partidas de ejemplo</string>
<string name="not_opened">aún sin abrir · %1$s</string>
@ -151,4 +151,35 @@
<string name="open_corrupt">El archivo está dañado o no es una base de ajedrez.</string>
<string name="open_empty">El archivo comprimido no contiene ninguna base PGN ni ChessBase.</string>
<string name="open_unsupported">Este tipo de base no se puede leer: %1$s</string>
<string name="add_file">Archivo</string>
<string name="add_file_hint">PGN, .cbv, .zip o .7z</string>
<string name="add_folder">Carpeta</string>
<string name="add_folder_hint">Todas las bases de una carpeta, también ChessBase (.cbh)</string>
<string name="folder_scanning">Buscando bases…</string>
<string name="folder_empty_title">No hay bases en esta carpeta</string>
<string name="folder_empty_text">Se encuentran archivos PGN, bases de ChessBase (.cbh, .cbv) y archivos .zip o .7z, en la carpeta y en dos niveles de subcarpetas.</string>
<string name="folder_added">ya está en la lista</string>
<string name="folder_incomplete">falta el archivo .cbg: las partidas no se pueden abrir</string>
<plurals name="folder_found">
<item quantity="one">%1$d base en «%2$s»</item>
<item quantity="many">%1$d de bases en «%2$s»</item>
<item quantity="other">%1$d bases en «%2$s»</item>
</plurals>
<plurals name="add_chosen">
<item quantity="one">Añadir %1$d</item>
<item quantity="many">Añadir %1$d</item>
<item quantity="other">Añadir %1$d</item>
</plurals>
<plurals name="added_count">
<item quantity="one">%1$d base añadida</item>
<item quantity="many">%1$d de bases añadidas</item>
<item quantity="other">%1$d bases añadidas</item>
</plurals>
<string name="add_tree_hint">Android no deja elegir la raíz del almacenamiento ni «Descargas» en sí: solo una carpeta dentro de ellas.</string>
<string name="pick_another">Elegir otra</string>
<string name="done">Hecho</string>
<string name="add">Añadir</string>
<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>
</resources>

View file

@ -3,7 +3,7 @@
<string name="sample_alekhine">Alekhine</string>
<string name="empty_title">Vos bases apparaîtront ici</string>
<string name="empty_text">Ajoutez un fichier PGN ou une archive .zip/.7z — depuis votre téléphone ou le cloud.</string>
<string name="empty_text">Ajoutez un fichier ou un dossier de bases : PGN, ChessBase, archives .zip et .7z — depuis votre téléphone ou le cloud.</string>
<string name="add_database">Ajouter une base</string>
<string name="open_samples">Ouvrir les parties d’exemple</string>
<string name="not_opened">pas encore ouverte · %1$s</string>
@ -151,4 +151,35 @@
<string name="open_corrupt">Le fichier est endommagé ou n’est pas une base d’échecs.</string>
<string name="open_empty">L’archive ne contient aucune base PGN ou ChessBase.</string>
<string name="open_unsupported">Ce type de base ne peut pas être lu : %1$s</string>
<string name="add_file">Fichier</string>
<string name="add_file_hint">PGN, .cbv, .zip ou .7z</string>
<string name="add_folder">Dossier</string>
<string name="add_folder_hint">Toutes les bases d’un dossier, y compris ChessBase (.cbh)</string>
<string name="folder_scanning">Recherche des bases…</string>
<string name="folder_empty_title">Aucune base dans ce dossier</string>
<string name="folder_empty_text">Sont recherchés : fichiers PGN, bases ChessBase (.cbh, .cbv) et archives .zip ou .7z, dans le dossier et deux niveaux de sous-dossiers.</string>
<string name="folder_added">déjà dans la liste</string>
<string name="folder_incomplete">le fichier .cbg manque : les parties ne s’ouvrent pas</string>
<plurals name="folder_found">
<item quantity="one">%1$d base dans « %2$s »</item>
<item quantity="many">%1$d de bases dans « %2$s »</item>
<item quantity="other">%1$d bases dans « %2$s »</item>
</plurals>
<plurals name="add_chosen">
<item quantity="one">Ajouter %1$d</item>
<item quantity="many">Ajouter %1$d</item>
<item quantity="other">Ajouter %1$d</item>
</plurals>
<plurals name="added_count">
<item quantity="one">%1$d base ajoutée</item>
<item quantity="many">%1$d de bases ajoutées</item>
<item quantity="other">%1$d bases ajoutées</item>
</plurals>
<string name="add_tree_hint">Android ne laisse choisir ni la racine du stockage ni « Téléchargements » lui-même — seulement un dossier à l’intérieur.</string>
<string name="pick_another">Choisir un autre</string>
<string name="done">Terminé</string>
<string name="add">Ajouter</string>
<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>
</resources>

View file

@ -3,7 +3,7 @@
<string name="sample_alekhine">Alekhine</string>
<string name="empty_title">Qui compariranno i tuoi database</string>
<string name="empty_text">Aggiungi un file PGN o un archivio .zip/.7z — dal telefono o dal cloud.</string>
<string name="empty_text">Aggiungi un file o una cartella di database: PGN, ChessBase, archivi .zip e .7z — dal telefono o dal cloud.</string>
<string name="add_database">Aggiungi database</string>
<string name="open_samples">Apri le partite di esempio</string>
<string name="not_opened">non ancora aperto · %1$s</string>
@ -151,4 +151,35 @@
<string name="open_corrupt">Il file è danneggiato o non è un database scacchistico.</string>
<string name="open_empty">Nell\'archivio non c\'è alcun database PGN o ChessBase.</string>
<string name="open_unsupported">Questo tipo di database non può essere letto: %1$s</string>
<string name="add_file">File</string>
<string name="add_file_hint">PGN, .cbv, .zip o .7z</string>
<string name="add_folder">Cartella</string>
<string name="add_folder_hint">Tutti i database di una cartella, anche ChessBase (.cbh)</string>
<string name="folder_scanning">Cerco i database…</string>
<string name="folder_empty_title">Nessun database in questa cartella</string>
<string name="folder_empty_text">Vengono trovati file PGN, database ChessBase (.cbh, .cbv) e archivi .zip o .7z, nella cartella e in due livelli di sottocartelle.</string>
<string name="folder_added">già nell’elenco</string>
<string name="folder_incomplete">manca il file .cbg: le partite non si possono aprire</string>
<plurals name="folder_found">
<item quantity="one">%1$d database in «%2$s»</item>
<item quantity="many">%1$d di database in «%2$s»</item>
<item quantity="other">%1$d database in «%2$s»</item>
</plurals>
<plurals name="add_chosen">
<item quantity="one">Aggiungi %1$d</item>
<item quantity="many">Aggiungi %1$d</item>
<item quantity="other">Aggiungi %1$d</item>
</plurals>
<plurals name="added_count">
<item quantity="one">%1$d database aggiunto</item>
<item quantity="many">%1$d di database aggiunti</item>
<item quantity="other">%1$d database aggiunti</item>
</plurals>
<string name="add_tree_hint">Android non permette di scegliere la radice della memoria né «Download» stessa: solo una cartella al loro interno.</string>
<string name="pick_another">Scegli un’altra</string>
<string name="done">Fatto</string>
<string name="add">Aggiungi</string>
<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>
</resources>

View file

@ -3,7 +3,7 @@
<string name="sample_alekhine">Алехин</string>
<string name="empty_title">Здесь будут ваши базы</string>
<string name="empty_text">Добавьте файл PGN или архив .zip/.7z — с телефона или из облака.</string>
<string name="empty_text">Добавьте файл или папку с базами: PGN, ChessBase, архивы .zip и .7z — с телефона или из облака.</string>
<string name="add_database">Добавить базу</string>
<string name="open_samples">Открыть примеры партий</string>
<string name="not_opened">ещё не открывалась · %1$s</string>
@ -152,4 +152,38 @@
<string name="open_corrupt">Файл повреждён или это не шахматная база.</string>
<string name="open_empty">В архиве нет базы PGN или ChessBase.</string>
<string name="open_unsupported">Такую базу прочитать нельзя: %1$s</string>
<string name="add_file">Файл</string>
<string name="add_file_hint">PGN, .cbv, .zip или .7z</string>
<string name="add_folder">Папка</string>
<string name="add_folder_hint">Все базы в папке, в том числе ChessBase (.cbh)</string>
<string name="folder_scanning">Ищу базы…</string>
<string name="folder_empty_title">В папке нет баз</string>
<string name="folder_empty_text">Подходят файлы PGN, базы ChessBase (.cbh, .cbv) и архивы .zip и .7z — в самой папке и во вложенных папках на два уровня.</string>
<string name="folder_added">уже в списке</string>
<string name="folder_incomplete">нет файла .cbg — партии не открыть</string>
<plurals name="folder_found">
<item quantity="one">В папке «%2$s» найдена %1$d база</item>
<item quantity="few">В папке «%2$s» найдены %1$d базы</item>
<item quantity="many">В папке «%2$s» найдено %1$d баз</item>
<item quantity="other">В папке «%2$s» найдено %1$d базы</item>
</plurals>
<plurals name="add_chosen">
<item quantity="one">Добавить %1$d</item>
<item quantity="few">Добавить %1$d</item>
<item quantity="many">Добавить %1$d</item>
<item quantity="other">Добавить %1$d</item>
</plurals>
<plurals name="added_count">
<item quantity="one">Добавлена %1$d база</item>
<item quantity="few">Добавлены %1$d базы</item>
<item quantity="many">Добавлено %1$d баз</item>
<item quantity="other">Добавлено %1$d базы</item>
</plurals>
<string name="add_tree_hint">Корень памяти и саму «Загрузки» выбрать нельзя — только папку внутри них.</string>
<string name="pick_another">Выбрать другую</string>
<string name="done">Готово</string>
<string name="add">Добавить</string>
<string name="choose_all">Отметить все</string>
<string name="choose_none">Снять все</string>
<string name="open_missing_part">Рядом с базой больше нет файла %1$s: его переместили или удалили.</string>
</resources>

View file

@ -4,7 +4,7 @@
<string name="sample_alekhine">Alekhine</string>
<string name="empty_title">Your databases will appear here</string>
<string name="empty_text">Add a PGN file or a .zip/.7z archive — from your phone or the cloud.</string>
<string name="empty_text">Add a file or a folder of databases: PGN, ChessBase, .zip and .7z archives — from your phone or the cloud.</string>
<string name="add_database">Add database</string>
<string name="open_samples">Open sample games</string>
<string name="not_opened">not opened yet · %1$s</string>
@ -151,4 +151,32 @@
<string name="open_corrupt">The file is damaged or is not a chess database.</string>
<string name="open_empty">There is no PGN or ChessBase database in the archive.</string>
<string name="open_unsupported">This kind of database cannot be read: %1$s</string>
<string name="add_file">File</string>
<string name="add_file_hint">PGN, .cbv, .zip or .7z</string>
<string name="add_folder">Folder</string>
<string name="add_folder_hint">Every database in a folder, ChessBase (.cbh) too</string>
<string name="folder_scanning">Looking for databases…</string>
<string name="folder_empty_title">No databases in this folder</string>
<string name="folder_empty_text">Looks for PGN files, ChessBase databases (.cbh, .cbv) and .zip or .7z archives in the folder and two levels of folders inside it.</string>
<string name="folder_added">already on the list</string>
<string name="folder_incomplete">no .cbg file — the games can’t be opened</string>
<plurals name="folder_found">
<item quantity="one">%1$d database in “%2$s”</item>
<item quantity="other">%1$d databases in “%2$s”</item>
</plurals>
<plurals name="add_chosen">
<item quantity="one">Add %1$d</item>
<item quantity="other">Add %1$d</item>
</plurals>
<plurals name="added_count">
<item quantity="one">%1$d database added</item>
<item quantity="other">%1$d databases added</item>
</plurals>
<string name="add_tree_hint">Android won’t let apps pick the storage root or Downloads itself — only a folder inside them.</string>
<string name="pick_another">Pick another</string>
<string name="done">Done</string>
<string name="add">Add</string>
<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>
</resources>

View file

@ -74,8 +74,9 @@ impl Files {
files: HashMap::new(),
};
for (name, data) in members {
// Names differ in case in sets copied from Windows ("Base.CBH", "base.cbg").
if let Some(ext) = name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase())
&& stem_of(name) == stem
&& stem_of(name).to_lowercase() == stem.to_lowercase()
&& USED.contains(&ext.as_str())
{
files.files.insert(ext, data.to_vec());
@ -237,3 +238,23 @@ fn le_i32(bytes: &[u8], at: usize) -> Option<i32> {
let s = bytes.get(at..at + 4)?;
Some(i32::from_le_bytes([s[0], s[1], s[2], s[3]]))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn members_whose_names_differ_in_case_belong_to_the_database() {
let members = [
("Base.CBH", &b"h"[..]),
("base.cbg", &b"g"[..]),
("BASE.Cba", &b"a"[..]),
("Other.cbg", &b"x"[..]),
];
let files = Files::from_members("Base.CBH", members);
assert_eq!(files.get("cbh"), Some(&b"h"[..]));
assert_eq!(files.get("cbg"), Some(&b"g"[..]));
assert_eq!(files.get("cba"), Some(&b"a"[..]));
assert_eq!(files.files.len(), 3);
}
}

View file

@ -169,7 +169,6 @@ pub fn open_file(name: String, fd: i32) -> Result<Arc<Database>, ApiError> {
#[cfg(unix)]
fn read_fd(fd: i32) -> Result<Vec<u8>, ApiError> {
use std::io::Read;
use std::os::fd::FromRawFd;
if fd < 0 {
return Err(ApiError::Io {
@ -178,7 +177,11 @@ fn read_fd(fd: i32) -> Result<Vec<u8>, ApiError> {
}
// SAFETY: the caller hands the descriptor over (detached from its owner); the File
// owns and closes it.
let mut file = unsafe { std::fs::File::from_raw_fd(fd) };
read_all(unsafe { std::fs::File::from_raw_fd(fd) })
}
fn read_all(mut file: std::fs::File) -> Result<Vec<u8>, ApiError> {
use std::io::Read;
let mut bytes = Vec::new();
file.read_to_end(&mut bytes).map_err(|e| ApiError::Io {
detail: e.to_string(),
@ -212,14 +215,23 @@ pub fn open_chessbase(cbh_name: String, files: Vec<FolderFile>) -> Result<Arc<Da
let stem = cbh_name
.rsplit_once('.')
.map_or(cbh_name.as_str(), |(s, _)| s);
// Every descriptor is owned (and so closed) from here on, also when one fails.
let owned: Vec<(String, Option<std::fs::File>)> = files
.into_iter()
.map(|f| (f.name, owned_fd(f.fd)))
.collect();
let mut contents = Vec::new();
for f in files {
let same = f.name.rsplit_once('.').is_some_and(|(s, _)| s == stem);
if same {
contents.push((f.name, read_fd(f.fd)?));
} else {
// Closed without reading.
drop(read_fd_closed(f.fd));
for (name, file) in owned {
if name
.rsplit_once('.')
.is_some_and(|(s, _)| s.to_lowercase() == stem.to_lowercase())
{
let Some(file) = file else {
return Err(ApiError::Io {
detail: format!("no file {name}"),
});
};
contents.push((name, read_all(file)?));
}
}
Ok(wrap(chess_import::open_chessbase_files(
@ -231,7 +243,7 @@ pub fn open_chessbase(cbh_name: String, files: Vec<FolderFile>) -> Result<Arc<Da
}
#[cfg(unix)]
fn read_fd_closed(fd: i32) -> Option<std::fs::File> {
fn owned_fd(fd: i32) -> Option<std::fs::File> {
use std::os::fd::FromRawFd;
// SAFETY: as in `read_fd`: the descriptor is ours to close.
(fd >= 0).then(|| unsafe { std::fs::File::from_raw_fd(fd) })

View file

@ -143,7 +143,7 @@
- Слева плашка формата 40 dp с текстом `PGN`, `CB`, `ZIP` или `7Z` (§10.6). У базы с ошибкой вместо неё `!` на фоне `errorContainer`.
- Имя базы 16sp. Под ним 14sp цветом `onSurfaceVariant`: «N партий · формат».
- Числа сокращаются как на компьютере (`short_count`): «870 тыс. партий», «1,6 млн партий»; меньше 100 000 — полностью, с пробелом между разрядами.
- Пока базу ни разу не открывали, вторая строка — «ещё не открывалась · PGN, 12 МБ».
- Пока базу ни разу не открывали, вторая строка — «ещё не открывалась · PGN». Формат словом, как после открытия: `PGN`, `ChessBase`, `архив 7z`, `архив ZIP`; не код плашки `CB`. Размера нет: у баз из папки его нет без лишнего запроса.
- Разделителей между строками нет.
- Базы идут в порядке добавления, новые внизу.
- Нажатие открывает «Партии». Долгое нажатие и ⋮ открывают одно и то же меню: «Переименовать», «Сведения», «Убрать из списка».
@ -183,28 +183,30 @@
### 4.1. Лист «Добавить базу»
FAB открывает лист, а не сразу системный выбор файла: базе ChessBase нужен свой путь, и его надо показать заранее.
FAB открывает лист, а не сразу системный выбор: базе ChessBase из нескольких файлов нужна папка, и это надо показать заранее. Лист — `ModalBottomSheet` как у движка (§8.4), строки — `ListItem` на прозрачном фоне, без своей заливки.
```
┌────────────────────────────────────┐
│ ─── │
│ Добавить базу │
│ Добавить базу │ 22sp
│ [▤] Файл │ 72
│ PGN, архив .zip/.7z, .cbv │
│ [▣] Папка с базой ChessBase │ 72
│ .cbh вместе с соседними │
│ файлами │
│ [⎘] Вставить PGN из буфера │ 56
│ Android не даёт выбрать саму папку │ 12sp, onSurfaceVariant
│ «Загрузки». Положите базу во │
│ вложенную, например Загрузки/Шахматы│
│ PGN, .cbv, .zip или .7z │
│ [▣] Папка │ 72
│ Все базы в папке, в том числе │
│ ChessBase (.cbh) │
│ Корень памяти и саму «Загрузки» │ 12sp, onSurfaceVariant
│ выбрать нельзя — только папку │
│ внутри них. │
└────────────────────────────────────┘
```
- Сноска внизу — единственное место, где объясняется запрет Android. Системный выбор папки сам пишет «Can't use this folder» по-английски и предлагает создать папку; наша строка заранее говорит, что делать.
- «Вставить PGN из буфера» (§4.5) — позже, в листе появится третьей строкой.
### 4.2. «Файл»
- Используется `ACTION_OPEN_DOCUMENT` с MIME `*/*`, один файл. Формат определяется по содержимому, как в `chess_import::open`. Сразу после выбора приложение берёт постоянный доступ (`takePersistableUriPermission`).
- Строка базы появляется в списке и начинает читаться (§5). Если базу добавили с пустого экрана, сразу открываются её «Партии».
- Строка базы появляется в списке и открываются её «Партии».
- **Выбран `.cbh`** (или `.cbg`, `.cba` и т. п.) — диалог:
> **Нужна вся папка**
@ -214,23 +216,52 @@ FAB открывает лист, а не сразу системный выбо
Выбор папки открывается там, где лежал файл (`EXTRA_INITIAL_URI`), если система это позволяет.
- **Файл уже в списке** — второй строки не появляется. Снекбар «Эта база уже в списке», список прокручивается к ней.
### 4.3. «Папка с базой ChessBase»
### 4.3. «Папка»
- Используется `ACTION_OPEN_DOCUMENT_TREE` с постоянным доступом на чтение.
- В выбранной папке, без вложенных, ищутся `.cbh` вместе с соседними файлами, а также `.cbv`, `.pgn`, `.zip` и `.7z`.
- Найдена одна база — она добавляется сразу.
- Найдено несколько — лист с флажками, отмечены все:
- `ACTION_OPEN_DOCUMENT_TREE`, постоянный доступ на чтение берётся сразу и возвращается системе, если из папки ничего не добавили (отмена, пустая папка).
- Ищутся `.pgn`, `.zip`, `.7z`, `.cbv` и `.cbh` в самой папке и во вложенных на два уровня. Порядок — по алфавиту внутри каждой папки, сначала файлы, потом вложенные папки.
- **Пара `.cbh` + `.cbv` с одним именем в одной папке** — это одна база (`.cbv` — её архив). Показывается одна строка, `.cbh`; `.cbv` не предлагается.
- Лист открывается сразу во всю высоту (`skipPartiallyExpanded`), кнопки всегда видны под списком.
```
В папке 3 базы
☑ Турниры 2000–2025 870 тыс.
☑ Ученики 2 140
☑ openings.pgn 12 МБ
[Отмена] [Добавить (3)]
```
- Ни одной — диалог «В этой папке нет баз. Выберите папку, где лежит файл .cbh.» с кнопками «Выбрать другую» и «Отмена».
- Если рядом с `.cbh` нет `.cbg`, строка неактивна и подписана «Не хватает файла .cbg».
- Если система отказала в выборе папки, повторяем подсказку про «Загрузки» из листа.
**Поиск** (обычно доли секунды, на облачной папке дольше):
```
│ ◌ Ищу базы… │ 96, индикатор 24 dp
```
Лист можно закрыть и во время поиска.
**Найдено** — список с флажками, отмечено всё, что можно добавить:
```
┌────────────────────────────────────┐
│ В папке «Шахматы» найдено 7 баз │ 22sp, может в две строки
│ ☑ [CB] Endgame Manual │ 64, вся строка — флажок
│ Endgame Manual.cbh │ 14sp onSurfaceVariant
│ ☑ [PGN] Классика │
│ Книги/Ещё · Классика.pgn │ путь · файл
│ ☑ [PGN] Alekhin │ флажок отмечен и неактивен
│ уже в списке │
│ ☐ [CB] Неполная │ плашка errorContainer,
│ Книги · нет файла .cbg — │ подпись цветом error,
│ партии не открыть │ до двух строк
│ Отмена [Добавить 6]│
└────────────────────────────────────┘
```
- Первая строка — имя без расширения; вторая — где лежит внутри выбранной папки и имя файла (у файла в самой папке — только имя файла). Так две разные базы с одинаковым именем различаются путём.
- **Уже в списке** — та же база (тот же файл; у файла, добавленного через «Файл», — по имени и размеру). Флажок отмечен и неактивен.
- **Неполная** — `.cbh` без `.cbg`: флажок снят и неактивен, плашка `CB` на `errorContainer`.
- Кнопка — «Добавить N», N — число отмеченных; при N = 0 неактивна. Если добавить нечего (всё уже в списке или неполное) — одна кнопка «Готово».
- После добавления лист закрывается, базы встают в конец списка, снекбар «Добавлено 6 баз». Сразу ничего не открывается: базы читаются при первом открытии, до этого строка — «ещё не открывалась · ChessBase» (§3.2).
- **Ни одной базы:**
> **В папке нет баз**
> Подходят файлы PGN, базы ChessBase (.cbh, .cbv) и архивы .zip и .7z — в самой папке и во вложенных папках на два уровня.
> [Отмена] [Выбрать другую]
«Выбрать другую» снова открывает системный выбор папки.
- Одна найденная база тоже показывается списком из одной строки: человек видит, что именно добавится.
### 4.4. Файл на месте или копия
@ -1011,7 +1042,7 @@ FAB открывает лист, а не сразу системный выбо
| `db_add` | Добавить базу | Add database |
| `db_examples` | Открыть примеры партий | Open sample games |
| `db_games` | {n} партий · {format} | {n} games · {format} |
| `db_not_opened` | ещё не открывалась · {format}, {size} | not opened yet · {format}, {size} |
| `db_not_opened` | ещё не открывалась · {format} | not opened yet · {format} |
| `db_reading` | читаю… {n} | reading… {n} |
| `db_copying` | копирую… {p} % | copying… {p}% |
| `db_no_access` | Нет доступа к файлу | No access to the file |
@ -1035,18 +1066,23 @@ FAB открывает лист, а не сразу системный выбо
| `info_copy` | Копия в ChessPenguin (из {source}) | Copy in ChessPenguin (from {source}) |
| `info_notes` | Замечания ({n}) | Notes ({n}) |
| `add_title` | Добавить базу | Add database |
| `add_file` / `add_file_sub` | Файл / PGN, архив .zip/.7z, .cbv | File / PGN, .zip/.7z archive, .cbv |
| `add_folder` / `add_folder_sub` | Папка с базой ChessBase / .cbh вместе с соседними файлами | ChessBase database folder / .cbh with the files next to it |
| `add_paste` | Вставить PGN из буфера | Paste PGN from the clipboard |
| `add_download_hint` | Android не даёт выбрать саму папку «Загрузки». Положите базу во вложенную, например Загрузки/Шахматы. | Android does not let apps pick the Downloads folder itself. Put the database in a folder inside it, e.g. Downloads/Chess. |
| `add_file` / `add_file_hint` | Файл / PGN, .cbv, .zip или .7z | File / PGN, .cbv, .zip or .7z |
| `add_folder` / `add_folder_hint` | Папка / Все базы в папке, в том числе ChessBase (.cbh) | Folder / Every database in a folder, ChessBase (.cbh) too |
| `add_paste` | Вставить PGN из буфера (позже) | Paste PGN from the clipboard (later) |
| `add_tree_hint` | Корень памяти и саму «Загрузки» выбрать нельзя — только папку внутри них. | Android won't let apps pick the storage root or Downloads itself — only a folder inside them. |
| `cbh_title` | Нужна вся папка | The whole folder is needed |
| `cbh_body` | База ChessBase — это несколько файлов рядом: .cbh, .cbg, .cba и другие. Выберите папку, в которой они лежат. | A ChessBase database is several files side by side: .cbh, .cbg, .cba and others. Pick the folder they are in. |
| `cbh_pick` | Выбрать папку | Pick folder |
| `folder_found` | В папке {n} баз | {n} databases in the folder |
| `folder_add` | Добавить ({n}) | Add ({n}) |
| `folder_none` | В этой папке нет баз. Выберите папку, где лежит файл .cbh. | No databases in this folder. Pick the folder with the .cbh file. |
| `folder_scanning` | Ищу базы… | Looking for databases… |
| `folder_found` | В папке «{name}» найдено {n} баз | {n} databases in “{name}” |
| `add_chosen` | Добавить {n} | Add {n} |
| `added_count` | Добавлено {n} баз | {n} databases added |
| `folder_added` | уже в списке | already on the list |
| `folder_incomplete` | нет файла .cbg — партии не открыть | no .cbg file — the games can't be opened |
| `folder_empty_title` | В папке нет баз | No databases in this folder |
| `folder_empty_text` | Подходят файлы PGN, базы ChessBase (.cbh, .cbv) и архивы .zip и .7z — в самой папке и во вложенных папках на два уровня. | Looks for PGN files, ChessBase databases (.cbh, .cbv) and .zip or .7z archives in the folder and two levels of folders inside it. |
| `folder_other` | Выбрать другую | Pick another |
| `folder_missing_cbg` | Не хватает файла .cbg | The .cbg file is missing |
| `done` | Готово | Done |
| `cloud_copy` | Файл в облаке. ChessPenguin сохранит копию у себя: {size}. | The file is in the cloud. ChessPenguin will keep a copy: {size}. |
| `cloud_copy_ok` | Сохранить копию | Save a copy |
| `paste_none` | В буфере нет партии в формате PGN | No PGN game in the clipboard |
@ -1186,7 +1222,7 @@ FAB открывает лист, а не сразу системный выбо
### 15.1. Первая версия
- **Базы:** список, пустой экран с примерами, добавление файла и папки ChessBase, вставка PGN, «Открыть с помощью» и «Поделиться», переименование, сведения, «Убрать из списка», «Нет доступа» → «Найти».
- **Базы:** список, пустой экран с примерами, добавление файла и папки (все базы в ней), «Открыть с помощью» и «Поделиться», переименование, сведения, «Убрать из списка», «Нет доступа» → «Найти».
- **Форматы** — всё, что читает компьютер (`docs/dev/import.md`). Расчёт на базы до ~1 млн партий и PGN до 200 МБ.
- **Партии:** строки, поиск, сортировка, фильтры и чипы для больших баз, быстрая прокрутка, отметка «просмотрена», текстовые главы.
- **Партия:** доска, стрелки и поля из комментариев, нотация с вариантами и комментариями, строка «Дальше», ◀ ▶ ⏮ ⏭, переворот доски, ‹ › соседняя партия, сведения, копирование PGN и FEN, «Поделиться» файлом, режим чтения, замечания совместимости, подсказка при касании доски.
@ -1242,3 +1278,8 @@ FAB открывает лист, а не сразу системный выбо
- §10.6 — ◀ ▶ значком `play_arrow` 32 dp.
- §14.4, §14.5 — состояния кнопки «Движок» для TalkBack, «depth» вместо «d» в английском.
## 18. Ревью «Добавить папку» (2026-10-22)
- §4.1 — строки «Файл» и «Папка» на прозрачном фоне; сноска про корень памяти и «Загрузки»; вставка из буфера отложена.
- §4.3 — поиск на два уровня вглубь, пара `.cbh` + `.cbv` — одна строка; «уже в списке» и «неполная»; «Добавить N» и «Готово»; пустая папка с «Выбрать другую»; одна база — тоже списком.
- §3.2, §14.1 — «ещё не открывалась · формат словом», без размера.