diff --git a/CHANGELOG.md b/CHANGELOG.md index a5b532d..75b698c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/Library.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/Library.kt index 45fd8d7..888390b 100644 --- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/Library.kt +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/Library.kt @@ -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) + /// 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() private val lock = Mutex() + /// Taken off the list, "Undo" still offered: their access is kept. + private val pending = ArrayList() + + 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 { if (!file.exists()) return samples().also { save(it) } return runCatching { json.decodeFromString>(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() + 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) = 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 { + 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>() + 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) } } } diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/AddDatabase.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/AddDatabase.kt new file mode 100644 index 0000000..9081a5e --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/AddDatabase.kt @@ -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) -> 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)) + } +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/Common.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/Common.kt index 0bb4ced..0e9f687 100644 --- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/Common.kt +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/Common.kt @@ -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( diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/DatabasesScreen.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/DatabasesScreen.kt index 1eb7e37..365f583 100644 --- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/DatabasesScreen.kt +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/DatabasesScreen.kt @@ -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(null) } + var scan by remember { mutableStateOf(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(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() diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GamesScreen.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GamesScreen.kt index aa7e993..e409bc4 100644 --- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GamesScreen.kt +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GamesScreen.kt @@ -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) diff --git a/androidApp/app/src/main/res/values-de/strings.xml b/androidApp/app/src/main/res/values-de/strings.xml index a4d496a..ee600ea 100644 --- a/androidApp/app/src/main/res/values-de/strings.xml +++ b/androidApp/app/src/main/res/values-de/strings.xml @@ -3,7 +3,7 @@ Aljechin Hier erscheinen Ihre Datenbanken - Fügen Sie eine PGN-Datei oder ein .zip/.7z-Archiv hinzu — vom Telefon oder aus der Cloud. + Fügen Sie eine Datei oder einen Ordner mit Datenbanken hinzu: PGN, ChessBase, .zip- und .7z-Archive — vom Telefon oder aus der Cloud. Datenbank hinzufügen Beispielpartien öffnen noch nicht geöffnet · %1$s @@ -150,4 +150,32 @@ Die Datei ist beschädigt oder keine Schachdatenbank. Im Archiv ist keine PGN- oder ChessBase-Datenbank. Diese Art von Datenbank kann nicht gelesen werden: %1$s + Datei + PGN, .cbv, .zip oder .7z + Ordner + Alle Datenbanken in einem Ordner, auch ChessBase (.cbh) + Datenbanken werden gesucht… + Keine Datenbanken in diesem Ordner + Gefunden werden PGN-Dateien, ChessBase-Datenbanken (.cbh, .cbv) und .zip- oder .7z-Archive – im Ordner und in zwei Ebenen von Unterordnern. + schon in der Liste + die .cbg-Datei fehlt: die Partien lassen sich nicht öffnen + + %1$d Datenbank in „%2$s“ + %1$d Datenbanken in „%2$s“ + + + %1$d hinzufügen + %1$d hinzufügen + + + %1$d Datenbank hinzugefügt + %1$d Datenbanken hinzugefügt + + Android lässt weder den Speicherstamm noch „Downloads“ selbst auswählen — nur einen Ordner darin. + Anderen wählen + Fertig + Hinzufügen + Alle auswählen + Keine auswählen + Die Datei %1$s liegt nicht mehr neben der Datenbank: Sie wurde verschoben oder gelöscht. diff --git a/androidApp/app/src/main/res/values-es/strings.xml b/androidApp/app/src/main/res/values-es/strings.xml index 674c031..2840266 100644 --- a/androidApp/app/src/main/res/values-es/strings.xml +++ b/androidApp/app/src/main/res/values-es/strings.xml @@ -3,7 +3,7 @@ Alekhine Aquí aparecerán tus bases - Añade un archivo PGN o un archivo comprimido .zip/.7z — desde el teléfono o la nube. + Añade un archivo o una carpeta de bases: PGN, ChessBase, archivos .zip y .7z — desde el teléfono o la nube. Añadir base Abrir partidas de ejemplo aún sin abrir · %1$s @@ -151,4 +151,35 @@ El archivo está dañado o no es una base de ajedrez. El archivo comprimido no contiene ninguna base PGN ni ChessBase. Este tipo de base no se puede leer: %1$s + Archivo + PGN, .cbv, .zip o .7z + Carpeta + Todas las bases de una carpeta, también ChessBase (.cbh) + Buscando bases… + No hay bases en esta carpeta + Se encuentran archivos PGN, bases de ChessBase (.cbh, .cbv) y archivos .zip o .7z, en la carpeta y en dos niveles de subcarpetas. + ya está en la lista + falta el archivo .cbg: las partidas no se pueden abrir + + %1$d base en «%2$s» + %1$d de bases en «%2$s» + %1$d bases en «%2$s» + + + Añadir %1$d + Añadir %1$d + Añadir %1$d + + + %1$d base añadida + %1$d de bases añadidas + %1$d bases añadidas + + Android no deja elegir la raíz del almacenamiento ni «Descargas» en sí: solo una carpeta dentro de ellas. + Elegir otra + Hecho + Añadir + Marcar todas + Desmarcar todas + El archivo %1$s ya no está junto a la base: se movió o se borró. diff --git a/androidApp/app/src/main/res/values-fr/strings.xml b/androidApp/app/src/main/res/values-fr/strings.xml index f706ad7..168293d 100644 --- a/androidApp/app/src/main/res/values-fr/strings.xml +++ b/androidApp/app/src/main/res/values-fr/strings.xml @@ -3,7 +3,7 @@ Alekhine Vos bases apparaîtront ici - Ajoutez un fichier PGN ou une archive .zip/.7z — depuis votre téléphone ou le cloud. + Ajoutez un fichier ou un dossier de bases : PGN, ChessBase, archives .zip et .7z — depuis votre téléphone ou le cloud. Ajouter une base Ouvrir les parties d’exemple pas encore ouverte · %1$s @@ -151,4 +151,35 @@ Le fichier est endommagé ou n’est pas une base d’échecs. L’archive ne contient aucune base PGN ou ChessBase. Ce type de base ne peut pas être lu : %1$s + Fichier + PGN, .cbv, .zip ou .7z + Dossier + Toutes les bases d’un dossier, y compris ChessBase (.cbh) + Recherche des bases… + Aucune base dans ce dossier + Sont recherchés : fichiers PGN, bases ChessBase (.cbh, .cbv) et archives .zip ou .7z, dans le dossier et deux niveaux de sous-dossiers. + déjà dans la liste + le fichier .cbg manque : les parties ne s’ouvrent pas + + %1$d base dans « %2$s » + %1$d de bases dans « %2$s » + %1$d bases dans « %2$s » + + + Ajouter %1$d + Ajouter %1$d + Ajouter %1$d + + + %1$d base ajoutée + %1$d de bases ajoutées + %1$d bases ajoutées + + Android ne laisse choisir ni la racine du stockage ni « Téléchargements » lui-même — seulement un dossier à l’intérieur. + Choisir un autre + Terminé + Ajouter + Tout cocher + Tout décocher + Le fichier %1$s n’est plus à côté de la base : il a été déplacé ou supprimé. diff --git a/androidApp/app/src/main/res/values-it/strings.xml b/androidApp/app/src/main/res/values-it/strings.xml index 81f4e24..801f988 100644 --- a/androidApp/app/src/main/res/values-it/strings.xml +++ b/androidApp/app/src/main/res/values-it/strings.xml @@ -3,7 +3,7 @@ Alekhine Qui compariranno i tuoi database - Aggiungi un file PGN o un archivio .zip/.7z — dal telefono o dal cloud. + Aggiungi un file o una cartella di database: PGN, ChessBase, archivi .zip e .7z — dal telefono o dal cloud. Aggiungi database Apri le partite di esempio non ancora aperto · %1$s @@ -151,4 +151,35 @@ Il file è danneggiato o non è un database scacchistico. Nell\'archivio non c\'è alcun database PGN o ChessBase. Questo tipo di database non può essere letto: %1$s + File + PGN, .cbv, .zip o .7z + Cartella + Tutti i database di una cartella, anche ChessBase (.cbh) + Cerco i database… + Nessun database in questa cartella + Vengono trovati file PGN, database ChessBase (.cbh, .cbv) e archivi .zip o .7z, nella cartella e in due livelli di sottocartelle. + già nell’elenco + manca il file .cbg: le partite non si possono aprire + + %1$d database in «%2$s» + %1$d di database in «%2$s» + %1$d database in «%2$s» + + + Aggiungi %1$d + Aggiungi %1$d + Aggiungi %1$d + + + %1$d database aggiunto + %1$d di database aggiunti + %1$d database aggiunti + + Android non permette di scegliere la radice della memoria né «Download» stessa: solo una cartella al loro interno. + Scegli un’altra + Fatto + Aggiungi + Seleziona tutti + Deseleziona tutti + Il file %1$s non è più accanto al database: è stato spostato o eliminato. diff --git a/androidApp/app/src/main/res/values-ru/strings.xml b/androidApp/app/src/main/res/values-ru/strings.xml index ff6a12c..69980e3 100644 --- a/androidApp/app/src/main/res/values-ru/strings.xml +++ b/androidApp/app/src/main/res/values-ru/strings.xml @@ -3,7 +3,7 @@ Алехин Здесь будут ваши базы - Добавьте файл PGN или архив .zip/.7z — с телефона или из облака. + Добавьте файл или папку с базами: PGN, ChessBase, архивы .zip и .7z — с телефона или из облака. Добавить базу Открыть примеры партий ещё не открывалась · %1$s @@ -152,4 +152,38 @@ Файл повреждён или это не шахматная база. В архиве нет базы PGN или ChessBase. Такую базу прочитать нельзя: %1$s + Файл + PGN, .cbv, .zip или .7z + Папка + Все базы в папке, в том числе ChessBase (.cbh) + Ищу базы… + В папке нет баз + Подходят файлы PGN, базы ChessBase (.cbh, .cbv) и архивы .zip и .7z — в самой папке и во вложенных папках на два уровня. + уже в списке + нет файла .cbg — партии не открыть + + В папке «%2$s» найдена %1$d база + В папке «%2$s» найдены %1$d базы + В папке «%2$s» найдено %1$d баз + В папке «%2$s» найдено %1$d базы + + + Добавить %1$d + Добавить %1$d + Добавить %1$d + Добавить %1$d + + + Добавлена %1$d база + Добавлены %1$d базы + Добавлено %1$d баз + Добавлено %1$d базы + + Корень памяти и саму «Загрузки» выбрать нельзя — только папку внутри них. + Выбрать другую + Готово + Добавить + Отметить все + Снять все + Рядом с базой больше нет файла %1$s: его переместили или удалили. diff --git a/androidApp/app/src/main/res/values/strings.xml b/androidApp/app/src/main/res/values/strings.xml index cafa7fc..c692666 100644 --- a/androidApp/app/src/main/res/values/strings.xml +++ b/androidApp/app/src/main/res/values/strings.xml @@ -4,7 +4,7 @@ Alekhine Your databases will appear here - Add a PGN file or a .zip/.7z archive — from your phone or the cloud. + Add a file or a folder of databases: PGN, ChessBase, .zip and .7z archives — from your phone or the cloud. Add database Open sample games not opened yet · %1$s @@ -151,4 +151,32 @@ The file is damaged or is not a chess database. There is no PGN or ChessBase database in the archive. This kind of database cannot be read: %1$s + File + PGN, .cbv, .zip or .7z + Folder + Every database in a folder, ChessBase (.cbh) too + Looking for databases… + No databases in this folder + Looks for PGN files, ChessBase databases (.cbh, .cbv) and .zip or .7z archives in the folder and two levels of folders inside it. + already on the list + no .cbg file — the games can’t be opened + + %1$d database in “%2$s” + %1$d databases in “%2$s” + + + Add %1$d + Add %1$d + + + %1$d database added + %1$d databases added + + Android won’t let apps pick the storage root or Downloads itself — only a folder inside them. + Pick another + Done + Add + Tick all + Untick all + The file %1$s is not beside the database any more: it was moved or deleted. diff --git a/crates/chess-import/src/chessbase/mod.rs b/crates/chess-import/src/chessbase/mod.rs index 976e08e..b545ac5 100644 --- a/crates/chess-import/src/chessbase/mod.rs +++ b/crates/chess-import/src/chessbase/mod.rs @@ -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 { 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); + } +} diff --git a/crates/mobile-api/src/lib.rs b/crates/mobile-api/src/lib.rs index a3df3fc..c082003 100644 --- a/crates/mobile-api/src/lib.rs +++ b/crates/mobile-api/src/lib.rs @@ -169,7 +169,6 @@ pub fn open_file(name: String, fd: i32) -> Result, ApiError> { #[cfg(unix)] fn read_fd(fd: i32) -> Result, 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, 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, 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) -> Result)> = 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) -> Result Option { +fn owned_fd(fd: i32) -> Option { 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) }) diff --git a/docs/design/android-ui.md b/docs/design/android-ui.md index 7ddf44b..042d27f 100644 --- a/docs/design/android-ui.md +++ b/docs/design/android-ui.md @@ -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 — «ещё не открывалась · формат словом», без размера.