Android: paste PGN, open files from other apps, a calmer screen while the engine thinks
Some checks are pending
CI / check (push) Waiting to run
CI / windows-build (push) Waiting to run
CI / macos-build (push) Waiting to run

- Paste: «Add a database» offers the clipboard's games when it holds text; they are kept
  in the app as a copy (one game opens on the board). Text with no game is said so.
- Open with / Share: PGN, ZIP, 7z, .cbv from other apps are copied in, listed and opened;
  one copy at a time, the last one shown; not again from Recents; a lone .cbh says to
  add its folder. A copy is marked «copy» and removing it deletes it.
- Engine: the button turns it off again; its words reach the screen up to 5 times a
  second and redraw only the strip and the arrows; Stockfish runs at nice 10 (uci
  EngineConfig::nice) with 2 threads by default.
- PGN scan: tags right after a result on the same line start the next game.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vrubelroman 2026-10-23 02:06:08 +03:00
parent cb61f546ba
commit 7d77a1aaef
26 changed files with 618 additions and 66 deletions

View file

@ -12,13 +12,37 @@
android:theme="@style/Theme.ChessPenguin"
android:localeConfig="@xml/locales_config"
android:enableOnBackInvokedCallback="true">
<!-- One task: a file opened from another app comes to the app already open. -->
<activity
android:name=".MainActivity"
android:exported="true">
android:exported="true"
android:launchMode="singleTask">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<!-- "Open with": PGN, ZIP, 7z, and files of no known type (.cbv, and .pgn
from apps that do not know it). -->
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="content" />
<data android:mimeType="application/x-chess-pgn" />
<data android:mimeType="application/vnd.chess-pgn" />
<data android:mimeType="application/zip" />
<data android:mimeType="application/x-7z-compressed" />
<data android:mimeType="application/octet-stream" />
</intent-filter>
<!-- "Share" with a file of the same kinds. -->
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="application/x-chess-pgn" />
<data android:mimeType="application/vnd.chess-pgn" />
<data android:mimeType="application/zip" />
<data android:mimeType="application/x-7z-compressed" />
<data android:mimeType="application/octet-stream" />
</intent-filter>
</activity>
</application>

View file

@ -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<Incoming?>(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
}

View file

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

View file

@ -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<Databases> {
DatabasesScreen(onOpen = { backStack.add(Games(it)) }, onSettings = { backStack.add(SettingsKey) })
DatabasesScreen(onOpen = { backStack.add(Games(it)) }, onAdded = ::show, onSettings = { backStack.add(SettingsKey) })
}
entry<Games> { 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)
}

View file

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

View file

@ -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<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")
private val copies = File(context.filesDir, "copies")
private val json = Json { ignoreUnknownKeys = true }
private val _entries = MutableStateFlow(load())
val entries: StateFlow<List<DbEntry>> = _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(),
)
}
}
}

View file

@ -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> = _prefs.asStateFlow()

View file

@ -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)) },

View file

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

View file

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

View file

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

View file

@ -211,4 +211,16 @@
<string name="board">Brett</string>
<string name="pieces_tab">Figuren</string>
<string name="game_number">Nr. %1$s</string>
<string name="add_paste">PGN aus der Zwischenablage einfügen</string>
<string name="add_paste_hint">In einer anderen App kopierte Partien</string>
<string name="paste_none">Keine PGN-Partien in der Zwischenablage</string>
<string name="paste_db">Eingefügt am %1$s</string>
<string name="opening_file">Datei wird geöffnet…</string>
<string name="file_failed">Die Datei ließ sich nicht öffnen</string>
<string name="file_no_games">Diese Datei enthält keine Schachpartien.</string>
<string name="file_unreadable">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.</string>
<string name="file_chessbase_part">Eine ChessBase-Datenbank (.cbh) besteht aus mehreren Dateien, gekommen ist nur eine. Fügen Sie ihren Ordner hinzu: „Datenbank hinzufügen“ → „Ordner“.</string>
<string name="file_copy_failed">Die App konnte keine Kopie der Datei speichern. Prüfen Sie, ob auf dem Telefon Platz frei ist.</string>
<string name="db_copy">Kopie</string>
<string name="removed_copy">Datenbank aus ChessPenguin gelöscht</string>
</resources>

View file

@ -215,4 +215,16 @@
<string name="board">Tablero</string>
<string name="pieces_tab">Piezas</string>
<string name="game_number">N.º %1$s</string>
<string name="add_paste">Pegar PGN del portapapeles</string>
<string name="add_paste_hint">Partidas copiadas en otra aplicación</string>
<string name="paste_none">No hay partidas PGN en el portapapeles</string>
<string name="paste_db">Pegado el %1$s</string>
<string name="opening_file">Abriendo el archivo…</string>
<string name="file_failed">No se pudo abrir el archivo</string>
<string name="file_no_games">Este archivo no contiene partidas de ajedrez.</string>
<string name="file_unreadable">No se pudo leer el archivo: ya no existe o la aplicación de la que viene no dio acceso. Ábralo otra vez.</string>
<string name="file_chessbase_part">Una base de ChessBase (.cbh) consta de varios archivos y solo llegó uno. Añada su carpeta: «Añadir base» → «Carpeta».</string>
<string name="file_copy_failed">La aplicación no pudo guardar una copia del archivo. Compruebe que el teléfono tiene espacio libre.</string>
<string name="db_copy">copia</string>
<string name="removed_copy">Base eliminada de ChessPenguin</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 ou un dossier de bases : PGN, ChessBase, archives .zip et .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>
@ -157,9 +157,9 @@
<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_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>
<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>
@ -181,7 +181,7 @@
<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>
<string name="open_missing_part">Le fichier %1$s n’est plus à côté de la base : il a été déplacé ou supprimé.</string>
<string name="board_and_pieces">Échiquier et pièces</string>
<string name="board_brown">Marron</string>
<string name="board_blue">Bleu</string>
@ -215,4 +215,16 @@
<string name="board">Échiquier</string>
<string name="pieces_tab">Pièces</string>
<string name="game_number">N° %1$s</string>
<string name="add_paste">Coller le PGN du presse-papiers</string>
<string name="add_paste_hint">Parties copiées dans une autre application</string>
<string name="paste_none">Aucune partie PGN dans le presse-papiers</string>
<string name="paste_db">Collé le %1$s</string>
<string name="opening_file">Ouverture du fichier…</string>
<string name="file_failed">Impossible d’ouvrir le fichier</string>
<string name="file_no_games">Ce fichier ne contient aucune partie d’échecs.</string>
<string name="file_unreadable">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.</string>
<string name="file_chessbase_part">Une base ChessBase (.cbh) se compose de plusieurs fichiers, et un seul est arrivé. Ajoutez son dossier : « Ajouter une base » → « Dossier ».</string>
<string name="file_copy_failed">L’application n’a pas pu garder une copie du fichier. Vérifiez qu’il reste de la place sur le téléphone.</string>
<string name="db_copy">copie</string>
<string name="removed_copy">Base supprimée de ChessPenguin</string>
</resources>

View file

@ -215,4 +215,16 @@
<string name="board">Scacchiera</string>
<string name="pieces_tab">Pezzi</string>
<string name="game_number">N. %1$s</string>
<string name="add_paste">Incolla PGN dagli appunti</string>
<string name="add_paste_hint">Partite copiate in un’altra app</string>
<string name="paste_none">Nessuna partita PGN negli appunti</string>
<string name="paste_db">Incollato il %1$s</string>
<string name="opening_file">Apertura del file…</string>
<string name="file_failed">Impossibile aprire il file</string>
<string name="file_no_games">Questo file non contiene partite a scacchi.</string>
<string name="file_unreadable">Impossibile leggere il file: non esiste più o l’app da cui proviene non ha concesso l’accesso. Riaprilo.</string>
<string name="file_chessbase_part">Un database ChessBase (.cbh) è fatto di più file, ma ne è arrivato solo uno. Aggiungi la sua cartella: «Aggiungi database» → «Cartella».</string>
<string name="file_copy_failed">L’app non è riuscita a salvare una copia del file. Controlla che sul telefono ci sia spazio libero.</string>
<string name="db_copy">copia</string>
<string name="removed_copy">Database eliminato da ChessPenguin</string>
</resources>

View file

@ -219,4 +219,16 @@
<string name="board">Доска</string>
<string name="pieces_tab">Фигуры</string>
<string name="game_number">№ %1$s</string>
<string name="add_paste">Вставить PGN из буфера</string>
<string name="add_paste_hint">Партии, скопированные в другом приложении</string>
<string name="paste_none">В буфере нет партий в формате PGN</string>
<string name="paste_db">Из буфера, %1$s</string>
<string name="opening_file">Открываю файл…</string>
<string name="file_failed">Файл не открылся</string>
<string name="file_no_games">В этом файле нет шахматных партий.</string>
<string name="file_unreadable">Файл не прочитался: его уже нет или приложение, из которого он открыт, не дало к нему доступа. Попробуйте открыть его ещё раз.</string>
<string name="file_chessbase_part">База ChessBase (.cbh) состоит из нескольких файлов, а пришёл один. Добавьте папку, где она лежит: «Добавить базу» → «Папка».</string>
<string name="file_copy_failed">Приложению не удалось сохранить копию файла. Проверьте, есть ли на телефоне свободное место.</string>
<string name="db_copy">копия</string>
<string name="removed_copy">База удалена из ChessPenguin</string>
</resources>

View file

@ -214,4 +214,16 @@
<string name="board_ncf" translatable="false">NCF</string>
<string name="pieces_tab">Pieces</string>
<string name="game_number">No. %1$s</string>
<string name="add_paste">Paste PGN from the clipboard</string>
<string name="add_paste_hint">Games copied in another app</string>
<string name="paste_none">No PGN games in the clipboard</string>
<string name="paste_db">Pasted %1$s</string>
<string name="opening_file">Opening the file…</string>
<string name="file_failed">Couldn’t open the file</string>
<string name="file_no_games">There are no chess games in this file.</string>
<string name="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.</string>
<string name="file_chessbase_part">A ChessBase database (.cbh) is made of several files, and only one came. Add the folder it is in: \"Add database\" → \"Folder\".</string>
<string name="file_copy_failed">The app could not keep a copy of the file. Check that the phone has free space.</string>
<string name="db_copy">copy</string>
<string name="removed_copy">Database deleted from ChessPenguin</string>
</resources>