diff --git a/CHANGELOG.md b/CHANGELOG.md index 883235d..7d6bc3b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,18 @@ All notable changes are listed here. Versions follow [Semantic Versioning](https ## [Unreleased] +- Android: **paste PGN** — when the clipboard holds text, «Add a database» offers to paste + it: the games are kept in the app as a database and opened (one game on the board at + once). Text with no game in it is said so. +- Android: **open with ChessPenguin** — PGN, ZIP, 7z and ChessBase archives (`.cbv`) open + from other apps (Telegram, a file manager, «Share»): the file is copied into the app, + put on the list and opened. The same file again opens the same database. - Android: the engine button turns the engine off again (in 0.11.1 it only turned it on). +- Android: a smoother screen while the engine thinks — its words are shown up to five + times a second and redraw only the engine strip and the arrows; Stockfish runs below the + app's priority and takes 2 threads by default (a value chosen in Settings stays). +- PGN: a game whose tags follow the previous game's result on the same line (`… 1-0 + [Event "B"]`, as pasted text often has it) now shows its players in the games list too. ## [0.11.1] — 2026-10-23 diff --git a/Cargo.lock b/Cargo.lock index 389d6d9..e57a81a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4547,6 +4547,7 @@ checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" name = "uci" version = "0.11.1" dependencies = [ + "libc", "thiserror 2.0.21", ] diff --git a/androidApp/app/src/main/AndroidManifest.xml b/androidApp/app/src/main/AndroidManifest.xml index 473f472..0ed3b3f 100644 --- a/androidApp/app/src/main/AndroidManifest.xml +++ b/androidApp/app/src/main/AndroidManifest.xml @@ -12,13 +12,37 @@ android:theme="@style/Theme.ChessPenguin" android:localeConfig="@xml/locales_config" android:enableOnBackInvokedCallback="true"> + + android:exported="true" + android:launchMode="singleTask"> + + + + + + + + + + + + + + + + + + + + + diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ChessPenguinApp.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ChessPenguinApp.kt index 10aca49..9f34b28 100644 --- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ChessPenguinApp.kt +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ChessPenguinApp.kt @@ -4,12 +4,21 @@ import android.app.Application import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue +import android.net.Uri +import android.provider.OpenableColumns +import io.github.vrubelroman.chesspenguin.data.DbEntry import io.github.vrubelroman.chesspenguin.data.EngineFiles import io.github.vrubelroman.chesspenguin.data.Library import io.github.vrubelroman.chesspenguin.data.Settings import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import java.util.concurrent.atomic.AtomicInteger +import java.io.FileNotFoundException import java.util.UUID /// The app's databases, settings and engine files live as long as the process. @@ -32,4 +41,54 @@ class ChessPenguinApp : Application() { fun leftApp() { visit = UUID.randomUUID().toString() } + + /// A file opened from another app: being copied in, on the list, or why not. + val incoming = MutableStateFlow(null) + + /// One copy at a time, in the order the files came; only the last one opened is shown. + private val copying = Mutex() + private val waiting = AtomicInteger() + + /// Copies a file another app gave (it gives access only for a while) and puts it on + /// the list; `incoming` tells the screens how it went. + fun receive(uri: Uri) { + waiting.incrementAndGet() + incoming.value = Incoming.Opening + scope.launch { + val result = copying.withLock { + try { + val name = displayName(uri) ?: "games.pgn" + val ext = name.substringAfterLast('.', "").lowercase() + // One file of a ChessBase database: the others are not given with it. + if (ext in CHESSBASE_PARTS) throw ChessBasePart() + // A name with no known ending (some apps give "file_123") is read as PGN. + val fileName = if (ext in setOf("pgn", "zip", "7z", "cbv")) name else "$name.pgn" + val input = contentResolver.openInputStream(uri) ?: throw FileNotFoundException(uri.toString()) + Incoming.Opened(input.use { library.addCopy(fileName, it) { name.substringBeforeLast('.') } }) + } catch (e: Exception) { + Incoming.Failed(e) + } + } + val more = waiting.decrementAndGet() > 0 + // A file opened while another one was still being copied comes after it. + if (!(more && result is Incoming.Opened)) incoming.value = result + } + } + + private fun displayName(uri: Uri): String? = runCatching { + contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { c -> + if (c.moveToFirst()) c.getString(0) else null + } + }.getOrNull() +} + +/// A `.cbh` (or another part) of a ChessBase database, opened alone. +class ChessBasePart : Exception() + +private val CHESSBASE_PARTS = setOf("cbh", "cbg", "cba", "cbp", "cbs", "cbj", "cbt", "cbc", "cbe", "cbm") + +sealed interface Incoming { + data object Opening : Incoming + data class Opened(val entry: DbEntry) : Incoming + data class Failed(val error: Throwable) : Incoming } diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/MainActivity.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/MainActivity.kt index 3323129..f9bb64e 100644 --- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/MainActivity.kt +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/MainActivity.kt @@ -1,6 +1,8 @@ package io.github.vrubelroman.chesspenguin import android.content.Context +import android.content.Intent +import android.net.Uri import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent @@ -24,6 +26,8 @@ class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() + // Not again when the activity is made anew (turned): it was taken the first time. + if (savedInstanceState == null) receive(intent) val settings = (application as ChessPenguinApp).settings setContent { val prefs by settings.prefs.collectAsState() @@ -38,6 +42,23 @@ class MainActivity : ComponentActivity() { } } + override fun onNewIntent(intent: Intent) { + super.onNewIntent(intent) + receive(intent) + } + + /// A file given by another app: "Open with" (VIEW) or "Share" (SEND). + private fun receive(intent: Intent?) { + // Opened again from Recents: the task keeps the intent of the file it was made for. + if (intent == null || intent.flags and Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY != 0) return + val uri = when (intent.action) { + Intent.ACTION_VIEW -> intent.data + Intent.ACTION_SEND -> androidx.core.content.IntentCompat.getParcelableExtra(intent, Intent.EXTRA_STREAM, Uri::class.java) + else -> null + } ?: return + (application as ChessPenguinApp).receive(uri) + } + override fun onStop() { super.onStop() // Gone to the background or closed, not turned. diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/Navigation.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/Navigation.kt index 8cb7c2c..4a76bce 100644 --- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/Navigation.kt +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/Navigation.kt @@ -1,6 +1,32 @@ package io.github.vrubelroman.chesspenguin +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import androidx.compose.ui.window.Dialog +import androidx.compose.ui.window.DialogProperties +import androidx.compose.ui.semantics.semantics +import io.github.vrubelroman.chesspenguin.data.DbEntry +import io.github.vrubelroman.chesspenguin.data.NoGames +import uniffi.mobile_api.ApiException +import java.io.FileNotFoundException +import io.github.vrubelroman.chesspenguin.ui.app +import io.github.vrubelroman.chesspenguin.ui.openProblem import androidx.navigation3.runtime.NavKey import androidx.navigation3.runtime.entryProvider import androidx.navigation3.runtime.rememberNavBackStack @@ -30,12 +56,45 @@ import kotlinx.serialization.Serializable @Composable fun MainNavigation() { val backStack = rememberNavBackStack(Databases) + // A database just added from outside (the clipboard, another app): its list, or its + // only game at once, over the list of databases. + fun show(entry: DbEntry) { + while (backStack.size > 1) backStack.removeAt(backStack.lastIndex) + backStack.add(Games(entry.id)) + if (entry.games == 1) backStack.add(GameAt(entry.id, 0)) + } + val app = app() + val incoming by app.incoming.collectAsState() + LaunchedEffect(incoming) { + (incoming as? Incoming.Opened)?.let { + app.incoming.value = null + show(it.entry) + } + } + when (val i = incoming) { + Incoming.Opening -> Dialog(onDismissRequest = {}, properties = DialogProperties(dismissOnBackPress = false, dismissOnClickOutside = false)) { + Surface(shape = MaterialTheme.shapes.extraLarge, color = MaterialTheme.colorScheme.surfaceContainerHigh) { + Row(Modifier.padding(24.dp).semantics(mergeDescendants = true) {}, verticalAlignment = Alignment.CenterVertically) { + CircularProgressIndicator(Modifier.size(24.dp), strokeWidth = 3.dp) + Spacer(Modifier.size(16.dp)) + Text(stringResource(R.string.opening_file), style = MaterialTheme.typography.bodyLarge) + } + } + } + is Incoming.Failed -> AlertDialog( + onDismissRequest = { app.incoming.value = null }, + title = { Text(stringResource(R.string.file_failed)) }, + text = { Text(incomingProblem(i.error)) }, + confirmButton = { TextButton(onClick = { app.incoming.value = null }) { Text(stringResource(R.string.ok)) } }, + ) + else -> {} + } NavDisplay( backStack = backStack, onBack = { backStack.removeLastOrNull() }, entryProvider = entryProvider { entry { - DatabasesScreen(onOpen = { backStack.add(Games(it)) }, onSettings = { backStack.add(SettingsKey) }) + DatabasesScreen(onOpen = { backStack.add(Games(it)) }, onAdded = ::show, onSettings = { backStack.add(SettingsKey) }) } entry { key -> GamesScreen(key.db, onBack = { backStack.removeLastOrNull() }, onGame = { place, query -> backStack.add(GameAt(key.db, place, query)) }) @@ -59,3 +118,14 @@ fun MainNavigation() { }, ) } + +/// Why a file from another app did not open; it never got on the list, so the advice is +/// not that of a database on it (openProblem). +@Composable +private fun incomingProblem(e: Throwable): String = when (e) { + is ChessBasePart -> stringResource(R.string.file_chessbase_part) + is NoGames -> stringResource(R.string.file_no_games) + is SecurityException, is FileNotFoundException, is ApiException.Io -> stringResource(R.string.file_unreadable) + is ApiException -> openProblem(e).ifEmpty { stringResource(R.string.open_corrupt) } + else -> stringResource(R.string.file_copy_failed) +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/EngineSession.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/EngineSession.kt index 56c6c37..ebc0025 100644 --- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/EngineSession.kt +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/EngineSession.kt @@ -1,5 +1,6 @@ package io.github.vrubelroman.chesspenguin.data +import android.os.SystemClock import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job @@ -196,6 +197,9 @@ class EngineSession(private val files: EngineFiles, private val scope: Coroutine } private suspend fun poll(a: Analyzer) { + // What the engine said last and was not shown yet. + var held: EngineView? = null + var shown = 0L while (scope.isActive && analyzer === a) { // A short wait: analyze() waits for the engine handle while this holds it. val snapshot = try { @@ -206,8 +210,21 @@ class EngineSession(private val files: EngineFiles, private val scope: Coroutine } val s = search if (snapshot != null && s != null && snapshot.search == s.id && analyzer === a) { - _analysis.value = EngineView(s.position, snapshot) + held = EngineView(s.position, snapshot) + } + // The screen follows the engine a few times a second, not at every word of + // it; the first words about a new position are shown at once. + val next = held ?: continue + val now = SystemClock.uptimeMillis() + if (now - shown >= SHOW_EVERY_MS || next.position != _analysis.value?.position) { + _analysis.value = next + held = null + shown = now } } } + + private companion object { + const val SHOW_EVERY_MS = 200L + } } 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 888390b..d13ec55 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 @@ -35,6 +35,10 @@ enum class Source { /// A ChessBase database (`.cbh` with `.cbg`, `.cba`, … beside it) in a picked folder. ChessBase, + + /// A copy kept inside the app (`files/copies/`): games pasted from the clipboard, a + /// file opened from another app, which gives access to it only for a while. + Copy, } /// A database on the list. The file itself is never changed. @@ -44,7 +48,7 @@ data class DbEntry( val name: String, val source: Source, /// The asset path of a sample, the content URI of a file; for a ChessBase database, - /// the URI of the folder it is in. + /// the URI of the folder it is in; for a copy, its file's name in `files/copies/`. val location: String, /// The file's name, for its extension (PGN, .zip, .7z, .cbv, .cbh). val fileName: String, @@ -57,8 +61,13 @@ data class DbEntry( val format: String? = null, /// A sample shows the name of the current language until it is renamed (displayName). val renamed: Boolean = false, + /// A copy's SHA-256: the same file opened again is not copied twice. + val sha256: String? = null, ) +/// Text or a file with no games in it. +class NoGames : Exception() + /// A database found in a picked folder, offered to be added. data class Found( val name: String, @@ -101,6 +110,7 @@ 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") + private val copies = File(context.filesDir, "copies") private val json = Json { ignoreUnknownKeys = true } private val _entries = MutableStateFlow(load()) val entries: StateFlow> = _entries.asStateFlow() @@ -120,7 +130,9 @@ class Library(private val context: Context) { /// 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() + val kept = _entries.value.filter { it.source == Source.Copy }.map { it.location }.toSet() + copies.listFiles()?.filter { it.name !in kept }?.forEach { it.delete() } + val used = _entries.value.mapNotNull { it.tree ?: it.location.takeIf { _ -> it.source == Source.File || it.source == Source.ChessBase } }.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) } @@ -188,6 +200,69 @@ class Library(private val context: Context) { return entry } + /// Keeps a copy of `input` (named `fileName`, for its format) in the app and puts it + /// on the list, or gives the entry of the same copy already there. Throws [NoGames] + /// when there is no game in it, or the core's error when it cannot be read; nothing + /// stays behind then. + suspend fun addCopy(fileName: String, input: java.io.InputStream, name: (Database) -> String): DbEntry = withContext(Dispatchers.IO) { + copies.mkdirs() + val ext = fileName.substringAfterLast('.', "pgn").lowercase() + val tmp = File(copies, "incoming-${UUID.randomUUID()}.$ext") + try { + val digest = java.security.MessageDigest.getInstance("SHA-256") + tmp.outputStream().use { out -> + val buf = ByteArray(256 * 1024) + while (true) { + val n = input.read(buf) + if (n < 0) break + out.write(buf, 0, n) + digest.update(buf, 0, n) + } + } + val sum = digest.digest().joinToString("") { "%02x".format(it) } + lock.withLock { + _entries.value.firstOrNull { it.source == Source.Copy && it.sha256 == sum }?.let { return@withContext it } + } + val id = UUID.randomUUID().toString() + val kept = File(copies, "$id.$ext") + if (!tmp.renameTo(kept)) throw java.io.IOException("cannot keep the copy") + val db = try { + openFile(fileName, android.os.ParcelFileDescriptor.open(kept, android.os.ParcelFileDescriptor.MODE_READ_ONLY).detachFd()) + } catch (e: ApiException.Empty) { + kept.delete() + throw NoGames() + } catch (t: Throwable) { + kept.delete() + throw t + } + // PGN reading is lenient: any text is one "game" of a comment. A game counts + // when it has a tag or a move. + if (db.len() == 0u || (db.len() == 1u && db.game(0u).let { it.tags.isEmpty() && it.nodes.size <= 1 })) { + db.close() + kept.delete() + throw NoGames() + } + val entry = DbEntry( + id = id, + name = name(db), + source = Source.Copy, + location = kept.name, + fileName = fileName, + size = kept.length(), + games = db.len().toInt(), + format = db.format(), + sha256 = sum, + ) + lock.withLock { + open[id] = db + update { it + entry } + } + entry + } finally { + tmp.delete() + } + } + fun rename(id: String, name: String) = update { list -> list.map { if (it.id == id) it.copy(name = name, renamed = true) else it } } /// Takes the database off the list (the file stays where it is). Returns its place, @@ -207,6 +282,10 @@ class Library(private val context: Context) { fun forget(entry: DbEntry) { pending.remove(entry) if (entry.source == Source.Sample) return + if (entry.source == Source.Copy) { + File(copies, entry.location).delete() + 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 @@ -383,6 +462,10 @@ class Library(private val context: Context) { Source.Sample -> openBytes(e.fileName, context.assets.open(e.location).use { it.readBytes() }) Source.File -> openFile(e.fileName, openDocument(Uri.parse(e.location)).detachFd()) Source.ChessBase -> openChessBase(e) + Source.Copy -> openFile( + e.fileName, + android.os.ParcelFileDescriptor.open(File(copies, e.location), android.os.ParcelFileDescriptor.MODE_READ_ONLY).detachFd(), + ) } } } diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/Settings.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/Settings.kt index 4284720..102048d 100644 --- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/Settings.kt +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/Settings.kt @@ -26,16 +26,21 @@ data class Prefs( val engineHashMb: Int = 64, ) -/// Half the cores, at most 4 (§9). -fun defaultThreads(): Int = (Runtime.getRuntime().availableProcessors() / 2).coerceIn(1, 4) +/// Half the cores, at most 2: the engine leaves the phone's interface room (§9). +fun defaultThreads(): Int = (Runtime.getRuntime().availableProcessors() / 2).coerceIn(1, 2) class Settings(context: Context) { private val store = context.getSharedPreferences("settings", Context.MODE_PRIVATE) private val _prefs = MutableStateFlow(read()) init { - // The engine button was kept here up to 0.11 (it is not remembered any more). - store.edit().remove("engineOn").apply() + // Up to 0.11 the engine button was kept here (it is not remembered any more), and + // the threads were half the cores up to 4: that default becomes the new one. + if (store.getInt("version", 1) < 2) { + val oldDefault = (Runtime.getRuntime().availableProcessors() / 2).coerceIn(1, 4) + if (store.getInt("engineThreads", oldDefault) == oldDefault) update { it.copy(engineThreads = defaultThreads()) } + store.edit().remove("engineOn").putInt("version", 2).apply() + } } val prefs: StateFlow = _prefs.asStateFlow() 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 index 9081a5e..945adfe 100644 --- 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 @@ -17,6 +17,7 @@ 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.ContentPaste import androidx.compose.material.icons.outlined.Description import androidx.compose.material.icons.outlined.Folder import androidx.compose.material3.Button @@ -51,10 +52,10 @@ 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. +/// "Add a database": games in the clipboard, a file, or every database in a folder. @OptIn(ExperimentalMaterial3Api::class) @Composable -fun AddSheet(onFile: () -> Unit, onFolder: () -> Unit, onDismiss: () -> Unit) { +fun AddSheet(onFile: () -> Unit, onFolder: () -> Unit, onPaste: (() -> Unit)?, onDismiss: () -> Unit) { ModalBottomSheet(onDismissRequest = onDismiss) { Column(Modifier.navigationBarsPadding().padding(bottom = 24.dp)) { Text( @@ -62,6 +63,17 @@ fun AddSheet(onFile: () -> Unit, onFolder: () -> Unit, onDismiss: () -> Unit) { style = MaterialTheme.typography.titleLarge, modifier = Modifier.padding(horizontal = 24.dp, vertical = 8.dp).semantics { heading() }, ) + // Only when there is text to paste (asked without reading it: reading the + // clipboard makes Android say so on the screen). + if (onPaste != null) { + ListItem( + headlineContent = { Text(stringResource(R.string.add_paste)) }, + supportingContent = { Text(stringResource(R.string.add_paste_hint)) }, + leadingContent = { Icon(Icons.Outlined.ContentPaste, null) }, + colors = ListItemDefaults.colors(containerColor = Color.Transparent), + modifier = Modifier.clickable(role = Role.Button, onClick = onPaste).padding(horizontal = 8.dp), + ) + } ListItem( headlineContent = { Text(stringResource(R.string.add_file)) }, supportingContent = { Text(stringResource(R.string.add_file_hint)) }, 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 365f583..f414ac8 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 @@ -1,5 +1,7 @@ package io.github.vrubelroman.chesspenguin.ui +import android.content.ClipboardManager +import android.text.format.DateUtils import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.ExperimentalFoundationApi @@ -57,6 +59,7 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.input.nestedscroll.nestedScroll +import androidx.compose.ui.platform.LocalResources import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.pluralStringResource import androidx.compose.ui.res.stringResource @@ -69,17 +72,19 @@ 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 uniffi.mobile_api.Database import kotlinx.coroutines.launch /// The first screen: the databases on the list (android-ui.md §3). @OptIn(ExperimentalMaterial3Api::class) @Composable -fun DatabasesScreen(onOpen: (String) -> Unit, onSettings: () -> Unit) { +fun DatabasesScreen(onOpen: (String) -> Unit, onAdded: (DbEntry) -> Unit, onSettings: () -> Unit) { val library = app().library val entries by library.entries.collectAsState() val snackbar = remember { SnackbarHostState() } val scope = rememberCoroutineScope() val removedText = stringResource(R.string.removed) + val removedCopyText = stringResource(R.string.removed_copy) val undoText = stringResource(R.string.undo) val pick = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri -> if (uri != null) onOpen(library.addFile(uri).id) @@ -158,11 +163,17 @@ fun DatabasesScreen(onOpen: (String) -> Unit, onSettings: () -> Unit) { val removed = library.remove(e.id) ?: return@DatabaseRow scope.launch { snackbar.currentSnackbarData?.dismiss() - val r = snackbar.showSnackbar(removedText, undoText, withDismissAction = false) - if (r == SnackbarResult.ActionPerformed) { - library.restore(removed.first, removed.second) - } else { - library.forget(removed.second) + var restored = false + try { + // A copy is deleted, not only taken off the list. + val text = if (e.source == Source.Copy) removedCopyText else removedText + if (snackbar.showSnackbar(text, undoText, withDismissAction = false) == SnackbarResult.ActionPerformed) { + library.restore(removed.first, removed.second) + restored = true + } + } finally { + // Also when the screen goes away while "Undo" is offered. + if (!restored) library.forget(removed.second) } } }, @@ -173,7 +184,11 @@ fun DatabasesScreen(onOpen: (String) -> Unit, onSettings: () -> Unit) { } } val context = androidx.compose.ui.platform.LocalContext.current + val pasteNone = stringResource(R.string.paste_none) + val resources = LocalResources.current if (choosing) { + val clipboard = remember { context.getSystemService(ClipboardManager::class.java) } + val hasText = remember { clipboard.primaryClipDescription?.hasMimeType("text/*") == true } AddSheet( onFile = { choosing = false @@ -183,6 +198,24 @@ fun DatabasesScreen(onOpen: (String) -> Unit, onSettings: () -> Unit) { choosing = false pickFolder.launch(null) }, + onPaste = if (!hasText) null else { + { + choosing = false + val text = clipboard.primaryClip?.takeIf { it.itemCount > 0 }?.getItemAt(0)?.coerceToText(context)?.toString().orEmpty() + val dated = resources.getString( + R.string.paste_db, + DateUtils.formatDateTime(context, System.currentTimeMillis(), DateUtils.FORMAT_SHOW_DATE or DateUtils.FORMAT_SHOW_TIME or DateUtils.FORMAT_ABBREV_MONTH), + ) + scope.launch { + runCatching { + library.addCopy("clipboard.pgn", text.byteInputStream()) { db -> pastedName(db, dated) } + }.onSuccess(onAdded).onFailure { + snackbar.currentSnackbarData?.dismiss() + snackbar.showSnackbar(pasteNone) + } + } + } + }, onDismiss = { choosing = false }, ) } @@ -196,7 +229,7 @@ fun DatabasesScreen(onOpen: (String) -> Unit, onSettings: () -> Unit) { val n = chosen.count { !it.added && !it.incomplete } scope.launch { snackbar.currentSnackbarData?.dismiss() - snackbar.showSnackbar(context.resources.getQuantityString(R.plurals.added_count, n, n)) + snackbar.showSnackbar(resources.getQuantityString(R.plurals.added_count, n, n)) } // Nothing added: the folder's permission goes back. if (n == 0) library.forgetFolder(s.tree) @@ -256,6 +289,8 @@ private fun DatabaseRow(e: DbEntry, onOpen: () -> Unit, onRename: () -> Unit, on 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, formatName(e)) + // A copy kept in the app says so: removing it deletes it. + val shownSubtitle = if (e.source == Source.Copy) subtitle + " · " + stringResource(R.string.db_copy) else subtitle Row( modifier .fillMaxWidth() @@ -268,7 +303,7 @@ private fun DatabaseRow(e: DbEntry, onOpen: () -> Unit, onRename: () -> Unit, on Column(Modifier.weight(1f).padding(start = 16.dp)) { Text(displayName(e), style = MaterialTheme.typography.bodyLarge, maxLines = 1, overflow = TextOverflow.Ellipsis) Text( - subtitle, + shownSubtitle, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, @@ -310,3 +345,16 @@ private fun RenameDialog(name: String, onDismiss: () -> Unit, onSave: (String) - dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) } }, ) } + +/// The name of pasted games: one game by its players, games of one event by it, others by +/// when they were pasted (`dated`), so that two pastes differ. +private fun pastedName(db: Database, dated: String): String { + val rows = db.rowsOf((0u until db.len()).toList()) + if (rows.size == 1) { + val (white, black) = shortName(rows[0].white) to shortName(rows[0].black) + if (white != "?" || black != "?") return "$white – $black" + } else { + rows.map { it.event.trim() }.distinct().singleOrNull()?.takeIf { it.isNotEmpty() && it != "?" }?.let { return it } + } + return dated +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GameScreen.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GameScreen.kt index d9ce044..2edc2a5 100644 --- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GameScreen.kt +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GameScreen.kt @@ -160,7 +160,9 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o val netState by files.state.collectAsState() val session = remember { EngineSession(files, app.scope) } val status by session.status.collectAsState() - val engineView by session.analysis.collectAsState() + // Read only where it is shown (the strip, the arrows): the engine speaks several + // times a second, the rest of the screen is not drawn again for it. + val engineView = session.analysis.collectAsState() var visible by remember { mutableStateOf(true) } var sheet by rememberSaveable { mutableStateOf(false) } var wantEngine by rememberSaveable { mutableStateOf(false) } @@ -214,7 +216,7 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o val engineOn = engineWanted && engineReady val position = remember(g, current) { g?.let { enginePosition(it, current) } } // Only what the engine said about the position on the board. - val analysis = engineView?.takeIf { it.position == position }?.analysis + fun analysis() = engineView.value?.takeIf { it.position == position }?.analysis // Mate and stalemate need no engine: the strip says what it is (§7.3). val ending = when (node?.end) { "checkmate" -> stringResource(R.string.checkmate) + (g?.let { " · " + shortResult(it.result) }?.takeIf { !it.endsWith("*") } ?: "") @@ -338,7 +340,7 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o } else { node?.marks?.forEach { m -> m.to?.let { add(BoardArrow(m.from, it, markColor(m.color), 0.9f)) } } if (engineOn && prefs.bestArrow) { - analysis?.lines?.take(2)?.forEachIndexed { i, l -> + analysis()?.lines?.take(2)?.forEachIndexed { i, l -> val f = l.fromSquare val t = l.toSquare if (f != null && t != null) { @@ -374,22 +376,24 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o Column(sideModifier.fillMaxWidth()) { val p = preview if (engineOn) { - EngineStrip( - ending = ending, - status = status, - analysis = analysis, - flipped = flipped, - lines = prefs.engineLines, - expanded = expanded, - onExpand = { expanded = !expanded }, - onLine = { l -> if (l.steps.isNotEmpty()) preview = Preview(l, 0) }, - onDeeper = { session.deeper() }, - onRestart = { - session.shutdown() - position?.let { session.show(it, prefs) } - }, - notation = line, - ) + Live { + EngineStrip( + ending = ending, + status = status, + analysis = analysis(), + flipped = flipped, + lines = prefs.engineLines, + expanded = expanded, + onExpand = { expanded = !expanded }, + onLine = { l -> if (l.steps.isNotEmpty()) preview = Preview(l, 0) }, + onDeeper = { session.deeper() }, + onRestart = { + session.shutdown() + position?.let { session.show(it, prefs) } + }, + notation = line, + ) + } } else if (wantEngine && files.builtIn && netState is NetState.Loading) { Row(Modifier.fillMaxWidth().height(48.dp).padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically) { CircularProgressIndicator(Modifier.size(20.dp), strokeWidth = 2.dp) @@ -722,3 +726,7 @@ private fun firstBoardTouch(context: Context): Boolean { prefs.edit().putBoolean("board", true).apply() return true } + +/// A scope of its own: what is read in it is drawn again without its surroundings. +@Composable +private fun Live(content: @Composable () -> Unit) = content() 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 3ac91aa..f726e56 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 @@ -215,7 +215,8 @@ 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) { +fun openProblem(e: Throwable): String = when (e) { + is io.github.vrubelroman.chesspenguin.data.NoGames -> stringResource(R.string.file_no_games) 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) diff --git a/androidApp/app/src/main/res/values-de/strings.xml b/androidApp/app/src/main/res/values-de/strings.xml index 9c3c877..5d6ac45 100644 --- a/androidApp/app/src/main/res/values-de/strings.xml +++ b/androidApp/app/src/main/res/values-de/strings.xml @@ -211,4 +211,16 @@ Brett Figuren Nr. %1$s + PGN aus der Zwischenablage einfügen + In einer anderen App kopierte Partien + Keine PGN-Partien in der Zwischenablage + Eingefügt am %1$s + Datei wird geöffnet… + Die Datei ließ sich nicht öffnen + Diese Datei enthält keine Schachpartien. + Die Datei ließ sich nicht lesen: Sie existiert nicht mehr, oder die App, aus der sie stammt, hat keinen Zugriff gewährt. Öffnen Sie sie erneut. + Eine ChessBase-Datenbank (.cbh) besteht aus mehreren Dateien, gekommen ist nur eine. Fügen Sie ihren Ordner hinzu: „Datenbank hinzufügen“ → „Ordner“. + Die App konnte keine Kopie der Datei speichern. Prüfen Sie, ob auf dem Telefon Platz frei ist. + Kopie + Datenbank aus ChessPenguin 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 508d02f..f1861ef 100644 --- a/androidApp/app/src/main/res/values-es/strings.xml +++ b/androidApp/app/src/main/res/values-es/strings.xml @@ -215,4 +215,16 @@ Tablero Piezas N.º %1$s + Pegar PGN del portapapeles + Partidas copiadas en otra aplicación + No hay partidas PGN en el portapapeles + Pegado el %1$s + Abriendo el archivo… + No se pudo abrir el archivo + Este archivo no contiene partidas de ajedrez. + No se pudo leer el archivo: ya no existe o la aplicación de la que viene no dio acceso. Ábralo otra vez. + Una base de ChessBase (.cbh) consta de varios archivos y solo llegó uno. Añada su carpeta: «Añadir base» → «Carpeta». + La aplicación no pudo guardar una copia del archivo. Compruebe que el teléfono tiene espacio libre. + copia + Base eliminada de ChessPenguin diff --git a/androidApp/app/src/main/res/values-fr/strings.xml b/androidApp/app/src/main/res/values-fr/strings.xml index 1d86580..80e3d22 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 ou un dossier de bases : PGN, ChessBase, archives .zip et .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 @@ -157,9 +157,9 @@ 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. + 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 + le fichier .cbg manque : les parties ne s’ouvrent pas %1$d base dans « %2$s » %1$d de bases dans « %2$s » @@ -181,7 +181,7 @@ 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é. + Le fichier %1$s n’est plus à côté de la base : il a été déplacé ou supprimé. Échiquier et pièces Marron Bleu @@ -215,4 +215,16 @@ Échiquier Pièces N° %1$s + Coller le PGN du presse-papiers + Parties copiées dans une autre application + Aucune partie PGN dans le presse-papiers + Collé le %1$s + Ouverture du fichier… + Impossible d’ouvrir le fichier + Ce fichier ne contient aucune partie d’échecs. + Impossible de lire le fichier : il n’existe plus, ou l’application d’origine n’y a pas donné accès. Réessayez de l’ouvrir. + Une base ChessBase (.cbh) se compose de plusieurs fichiers, et un seul est arrivé. Ajoutez son dossier : « Ajouter une base » → « Dossier ». + L’application n’a pas pu garder une copie du fichier. Vérifiez qu’il reste de la place sur le téléphone. + copie + Base supprimée de ChessPenguin diff --git a/androidApp/app/src/main/res/values-it/strings.xml b/androidApp/app/src/main/res/values-it/strings.xml index 93b4865..a13c32c 100644 --- a/androidApp/app/src/main/res/values-it/strings.xml +++ b/androidApp/app/src/main/res/values-it/strings.xml @@ -215,4 +215,16 @@ Scacchiera Pezzi N. %1$s + Incolla PGN dagli appunti + Partite copiate in un’altra app + Nessuna partita PGN negli appunti + Incollato il %1$s + Apertura del file… + Impossibile aprire il file + Questo file non contiene partite a scacchi. + Impossibile leggere il file: non esiste più o l’app da cui proviene non ha concesso l’accesso. Riaprilo. + Un database ChessBase (.cbh) è fatto di più file, ma ne è arrivato solo uno. Aggiungi la sua cartella: «Aggiungi database» → «Cartella». + L’app non è riuscita a salvare una copia del file. Controlla che sul telefono ci sia spazio libero. + copia + Database eliminato da ChessPenguin diff --git a/androidApp/app/src/main/res/values-ru/strings.xml b/androidApp/app/src/main/res/values-ru/strings.xml index e591e5e..2dd26cd 100644 --- a/androidApp/app/src/main/res/values-ru/strings.xml +++ b/androidApp/app/src/main/res/values-ru/strings.xml @@ -219,4 +219,16 @@ Доска Фигуры № %1$s + Вставить PGN из буфера + Партии, скопированные в другом приложении + В буфере нет партий в формате PGN + Из буфера, %1$s + Открываю файл… + Файл не открылся + В этом файле нет шахматных партий. + Файл не прочитался: его уже нет или приложение, из которого он открыт, не дало к нему доступа. Попробуйте открыть его ещё раз. + База ChessBase (.cbh) состоит из нескольких файлов, а пришёл один. Добавьте папку, где она лежит: «Добавить базу» → «Папка». + Приложению не удалось сохранить копию файла. Проверьте, есть ли на телефоне свободное место. + копия + База удалена из ChessPenguin diff --git a/androidApp/app/src/main/res/values/strings.xml b/androidApp/app/src/main/res/values/strings.xml index a525bca..27ab296 100644 --- a/androidApp/app/src/main/res/values/strings.xml +++ b/androidApp/app/src/main/res/values/strings.xml @@ -214,4 +214,16 @@ NCF Pieces No. %1$s + Paste PGN from the clipboard + Games copied in another app + No PGN games in the clipboard + Pasted %1$s + Opening the file… + Couldn’t open the file + There are no chess games in this file. + The file could not be read: it may be gone, or the app it came from did not give access to it. Try opening it again. + A ChessBase database (.cbh) is made of several files, and only one came. Add the folder it is in: \"Add database\" → \"Folder\". + The app could not keep a copy of the file. Check that the phone has free space. + copy + Database deleted from ChessPenguin diff --git a/crates/chess-core/src/pgn/lexer.rs b/crates/chess-core/src/pgn/lexer.rs index 9cd166c..990fa2f 100644 --- a/crates/chess-core/src/pgn/lexer.rs +++ b/crates/chess-core/src/pgn/lexer.rs @@ -114,6 +114,12 @@ impl<'a> Lexer<'a> { } } + /// After a game's result a header may follow on the same line (`… 1-0 [Event "B"]`, + /// as pasted or joined text has it): a tag there counts as at a line's start. + pub fn allow_tag(&mut self) { + self.line_blank = true; + } + /// Is there a tag-looking line (`[Name "`) at `i`? fn tag_like_at(&self, mut i: usize) -> bool { if self.at(i) != Some(b'[') { diff --git a/crates/chess-core/src/pgn/scan.rs b/crates/chess-core/src/pgn/scan.rs index d176b1e..11f9c1e 100644 --- a/crates/chess-core/src/pgn/scan.rs +++ b/crates/chess-core/src/pgn/scan.rs @@ -242,6 +242,7 @@ pub fn scan_games( } if depth == 0 && matches!(w, b"1-0" | b"0-1" | b"1/2-1/2" | b"*") { result_seen = true; + lx.allow_tag(); } } } @@ -292,6 +293,14 @@ mod tests { assert!(e[0].tags.is_empty()); } + #[test] + fn a_header_on_the_line_of_the_last_result_starts_the_next_game() { + let e = scan("[White \"Aaa\"] 1. e4 e5 * [White \"Ccc\"][Black \"Ddd\"] 1. d4 d5 *\n"); + assert_eq!(e.len(), 2); + assert_eq!(e[1].white(), Some("Ccc")); + assert_eq!(e[1].black(), Some("Ddd")); + } + #[test] fn cancellation() { let cancel = AtomicBool::new(true); diff --git a/crates/mobile-api/src/engine.rs b/crates/mobile-api/src/engine.rs index 87a8797..9429f77 100644 --- a/crates/mobile-api/src/engine.rs +++ b/crates/mobile-api/src/engine.rs @@ -112,7 +112,12 @@ impl Analyzer { let start = |e: uci::EngineError| EngineFailure::Start { detail: e.to_string(), }; - let handle = Engine::spawn_with(EngineConfig::new(path), Box::new(|| {})).map_err(start)?; + // Below the app (nice 10): the phone's interface comes first while it thinks. + let config = EngineConfig { + nice: 10, + ..EngineConfig::new(path) + }; + let handle = Engine::spawn_with(config, Box::new(|| {})).map_err(start)?; if !eval_file.is_empty() { handle .set_option("EvalFile", Some(&eval_file)) diff --git a/crates/uci/Cargo.toml b/crates/uci/Cargo.toml index d78642d..9c9253f 100644 --- a/crates/uci/Cargo.toml +++ b/crates/uci/Cargo.toml @@ -9,6 +9,10 @@ description = "UCI chess engine process supervisor (no UI dependencies)" [dependencies] thiserror.workspace = true +[target.'cfg(unix)'.dependencies] +# nice(2) for EngineConfig::nice (std has no way to lower a child's priority). +libc = "0.2" + # Test helper: deterministic fake UCI engine used by tests/ via CARGO_BIN_EXE_fake_uci. [[bin]] name = "fake_uci" diff --git a/crates/uci/src/engine.rs b/crates/uci/src/engine.rs index a9e5291..f5f5785 100644 --- a/crates/uci/src/engine.rs +++ b/crates/uci/src/engine.rs @@ -78,6 +78,9 @@ pub struct EngineConfig { /// (engines often look for weights/books next to themselves). pub working_dir: Option, pub timeouts: Timeouts, + /// Added to the engine's nice value on Unix (0 = as the app): a phone keeps its + /// interface smooth while the engine thinks. Every thread of the engine has it. + pub nice: i32, } impl EngineConfig { @@ -87,6 +90,7 @@ impl EngineConfig { args: Vec::new(), working_dir: None, timeouts: Timeouts::default(), + nice: 0, } } } @@ -391,6 +395,19 @@ fn spawn_impl(cfg: EngineConfig, waker: Waker) -> Result/stat, after the name). +#[cfg(target_os = "linux")] +fn nice_of(pid: u32) -> i32 { + let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).expect("stat"); + let after_name = &stat[stat.rfind(')').expect("name") + 2..]; + after_name + .split(' ') + .nth(16) + .expect("nice") + .parse() + .expect("number") +} + +#[cfg(target_os = "linux")] +#[test] +fn an_engine_can_run_below_the_app() { + let ours = nice_of(std::process::id()); + let calm = Engine::spawn_with( + EngineConfig { + nice: 10, + ..config(&[]) + }, + Box::new(|| {}), + ) + .expect("spawn"); + let plain = spawn(&[]); + assert_eq!(nice_of(calm.pid()), (ours + 10).min(19)); + assert_eq!(nice_of(plain.pid()), ours); + calm.quit(); + plain.quit(); +} diff --git a/docs/design/android-ui.md b/docs/design/android-ui.md index 77d5a43..6295ed2 100644 --- a/docs/design/android-ui.md +++ b/docs/design/android-ui.md @@ -72,9 +72,10 @@ │ Партия │ листы: «Сведения», меню ⋮, «Скачать движок» └──────────────┘ -«Открыть с помощью» / «Поделиться» из Telegram, почты, файлового менеджера - ──▶ сразу «Партии» этого файла (или «Партия», если партия одна) с полосой - «Этой базы нет в списке [Добавить]». +«Открыть с помощью» / «Поделиться» из Telegram, почты, файлового менеджера, +«Вставить PGN из буфера» в листе «Добавить базу» + ──▶ копия в приложении встаёт в список баз; поверх «Баз» сразу + «Партии» этой копии, а если партия одна — «Партия» (§4.5, §4.6). ``` - Приложение — одна активность; экраны лежат в стеке. «Назад» (жест или ← в верхней панели) всегда возвращает на шаг: Партия → Партии → Базы → выход. @@ -177,7 +178,7 @@ - «Текстов» показывается, только если в базе есть текстовые главы. - «Замечания» — заметки импорта (например, что повтор в архиве пропущен). Если заметок нет, пункта нет. - **Убрать из списка** — без диалога. Строка исчезает, на 4 с появляется снекбар «База убрана из списка · Вернуть». Сам файл не удаляется. - - Для копии в приложении сначала диалог: «Убрать базу? Копия в ChessPenguin будет удалена. Исходный файл не изменится.» Кнопки «Отмена» и «Убрать». Снекбара «Вернуть» после этого нет. + - Копия в приложении (§4.4) при этом удаляется; снекбар — «База удалена из ChessPenguin · Вернуть». ~~Диалог «Убрать базу?»~~ — заменён снекбаром 2026-10-23 (§20). ## 4. Добавление базы @@ -189,6 +190,9 @@ FAB открывает лист, а не сразу системный выбо ┌────────────────────────────────────┐ │ ─── │ │ Добавить базу │ 22sp +│ [⎘] Вставить PGN из буфера │ 72 только если в буфере текст +│ Партии, скопированные в другом│ +│ приложении │ │ [▤] Файл │ 72 │ PGN, .cbv, .zip или .7z │ │ [▣] Папка │ 72 @@ -201,7 +205,9 @@ FAB открывает лист, а не сразу системный выбо ``` - Сноска внизу — единственное место, где объясняется запрет Android. Системный выбор папки сам пишет «Can't use this folder» по-английски и предлагает создать папку; наша строка заранее говорит, что делать. -- «Вставить PGN из буфера» (§4.5) — позже, в листе появится третьей строкой. +- **«Вставить PGN из буфера»** (§4.5) — первая строка, значок `content_paste`. Она есть, только если в буфере текст. Проверяется лишь описание буфера (`primaryClipDescription`, тип `text/*`): чтение самого текста Android объявляет всплывающим сообщением, поэтому текст читается только по нажатию. + - Строка первой, потому что она контекстная: человек только что скопировал партию в другом приложении и пришёл её вставить. «Файл» и «Папка» сдвигаются на 72 dp, но на них не нажимают вслепую — лист читают глазами. + - Подсказка до двух строк — допустимо; на 360 dp по-русски она помещается в одну-две строки, по-немецки «In einer anderen App kopierte Partien» — в одну. ### 4.2. «Файл» @@ -266,23 +272,48 @@ FAB открывает лист, а не сразу системный выбо ### 4.4. Файл на месте или копия - **Файл в памяти телефона или на SD-карте** читается на месте, без копии. -- **Облачный файл** (Google Диск и т. п., если его нельзя читать с произвольного места) и **файл из «Поделиться»** копируются в память приложения. +- **Облачный файл** (Google Диск и т. п., если его нельзя читать с произвольного места), **файл из «Открыть с помощью» и «Поделиться»** (§4.6) и **текст из буфера** (§4.5) копируются в память приложения (`files/copies/`). + - Копия — обычная база в списке. Во второй строке у неё слово «копия»: «1 партия · PGN · копия» (en «1 game · PGN · copy»), чтобы человек знал, что файл лежит в ChessPenguin, а не там, откуда пришёл. + - «Убрать из списка» у копии удаляет её. Снекбар другой: «База удалена из ChessPenguin · Вернуть» (en «Database deleted from ChessPenguin · Undo»); пока он виден, «Вернуть» возвращает базу, после него файл копии стирается. Диалог §3.3 заменён этим снекбаром: действие обратимо, лишний вопрос не нужен. + - Тот же файл или тот же текст второй раз не копируется: по SHA-256 находится уже сохранённая копия, и открывается она (с её текущим, возможно, новым именем). - Если файл больше 50 МБ, сначала диалог: «Файл в облаке. ChessPenguin сохранит копию у себя: 120 МБ.» с кнопками «Отмена» и «Сохранить копию». - Пока идёт копирование, в строке базы написано «копирую… 40 %». - Как отличить один случай от другого, решает разработчик: по флагам документа и по тому, поддерживает ли дескриптор `seek`. Пользователь видит итог в «Сведениях». ### 4.5. «Вставить PGN из буфера» -- В буфере одна партия — сразу открывается «Партия», в список ничего не добавляется. Несколько партий — открываются «Партии» временной базы «Из буфера» с полосой «Этой базы нет в списке [Добавить]». -- В буфере нет PGN — снекбар «В буфере нет партии в формате PGN». -- Буфер читается только по нажатию, а не заранее, чтобы система не показывала уведомление о доступе к буферу без причины. +- По нажатию лист закрывается, текст буфера сохраняется копией (§4.4) и ставится в конец списка баз. Поверх «Баз» открываются: + - одна партия — сразу «Партия» («1 из 1», ‹ › неактивны); «назад» ведёт в «Партии» этой копии, потом в «Базы»; + - несколько — «Партии». +- **Имя копии.** + - Одна партия — игроки, как в строке партии (§6.2): «Alekhine A. – Rozanov V.». Если обоих игроков нет («?»), — как у нескольких партий. + - Несколько партий с одним и тем же непустым тегом `Event` — это событие: «Wijk aan Zee 2024». + - Иначе — «Из буфера, {дата и время}»: «Из буфера, 23 окт., 14:05» (en «Pasted 23 Oct, 14:05»). Дата и время — `DateUtils.formatDateTime` с `FORMAT_SHOW_DATE | FORMAT_SHOW_TIME | FORMAT_ABBREV_MONTH`, без года. Так две разные вставки в списке различаются; переименовать можно как любую базу. +- Нет партий (пустой текст, обычный текст, текст без тегов и ходов) — лист закрыт, снекбар «В буфере нет партий в формате PGN». В список ничего не добавляется. +- Тот же текст второй раз открывает уже сохранённую копию (§4.4). ### 4.6. «Открыть с помощью» и «Поделиться» -- Приложение принимает `ACTION_VIEW` и `ACTION_SEND` с MIME `application/x-chess-pgn`, `application/vnd.chess-pgn`, `text/plain`, `application/zip`, `application/x-7z-compressed` и `application/octet-stream`. Формат определяется по содержимому. Если это не шахматный файл — экран ошибки «Это не база партий» с кнопкой «К базам». -- Файл копируется во временную папку. Открываются его «Партии», а если партия одна — сразу «Партия». Сверху полоса M3 banner: «Этой базы нет в списке. [Добавить]». - - «Добавить» переносит копию в постоянную папку и ставит базу в список; снекбар «База добавлена». - - Если не нажать «Добавить», временная копия удаляется при следующем запуске. +- Приложение принимает `ACTION_VIEW` (схема `content`) и `ACTION_SEND` с MIME `application/x-chess-pgn`, `application/vnd.chess-pgn`, `application/zip`, `application/x-7z-compressed` и `application/octet-stream` — последний для `.cbv` и для `.pgn` из приложений, которые не знают этот тип (Telegram). `text/plain` не принимаем: иначе ChessPenguin предлагался бы для любого текста; текст партии вставляется из буфера (§4.5). +- Активность одна (`singleTask`): файл приходит в уже открытое приложение, а не во вторую копию поверх Telegram. +- Файл сразу копируется в приложение (§4.4): чужое приложение даёт доступ только на время. Имя базы — имя файла без расширения. Имя без известного расширения (`file_123`) читается как PGN. +- **Пока копируется** — модальный диалог без кнопок, его не закрыть ни «назад», ни нажатием мимо: + +``` +┌──────────────────────────────┐ +│ (◌) Открываю файл… │ 24 dp индикатор, 16 dp, bodyLarge +└──────────────────────────────┘ отступы 24 dp, extraLarge, surfaceContainerHigh +``` + +- **Готово** — диалог закрывается, база встаёт в конец списка. Стек сбрасывается до «Баз», поверх — «Партии» этой базы, а если партия одна — «Партия». То, что было открыто до этого, закрывается: пришедший файл важнее. +- **Ошибка** — диалог: + + > **Файл не открылся** + > {причина} + > [Понятно] + + Причина — та же, что при открытии базы из списка (§11): «В этом файле нет шахматных партий.», «Файл повреждён или это не шахматная база.», пароль, `.2cbh` и т. п. Если файл не удалось прочитать (доступ отозван, файла уже нет) — «Файл не прочитался: его уже нет или приложение, из которого он открыт, не дало к нему доступа. Попробуйте открыть его ещё раз.» В список ничего не добавляется, экран под диалогом не меняется. +- TalkBack: при появлении диалога «Открываю файл…» фокус на нём, текст читается сразу; индикатор без своего описания. Диалог ошибки — обычный `AlertDialog`: заголовок, причина, кнопка. ## 5. Открытие и чтение @@ -524,7 +555,7 @@ FAB открывает лист, а не сразу системный выбо - На первой партии ‹ неактивна, на последней неактивна ›. - Партия сменяется плавно (§10.8). Стек экранов не растёт: «назад» ведёт в «Партии». - Свайпа между партиями нет: случайно потерять место в разобранной партии хуже, чем лишний раз нажать стрелку. -- Если партия открыта не из списка (из буфера или из «Поделиться» с одной партией), кнопок ‹ › нет. +- Партия из буфера или из файла с одной партией — тоже база в списке (§4.5, §4.6): «1 из 1», обе стрелки неактивны. ### 7.7. Верхняя панель и меню ⋮ @@ -764,7 +795,7 @@ FAB открывает лист, а не сразу системный выбо - **Тема:** «Как в системе» (по умолчанию), «Светлая» или «Тёмная». - **Цвета обоев** — §10.3. - **Язык:** «Как в системе» и шесть языков компьютера (English, Русский, Français, Deutsch, Español, Italiano). Язык задаётся через `AppCompatDelegate.setApplicationLocales`: на Android 13+ тот же выбор виден в системных настройках приложения, на Android 12 работает внутри приложения. Если язык системы не из этих шести, интерфейс на английском. -- **Движок → Дополнительно:** «Потоки» — от 1 до числа ядер, по умолчанию половина, но не больше 4. «Память» — 16, 32, 64, 128 или 256 МБ, по умолчанию 64. +- **Движок → Дополнительно:** «Потоки» — от 1 до числа ядер, по умолчанию половина, но не больше 2 (с 0.11.2; раньше 4): интерфейсу телефона остаётся место. У тех, кто не менял старое значение по умолчанию, оно заменяется новым. «Память» — 16, 32, 64, 128 или 256 МБ, по умолчанию 64. - «Скачать» в настройках открывает тот же лист «Движок Stockfish» (§8.4), а не начинает загрузку молча: в листе есть предупреждение о мобильном интернете и отмена. - Строка состояния движка зависит от сборки и §8.4: «Stockfish 19 · встроен», «Не скачан · Скачать (80 МБ)», «Скачивается… 23 из 80 МБ» или «Stockfish 19 · скачан» с пунктом «Удалить движок». @@ -967,6 +998,9 @@ FAB открывает лист, а не сразу системный выбо | Облачный файл без сети | экран ошибки | «Файл в облаке, а интернета нет…» | «Повторить» | | Файл повреждён посередине | Партии, полоса сверху | «Прочитано {n} партий; дальше файл повреждён.» | «Подробности» | | Ничего не найдено | Партии | «Ничего не найдено» | «Сбросить поиск» / «Сбросить фильтры» | +| В буфере нет PGN | Базы, снекбар | «В буфере нет партий в формате PGN» | — | +| Файл из другого приложения копируется | диалог | «Открываю файл…» | — | +| Файл из другого приложения не открылся | диалог | «Файл не открылся» / причина | «Понятно» | | Ошибки скачивания движка | лист движка | §8.4 | §8.4 | | Движок не отвечает | строка движка | «Движок не отвечает» | «Перезапустить» | | Движок не запускается | строка движка | «Движок не запускается на этом телефоне» | — | @@ -1095,8 +1129,6 @@ FAB открывает лист, а не сразу системный выбо | `db_remove` | Убрать из списка | Remove from list | | `db_removed` | База убрана из списка | Database removed from the list | | `undo` | Вернуть | Undo | -| `db_remove_copy_title` | Убрать базу? | Remove the database? | -| `db_remove_copy_body` | Копия в ChessPenguin будет удалена. Исходный файл не изменится. | The copy in ChessPenguin will be deleted. The original file stays as it is. | | `remove` | Убрать | Remove | | `cancel` / `save` | Отмена / Сохранить | Cancel / Save | | `db_stop_reading` | Остановить чтение | Stop reading | @@ -1110,7 +1142,7 @@ FAB открывает лист, а не сразу системный выбо | `add_title` | Добавить базу | Add database | | `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_paste` / `add_paste_hint` | Вставить PGN из буфера / Партии, скопированные в другом приложении | Paste PGN from the clipboard / Games copied in another app | | `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. | @@ -1127,10 +1159,10 @@ FAB открывает лист, а не сразу системный выбо | `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 | -| `paste_db` | Из буфера | From the clipboard | -| `not_in_list` / `not_in_list_add` | Этой базы нет в списке. / Добавить | This database is not in your list. / Add | -| `db_added` | База добавлена | Database added | +| `paste_none` | В буфере нет партий в формате PGN | No PGN games in the clipboard | +| `paste_db` | Из буфера, {when} | Pasted {when} | +| `db_copy` | {n} партий · {format} · копия | {n} games · {format} · copy | +| `removed_copy` | База удалена из ChessPenguin | Database deleted from ChessPenguin | | `examples_classics` / `examples_alekhine` | Классические партии / Алехин | Classic games / Alekhine | ### 14.2. Открытие и ошибки @@ -1153,6 +1185,10 @@ FAB открывает лист, а не сразу системный выбо | `err_broken` | Прочитано {n} партий; дальше файл повреждён. | {n} games read; the rest of the file is damaged. | | `file_changed` | Файл изменился — читаю заново | The file has changed — reading it again | | `to_databases` | К базам | To databases | +| `opening_file` | Открываю файл… | Opening the file… | +| `file_failed` | Файл не открылся | Couldn't open the file | +| `file_no_games` | В этом файле нет шахматных партий. | There are no chess games in this file. | +| `file_unreadable` | Файл не прочитался: его уже нет или приложение, из которого он открыт, не дало к нему доступа. Попробуйте открыть его ещё раз. | The file could not be read: it may be gone, or the app it came from did not give access to it. Try opening it again. | | `retry` | Повторить | Retry | | `details` / `copy` | Подробности / Копировать | Details / Copy | @@ -1332,3 +1368,14 @@ FAB открывает лист, а не сразу системный выбо - §9, §9.1, §10.5, §10.9, §16 — выбор доски и набора фигур на отдельном экране с превью; решение §16.2 о «первой версии без выбора» заменено. - §6.1, §6.2, §12.3 — номер партии в базе слева в строке списка, виден и при поиске. - §0, §7.6, §8.3, §14.6 — кнопка «Движок» больше не запоминается: каждая партия открывается с выключенным движком; выход из партии, фон и погасший экран его выключают; поворот, Настройки поверх партии и ‹ › — нет. + +## 20. Вставка из буфера и файлы из других приложений (2026-10-23) + +- §2.1, §4.4, §4.5, §4.6 — временные базы с полосой «Этой базы нет в списке [Добавить]» отменены: вставленный текст и файл из «Открыть с помощью» / «Поделиться» сразу становятся копией в списке. Одна партия открывает «Партию», несколько — «Партии». +- §4.1 — «Вставить PGN из буфера» первой строкой листа, только когда в буфере текст; сам буфер читается по нажатию. +- §4.4, §3.3 — у копии в строке «· копия»; «Убрать из списка» удаляет копию со снекбаром «База удалена из ChessPenguin · Вернуть» вместо диалога; повтор того же файла или текста открывает прежнюю копию. +- §4.5 — имя вставки: игроки для одной партии, общий `Event` для нескольких, иначе «Из буфера, 23 окт., 14:05». +- §4.6, §11 — диалоги «Открываю файл…» и «Файл не открылся»; `text/plain` не принимается; `singleTask`. +- §7.6 — партия из буфера или из файла с одной партией — «1 из 1» с неактивными ‹ ›. +- §9 — потоков движка по умолчанию не больше 2. Кнопка «Движок» включает и выключает анализ, движок запускается только ею (§19); экран партии при анализе перерисовывает только строку движка и стрелки. +- §14.1, §14.2 — новые и исправленные строки.