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

@ -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>