feat: open PGN from Android clipboard

This commit is contained in:
vrubelroman 2026-11-05 21:14:42 +03:00
parent 4eb0822ec6
commit 5e3d1ead3f
22 changed files with 849 additions and 14 deletions

View file

@ -7,6 +7,9 @@ import androidx.compose.runtime.setValue
import android.net.Uri
import android.provider.OpenableColumns
import io.github.vrubelroman.chesspenguin.data.AppUpdates
import io.github.vrubelroman.chesspenguin.data.CLIPBOARD_PREFERENCES
import io.github.vrubelroman.chesspenguin.data.ClipboardOffer
import io.github.vrubelroman.chesspenguin.data.ClipboardPgn
import io.github.vrubelroman.chesspenguin.data.DbEntry
import io.github.vrubelroman.chesspenguin.data.EngineFiles
import io.github.vrubelroman.chesspenguin.data.MaiaFiles
@ -24,7 +27,6 @@ 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
@ -49,6 +51,18 @@ class ChessPenguinApp : Application() {
val downloads by lazy { OnlineDownloads(library, scope) }
/// The app's own updates (android-ui.md §25).
val updates by lazy { AppUpdates(this, scope, engineFiles) }
val clipboardPgn by lazy {
ClipboardPgn(
library,
scope,
getSharedPreferences(CLIPBOARD_PREFERENCES, MODE_PRIVATE),
latestIncoming.lock,
) {
if (latestIncoming.invalidateClipboard() && incoming.value == Incoming.Opening) {
incoming.value = null
}
}
}
override fun onCreate() {
super.onCreate()
@ -79,13 +93,14 @@ class ChessPenguinApp : Application() {
/// 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()
private val latestIncoming = LatestIncoming()
/// 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
val request = latestIncoming.withLock {
latestIncoming.next(IncomingOrigin.Uri).also { incoming.value = Incoming.Opening }
}
scope.launch {
val result = copying.withLock {
try {
@ -101,9 +116,47 @@ class ChessPenguinApp : Application() {
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
latestIncoming.publish(request) { incoming.value = result }
}
}
fun openClipboard(offer: ClipboardOffer, name: String) {
val (accepted, request) = latestIncoming.withLock {
val accepted = clipboardPgn.accept(offer) ?: return
val request = latestIncoming.next(IncomingOrigin.Clipboard)
incoming.value = Incoming.Opening
accepted to request
}
scope.launch {
val result = copying.withLock {
try {
Incoming.Pasted(library.addCopy("clipboard.pgn", accepted.bytes.inputStream()) { name })
} catch (e: Exception) {
Incoming.Failed(e)
}
}
latestIncoming.withLock {
if (!latestIncoming.isLatest(request)) {
clipboardPgn.finish(accepted, false)
return@withLock
}
if (!clipboardPgn.canPublish(accepted)) {
if (incoming.value == Incoming.Opening) incoming.value = null
return@withLock
}
when (result) {
is Incoming.Pasted -> {
clipboardPgn.finish(accepted, true)
incoming.value = result
}
is Incoming.Failed -> {
clipboardPgn.finish(accepted, false)
incoming.value = result
}
else -> incoming.value = null
}
latestIncoming.clear(request)
}
}
}
@ -119,8 +172,47 @@ class ChessBasePart : Exception()
private val CHESSBASE_PARTS = setOf("cbh", "cbg", "cba", "cbp", "cbs", "cbj", "cbt", "cbc", "cbe", "cbm")
internal enum class IncomingOrigin {
Uri,
Clipboard,
}
internal class LatestIncoming {
internal val lock = Any()
private var generation = 0L
private var origin: IncomingOrigin? = null
fun next(origin: IncomingOrigin = IncomingOrigin.Uri): Long = synchronized(lock) {
this.origin = origin
++generation
}
fun isLatest(request: Long): Boolean = synchronized(lock) { request == generation }
fun invalidateClipboard(): Boolean = synchronized(lock) {
if (origin != IncomingOrigin.Clipboard) return false
origin = null
generation += 1
true
}
fun clear(request: Long) = synchronized(lock) {
if (isLatest(request)) origin = null
}
fun publish(request: Long, action: () -> Unit): Boolean = synchronized(lock) {
if (!isLatest(request)) return false
action()
clear(request)
true
}
inline fun <T> withLock(action: () -> T): T = synchronized(lock, action)
}
sealed interface Incoming {
data object Opening : Incoming
data class Opened(val entry: DbEntry) : Incoming
data class Pasted(val entry: DbEntry) : Incoming
data class Failed(val error: Throwable) : Incoming
}

View file

@ -1,5 +1,6 @@
package io.github.vrubelroman.chesspenguin
import android.content.ClipboardManager
import android.content.Context
import android.app.UiModeManager
import android.content.Intent
@ -117,7 +118,9 @@ class MainActivity : ComponentActivity() {
override fun onResume() {
super.onResume()
(application as ChessPenguinApp).updates.onResume()
val app = application as ChessPenguinApp
app.updates.onResume()
app.clipboardPgn.check(clipboardText(this))
}
override fun onStop() {
@ -127,3 +130,10 @@ class MainActivity : ComponentActivity() {
if (!isChangingConfigurations) (application as ChessPenguinApp).leftApp()
}
}
fun clipboardText(context: Context): String? = context.getSystemService(ClipboardManager::class.java)
?.primaryClip
?.takeIf { it.itemCount > 0 }
?.getItemAt(0)
?.text
?.toString()

View file

@ -16,6 +16,8 @@ import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.pluralStringResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
@ -77,17 +79,67 @@ fun MainNavigation() {
backStack.add(Games(entry.id))
if (entry.games == 1) backStack.add(GameAt(entry.id, 0))
}
fun showPasted(entry: DbEntry) {
while (backStack.size > 1) backStack.removeAt(backStack.lastIndex)
backStack.add(Games(entry.id))
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) {
is Incoming.Opened -> {
if (app.incoming.compareAndSet(i, null)) show(i.entry)
}
is Incoming.Pasted -> {
if (app.incoming.compareAndSet(i, null)) {
resetPastedView(app.shown, app.lastOpened, i.entry.id)
showPasted(i.entry)
}
}
else -> {}
}
}
// The app's update, over any screen (android-ui.md §25.3).
val updateSheet by app.updates.sheet.collectAsState()
if (updateSheet) UpdateSheet()
val clipboardUnblocked = incoming == null && !updateSheet
val context = LocalContext.current
LaunchedEffect(clipboardUnblocked) {
if (clipboardUnblocked) app.clipboardPgn.check(clipboardText(context))
}
val clipboardOffer by app.clipboardPgn.offer.collectAsState()
if (clipboardUnblocked) {
clipboardOffer?.let { offer ->
val clipboardName = stringResource(R.string.clipboard_database_name)
AlertDialog(
onDismissRequest = { app.clipboardPgn.dismiss(offer) },
title = { Text(pluralStringResource(R.plurals.clipboard_open_title, offer.games, offer.games)) },
text = {
Text(
if (offer.games == 1) {
stringResource(R.string.clipboard_open_one)
} else {
stringResource(
R.string.clipboard_open_many,
pluralStringResource(R.plurals.games_count, offer.games, offer.games),
)
},
)
},
confirmButton = {
TextButton(onClick = { app.openClipboard(offer, clipboardName) }) {
Text(stringResource(R.string.clipboard_open))
}
},
dismissButton = {
TextButton(onClick = { app.clipboardPgn.dismiss(offer) }) {
Text(stringResource(R.string.cancel))
}
},
)
}
}
when (val i = incoming) {
Incoming.Opening -> Dialog(onDismissRequest = {}, properties = DialogProperties(dismissOnBackPress = false, dismissOnClickOutside = false)) {
Surface(shape = MaterialTheme.shapes.extraLarge, color = MaterialTheme.colorScheme.surfaceContainerHigh) {
@ -99,10 +151,10 @@ fun MainNavigation() {
}
}
is Incoming.Failed -> AlertDialog(
onDismissRequest = { app.incoming.value = null },
onDismissRequest = { app.incoming.compareAndSet(i, 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)) } },
confirmButton = { TextButton(onClick = { app.incoming.compareAndSet(i, null) }) { Text(stringResource(R.string.ok)) } },
)
else -> {}
}
@ -168,6 +220,15 @@ fun MainNavigation() {
)
}
internal fun resetPastedView(
shown: HashMap<String, List<UInt>>,
lastOpened: HashMap<String, Pair<String, Int>>,
id: String,
) {
shown.remove(id)
lastOpened.remove(id)
}
/// 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

View file

@ -0,0 +1,173 @@
package io.github.vrubelroman.chesspenguin.data
import android.content.SharedPreferences
import java.security.MessageDigest
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
internal const val CLIPBOARD_PGN_MAX_BYTES = 8 * 1024 * 1024
internal const val CLIPBOARD_PREFERENCES = "clipboard-pgn"
private const val PREFS_DIGESTS = "decided-sha256"
data class ClipboardOffer(
val bytes: ByteArray,
val games: Int,
internal val digest: String,
internal val generation: Long,
)
data class ClipboardAccept(
val bytes: ByteArray,
internal val digest: String,
internal val generation: Long,
)
class ClipboardPgn(
private val library: Library,
private val scope: CoroutineScope,
preferences: SharedPreferences,
private val requestLock: Any,
private val invalidateIncoming: () -> Unit,
) {
private val gate = ClipboardPromptGate(
decided = preferences.getStringSet(PREFS_DIGESTS, null).orEmpty(),
onDecide = { digests -> preferences.edit().putStringSet(PREFS_DIGESTS, digests).apply() },
)
private val _offer = MutableStateFlow<ClipboardOffer?>(null)
val offer: StateFlow<ClipboardOffer?> = _offer.asStateFlow()
private var hasSnapshot = false
private var lastSnapshot: String? = null
fun check(text: String?) {
val generation = synchronized(requestLock) {
val changed = if (hasSnapshot && text == lastSnapshot) {
false
} else {
hasSnapshot = true
lastSnapshot = text
true
}
if (!changed) return
invalidateIncoming()
gate.invalidate().also { _offer.value = null }
}
if (text.isNullOrBlank() || !clipboardPgnLengthMayFit(text)) return
scope.launch {
val bytes = clipboardUtf8(text)
if (!clipboardPgnWithinLimit(bytes.size)) return@launch
val digest = clipboardSha256(bytes)
val games = try {
library.countPgnGames(bytes)
} catch (e: CancellationException) {
throw e
} catch (_: Exception) {
null
}
if (games == null) return@launch
val offer = ClipboardOffer(bytes, games, digest, generation)
synchronized(requestLock) {
if (gate.publish(offer)) {
_offer.value = offer
}
}
}
}
fun accept(offer: ClipboardOffer): ClipboardAccept? = synchronized(requestLock) {
gate.accept(offer)?.also { _offer.value = null }
}
fun dismiss(offer: ClipboardOffer) {
synchronized(requestLock) {
if (gate.dismiss(offer)) {
_offer.value = null
}
}
}
fun canPublish(accept: ClipboardAccept): Boolean = synchronized(requestLock) { gate.canPublish(accept) }
fun finish(accept: ClipboardAccept, success: Boolean): Boolean = synchronized(requestLock) {
val finished = gate.finish(accept, success)
if (finished && !success) {
hasSnapshot = false
lastSnapshot = null
}
finished
}
}
internal class ClipboardPromptGate(
decided: Set<String> = emptySet(),
private val onDecide: (Set<String>) -> Unit = {},
) {
private val decided = HashSet(decided)
private var generation = 0L
private var offer: ClipboardOffer? = null
private var accepted: ClipboardAccept? = null
@Synchronized
fun invalidate(): Long {
generation += 1
offer = null
accepted = null
return generation
}
@Synchronized
fun publish(offer: ClipboardOffer): Boolean {
if (offer.generation != generation || offer.digest in decided || accepted != null) return false
this.offer = offer
return true
}
@Synchronized
fun accept(offer: ClipboardOffer): ClipboardAccept? {
if (this.offer != offer || accepted != null) return null
val accept = ClipboardAccept(offer.bytes, offer.digest, offer.generation)
accepted = accept
this.offer = null
return accept
}
@Synchronized
fun dismiss(offer: ClipboardOffer): Boolean {
if (this.offer != offer) return false
this.offer = null
decide(offer.digest)
return true
}
@Synchronized
fun canPublish(accept: ClipboardAccept): Boolean =
accepted == accept && accept.generation == generation
@Synchronized
fun finish(accept: ClipboardAccept, success: Boolean): Boolean {
if (accepted != accept || accept.generation != generation) return false
accepted = null
if (success) {
decide(accept.digest)
} else {
invalidate()
}
return true
}
private fun decide(digest: String) {
if (decided.add(digest)) onDecide(decided.toSet())
}
}
internal fun clipboardPgnLengthMayFit(text: String): Boolean = text.length <= CLIPBOARD_PGN_MAX_BYTES
internal fun clipboardUtf8(text: String): ByteArray = text.toByteArray(Charsets.UTF_8)
internal fun clipboardSha256(bytes: ByteArray): String =
MessageDigest.getInstance("SHA-256").digest(bytes).joinToString("") { "%02x".format(it) }
internal fun clipboardPgnWithinLimit(size: Int): Boolean = size <= CLIPBOARD_PGN_MAX_BYTES

View file

@ -251,6 +251,27 @@ class Library(private val context: Context) {
return entry
}
/// Counts real games in PGN text without keeping a copy of it.
suspend fun countPgnGames(text: String): Int? = countPgnGames(clipboardUtf8(text))
suspend fun countPgnGames(bytes: ByteArray): Int? = withContext(Dispatchers.IO) {
if (!clipboardPgnWithinLimit(bytes.size)) return@withContext null
val db = runCatching { openBytes("clipboard.pgn", bytes) }.getOrNull() ?: return@withContext null
try {
val count = db.len().toInt()
if (count == 0) {
null
} else {
val first = db.game(0u)
if (firstPgnGameIsMeaningful(count, first.tags.size, first.nodes.size)) count else null
}
} catch (_: ApiException) {
null
} finally {
db.close()
}
}
/// 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
@ -272,7 +293,7 @@ class Library(private val context: Context) {
}
val sum = digest.digest().joinToString("") { "%02x".format(it) }
lock.withLock {
_entries.value.firstOrNull { it.source == Source.Copy && it.sha256 == sum }?.let { return@withContext it }
copyWithDigest(_entries.value, sum)?.let { return@withContext it }
}
val id = UUID.randomUUID().toString()
val kept = File(copies, "$id.$ext")
@ -305,6 +326,11 @@ class Library(private val context: Context) {
sha256 = sum,
)
lock.withLock {
copyWithDigest(_entries.value, sum)?.let { existing ->
db.close()
kept.delete()
return@withContext existing
}
open[id] = db
update { it + entry }
}
@ -627,5 +653,11 @@ class Library(private val context: Context) {
}
}
internal fun firstPgnGameIsMeaningful(count: Int, tags: Int, nodes: Int): Boolean =
count > 0 && (tags > 0 || nodes > 1)
internal fun copyWithDigest(entries: List<DbEntry>, digest: String): DbEntry? =
entries.firstOrNull { it.source == Source.Copy && it.sha256 == digest }
private fun sha256(bytes: ByteArray): String =
java.security.MessageDigest.getInstance("SHA-256").digest(bytes).joinToString("") { "%02x".format(it) }

View file

@ -213,6 +213,14 @@
<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>
<plurals name="clipboard_open_title">
<item quantity="one">Partie in der Zwischenablage</item>
<item quantity="other">Partien in der Zwischenablage</item>
</plurals>
<string name="clipboard_open_one">Diese PGN-Partie speichern und auf dem Brett öffnen?</string>
<string name="clipboard_open_many">%1$s speichern und die erste Partie auf dem Brett öffnen? Alle Partien bleiben in der lokalen Kopie.</string>
<string name="clipboard_open">Öffnen</string>
<string name="clipboard_database_name">Zwischenablage</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>

View file

@ -217,6 +217,15 @@
<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>
<plurals name="clipboard_open_title">
<item quantity="one">Partida en el portapapeles</item>
<item quantity="many">Partidas en el portapapeles</item>
<item quantity="other">Partidas en el portapapeles</item>
</plurals>
<string name="clipboard_open_one">Guardar esta partida PGN y abrirla en el tablero?</string>
<string name="clipboard_open_many">Guardar %1$s y abrir la primera partida en el tablero? Todas las partidas se conservarán en la copia local.</string>
<string name="clipboard_open">Abrir</string>
<string name="clipboard_database_name">Portapapeles</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>

View file

@ -217,6 +217,15 @@
<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>
<plurals name="clipboard_open_title">
<item quantity="one">%1$s partie dans le presse-papiers</item>
<item quantity="many">%1$s parties dans le presse-papiers</item>
<item quantity="other">%1$s parties dans le presse-papiers</item>
</plurals>
<string name="clipboard_open_one">Enregistrer cette partie PGN et l’ouvrir sur l’échiquier ?</string>
<string name="clipboard_open_many">Enregistrer %1$s et ouvrir la première partie sur l’échiquier ? Toutes les parties seront conservées dans la copie locale.</string>
<string name="clipboard_open">Ouvrir</string>
<string name="clipboard_database_name">Presse-papiers</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>

View file

@ -217,6 +217,15 @@
<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>
<plurals name="clipboard_open_title">
<item quantity="one">Partita negli appunti</item>
<item quantity="many">Partite negli appunti</item>
<item quantity="other">Partite negli appunti</item>
</plurals>
<string name="clipboard_open_one">Salvare questa partita PGN e aprirla sulla scacchiera?</string>
<string name="clipboard_open_many">Salvare %1$s e aprire la prima partita sulla scacchiera? Tutte le partite saranno conservate nella copia locale.</string>
<string name="clipboard_open">Apri</string>
<string name="clipboard_database_name">Appunti</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>

View file

@ -213,6 +213,14 @@
<string name="add_paste_hint">Басқа бағдарламада көшірілген партиялар</string>
<string name="paste_none">Алмасу буферінде PGN партиясы жоқ</string>
<string name="paste_db">Қойылды: %1$s</string>
<plurals name="clipboard_open_title">
<item quantity="one">Алмасу буферіндегі партия</item>
<item quantity="other">Алмасу буферіндегі партиялар</item>
</plurals>
<string name="clipboard_open_one">Осы PGN партиясын сақтап, тақтада ашу керек пе?</string>
<string name="clipboard_open_many">%1$s сақтап, бірінші партияны тақтада ашу керек пе? Барлық партиялар жергілікті көшірмеде сақталады.</string>
<string name="clipboard_open">Ашу</string>
<string name="clipboard_database_name">Алмасу буфері</string>
<string name="opening_file">Файл ашылуда…</string>
<string name="file_failed">Файлды ашу мүмкін болмады</string>
<string name="file_no_games">Бұл файлда шахмат партиялары жоқ.</string>

View file

@ -217,6 +217,15 @@
<string name="add_paste_hint">Partidas copiadas em outro app</string>
<string name="paste_none">Nenhuma partida PGN na área de transferência</string>
<string name="paste_db">Colado %1$s</string>
<plurals name="clipboard_open_title">
<item quantity="one">%1$s partida na área de transferência</item>
<item quantity="many">%1$s partidas na área de transferência</item>
<item quantity="other">%1$s partidas na área de transferência</item>
</plurals>
<string name="clipboard_open_one">Salvar esta partida PGN e abri-la no tabuleiro?</string>
<string name="clipboard_open_many">Salvar %1$s e abrir a primeira partida no tabuleiro? Todas as partidas serão mantidas na cópia local.</string>
<string name="clipboard_open">Abrir</string>
<string name="clipboard_database_name">Área de transferência</string>
<string name="opening_file">Abrindo o arquivo…</string>
<string name="file_failed">Não foi possível abrir o arquivo</string>
<string name="file_no_games">Não há partidas de xadrez neste arquivo.</string>

View file

@ -221,6 +221,16 @@
<string name="add_paste_hint">Партии, скопированные в другом приложении</string>
<string name="paste_none">В буфере нет партий в формате PGN</string>
<string name="paste_db">Из буфера, %1$s</string>
<plurals name="clipboard_open_title">
<item quantity="one">%1$s партия в буфере обмена</item>
<item quantity="few">%1$s партии в буфере обмена</item>
<item quantity="many">%1$s партий в буфере обмена</item>
<item quantity="other">%1$s партии в буфере обмена</item>
</plurals>
<string name="clipboard_open_one">Сохранить PGN-партию и открыть её на доске?</string>
<string name="clipboard_open_many">Сохранить %1$s и открыть первую партию на доске? Все партии останутся в локальной копии.</string>
<string name="clipboard_open">Открыть</string>
<string name="clipboard_database_name">Буфер обмена</string>
<string name="opening_file">Открываю файл…</string>
<string name="file_failed">Файл не открылся</string>
<string name="file_no_games">В этом файле нет шахматных партий.</string>

View file

@ -214,6 +214,14 @@
<string name="add_paste_hint">Boshqa ilovada nusxalangan partiyalar</string>
<string name="paste_none">Almashish buferida PGN partiyalar yoʻq</string>
<string name="paste_db">Qoʻyildi: %1$s</string>
<plurals name="clipboard_open_title">
<item quantity="one">Almashish buferida partiya</item>
<item quantity="other">Almashish buferida partiyalar</item>
</plurals>
<string name="clipboard_open_one">Bu PGN partiyani saqlab, doskada ochish?</string>
<string name="clipboard_open_many">%1$s saqlab, birinchi partiyani doskada ochish? Barcha partiyalar mahalliy nusxada saqlanadi.</string>
<string name="clipboard_open">Ochish</string>
<string name="clipboard_database_name">Almashish buferi</string>
<string name="opening_file">Fayl ochilmoqda…</string>
<string name="file_failed">Faylni ochib boʻlmadi</string>
<string name="file_no_games">Bu faylda shaxmat partiyalari yoʻq.</string>

View file

@ -216,6 +216,14 @@
<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>
<plurals name="clipboard_open_title">
<item quantity="one">Game in clipboard</item>
<item quantity="other">Games in clipboard</item>
</plurals>
<string name="clipboard_open_one">Save this PGN game and open it on the board?</string>
<string name="clipboard_open_many">Save %1$s and open the first game on the board? All games will be kept in the local copy.</string>
<string name="clipboard_open">Open</string>
<string name="clipboard_database_name">Clipboard</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>

View file

@ -0,0 +1,95 @@
package io.github.vrubelroman.chesspenguin
import io.github.vrubelroman.chesspenguin.data.DbEntry
import io.github.vrubelroman.chesspenguin.data.Source
import kotlinx.coroutines.flow.MutableStateFlow
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
class ClipboardIncomingTest {
@Test
fun `pasted existing copy ignores a previous empty filtered view`() {
val shown = hashMapOf("copy" to emptyList<UInt>())
val lastOpened = hashMapOf("copy" to ("not-found" to 0))
resetPastedView(shown, lastOpened, "copy")
assertFalse(shown.containsKey("copy"))
assertFalse(lastOpened.containsKey("copy"))
}
@Test
fun `uri and clipboard publish only their latest common request`() {
val requests = LatestIncoming()
val uri = requests.next()
val clipboard = requests.next()
assertFalse(requests.isLatest(uri))
assertTrue(requests.isLatest(clipboard))
val newerUri = requests.next()
assertFalse(requests.isLatest(clipboard))
assertTrue(requests.isLatest(newerUri))
}
@Test
fun `stale request cannot publish after a newer request starts`() {
val requests = LatestIncoming()
val old = requests.next()
val current = requests.next()
var published: Long? = null
assertFalse(requests.publish(old) { published = old })
assertNull(published)
assertTrue(requests.publish(current) { published = current })
assertEquals(current, published)
}
@Test
fun `blank clipboard snapshot does not invalidate uri import`() {
val requests = LatestIncoming()
val uri = requests.next(IncomingOrigin.Uri)
assertFalse(requests.invalidateClipboard())
assertTrue(requests.isLatest(uri))
}
@Test
fun `clipboard snapshot invalidates active clipboard import`() {
val requests = LatestIncoming()
val clipboard = requests.next(IncomingOrigin.Clipboard)
assertTrue(requests.invalidateClipboard())
assertFalse(requests.isLatest(clipboard))
}
@Test
fun `failed dismiss compareAndSet cannot clear a newer opening`() {
val incoming = MutableStateFlow<Incoming?>(Incoming.Failed(IllegalStateException("old")))
val expected = incoming.value
incoming.value = Incoming.Opening
assertFalse(incoming.compareAndSet(expected, null))
assertEquals(Incoming.Opening, incoming.value)
}
@Test
fun `stale collector cannot clear a newer incoming event`() {
val entry = DbEntry(
id = "copy",
name = "Clipboard",
source = Source.Copy,
location = "copy.pgn",
fileName = "clipboard.pgn",
)
val incoming = MutableStateFlow<Incoming?>(Incoming.Opened(entry))
val expected = incoming.value
incoming.value = Incoming.Opening
assertFalse(incoming.compareAndSet(expected, null))
assertEquals(Incoming.Opening, incoming.value)
}
}

View file

@ -0,0 +1,135 @@
package io.github.vrubelroman.chesspenguin.data
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertSame
import org.junit.Assert.assertTrue
import org.junit.Test
class ClipboardPromptGateTest {
@Test
fun `new offer is accepted once and same offer cannot be accepted twice`() {
val gate = ClipboardPromptGate()
val generation = gate.invalidate()
val offer = offer("same", generation)
assertTrue(gate.publish(offer))
val accepted = gate.accept(offer)
assertNotNull(accepted)
assertNull(gate.accept(offer))
assertTrue(gate.canPublish(accepted!!))
}
@Test
fun `blank snapshot invalidates offer and pending publication`() {
val gate = ClipboardPromptGate()
val generation = gate.invalidate()
val offer = offer("old", generation)
assertTrue(gate.publish(offer))
val accepted = gate.accept(offer)!!
gate.invalidate()
assertFalse(gate.canPublish(accepted))
assertFalse(gate.publish(offer))
}
@Test
fun `stale accept is ignored after snapshot changes`() {
val gate = ClipboardPromptGate()
val old = offer("old", gate.invalidate())
assertTrue(gate.publish(old))
gate.invalidate()
val current = offer("current", gate.invalidate())
assertNull(gate.accept(old))
assertTrue(gate.publish(current))
assertNotNull(gate.accept(current))
}
@Test
fun `changed snapshot forbids old import publication`() {
val gate = ClipboardPromptGate()
val accepted = gate.accept(offer("old", gate.invalidate()).also { gate.publish(it) })!!
gate.invalidate()
assertFalse(gate.canPublish(accepted))
}
@Test
fun `dismissed digest stays decided while changed text is allowed`() {
val gate = ClipboardPromptGate()
val dismissed = offer("dismissed", gate.invalidate())
assertTrue(gate.publish(dismissed))
assertTrue(gate.dismiss(dismissed))
assertFalse(gate.publish(dismissed.copy(generation = gate.invalidate())))
assertTrue(gate.publish(offer("changed", gate.invalidate())))
}
@Test
fun `successful open persists digest only after entry and survives cold restoration`() {
var persisted = emptySet<String>()
val first = ClipboardPromptGate(onDecide = { persisted = it })
val offer = offer("sha256-of-opened-text", first.invalidate())
assertTrue(first.publish(offer))
val accepted = first.accept(offer)!!
assertTrue(persisted.isEmpty())
assertTrue(first.finish(accepted, true))
val restored = ClipboardPromptGate(decided = persisted)
assertFalse(restored.publish(offer.copy(generation = restored.invalidate())))
assertTrue(restored.publish(offer.copy(digest = "new-text", generation = restored.invalidate())))
}
@Test
fun `failed import does not persist digest and retries after cold start`() {
var persisted = emptySet<String>()
val first = ClipboardPromptGate(onDecide = { persisted = it })
val offer = offer("retry-digest", first.invalidate())
assertTrue(first.publish(offer))
val accepted = first.accept(offer)!!
assertTrue(persisted.isEmpty())
assertTrue(first.finish(accepted, false))
val restored = ClipboardPromptGate(decided = persisted)
assertTrue(restored.publish(offer.copy(generation = restored.invalidate())))
}
@Test
fun `one UTF8 snapshot preserves BOM CRLF unicode and import bytes`() {
val text = "\uFEFF[Event \"Партия 😀\"]\r\n1. e4 e5\r\n*"
val bytes = clipboardUtf8(text)
val gate = ClipboardPromptGate()
val offer = ClipboardOffer(bytes, 1, clipboardSha256(bytes), gate.invalidate())
assertTrue(gate.publish(offer))
val accepted = gate.accept(offer)!!
assertArrayEquals(text.toByteArray(Charsets.UTF_8), accepted.bytes)
assertSame(bytes, accepted.bytes)
assertNotEquals(
clipboardSha256(bytes),
clipboardSha256(clipboardUtf8(text.replace("\r\n", "\n"))),
)
}
@Test
fun `clipboard size limit includes eight MiB and rejects one byte more`() {
assertTrue(clipboardPgnLengthMayFit("a".repeat(CLIPBOARD_PGN_MAX_BYTES)))
assertFalse(clipboardPgnLengthMayFit("a".repeat(CLIPBOARD_PGN_MAX_BYTES + 1)))
assertTrue(clipboardPgnWithinLimit(CLIPBOARD_PGN_MAX_BYTES - 1))
assertTrue(clipboardPgnWithinLimit(CLIPBOARD_PGN_MAX_BYTES))
assertFalse(clipboardPgnWithinLimit(CLIPBOARD_PGN_MAX_BYTES + 1))
}
private fun offer(digest: String, generation: Long, games: Int = 1): ClipboardOffer =
ClipboardOffer(byteArrayOf(1), games, digest, generation)
}

View file

@ -0,0 +1,47 @@
package io.github.vrubelroman.chesspenguin.data
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertSame
import org.junit.Assert.assertTrue
import org.junit.Test
class LibraryClipboardTest {
@Test
fun `first valid record is accepted even when a later record is malformed`() {
assertTrue(firstPgnGameIsMeaningful(count = 2, tags = 1, nodes = 1))
assertTrue(firstPgnGameIsMeaningful(count = 2, tags = 0, nodes = 2))
}
@Test
fun `first malformed record is rejected even when a later record is valid`() {
assertFalse(firstPgnGameIsMeaningful(count = 2, tags = 0, nodes = 1))
}
@Test
fun `multiple empty records and zero records are rejected`() {
assertFalse(firstPgnGameIsMeaningful(count = 3, tags = 0, nodes = 1))
assertFalse(firstPgnGameIsMeaningful(count = 0, tags = 0, nodes = 0))
}
@Test
fun `tag only first record is accepted by the shared addCopy rule`() {
assertTrue(firstPgnGameIsMeaningful(count = 1, tags = 1, nodes = 1))
}
@Test
fun `final digest lookup reuses an existing copy after concurrent parsing`() {
val existing = DbEntry(
id = "existing",
name = "Clipboard",
source = Source.Copy,
location = "existing.pgn",
fileName = "clipboard.pgn",
sha256 = "same-digest",
)
val other = existing.copy(id = "other", sha256 = "other-digest")
assertSame(existing, copyWithDigest(listOf(other, existing), "same-digest"))
assertNull(copyWithDigest(listOf(other, existing), "new-digest"))
}
}