Merge Android clipboard into opening training
# Conflicts: # CHANGELOG.md # docs/decisions.md # docs/dev/tasks.md
This commit is contained in:
commit
a4521d94ed
32 changed files with 1905 additions and 113 deletions
|
|
@ -23,6 +23,11 @@ All notable changes are listed here. Versions follow [Semantic Versioning](https
|
|||
statistics preserve shared moves on each actual PGN line while the global total deduplicates
|
||||
them. The library table keeps ECO codes, opening names and the actual number of variations;
|
||||
the training board has no move list and keeps PGN badges, arrows and circles.
|
||||
- Android: when the app opens or returns to the foreground, a PGN in the clipboard can be
|
||||
opened from a small confirmation dialog. One or several games are stored as a local copy,
|
||||
and the first game always opens on the board. Opening or dismissing the same text is remembered
|
||||
across restarts; an unsuccessful import can be retried. Clipboard checks are local, generation-safe,
|
||||
limited to 8 MiB and never start an import without confirmation.
|
||||
|
||||
## [2.1.5] — 2026-11-02
|
||||
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
@ -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) }
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
}
|
||||
}
|
||||
|
|
@ -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)
|
||||
}
|
||||
|
|
@ -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"))
|
||||
}
|
||||
}
|
||||
|
|
@ -18738,6 +18738,259 @@ const ROWS: &[[&str; 9]] = &[
|
|||
"Diapazon −2…2. Moslashuvchan tezlik = koeffitsiyent × (1 + o‘rganilgan ulush), 0,25×–4× bilan cheklangan: to‘liq o‘rganilgan yurishda 1,5 3× beradi; 0 yoki undan kam 0,25× beradi.",
|
||||
"Ауқым −2…2. Бейімделгіш жылдамдық = коэффициент × (1 + үйренілген үлес), 0,25×–4× шегінде: толық үйренілген жүрісте 1,5 — 3×; 0 немесе одан аз — 0,25×.",
|
||||
],
|
||||
[
|
||||
"plies",
|
||||
"полуходов",
|
||||
"demi-coups",
|
||||
"Halbzüge",
|
||||
"semimovimientos",
|
||||
"semimosse",
|
||||
"meios lances",
|
||||
"yarim yurishlar",
|
||||
"жарты жүрістер",
|
||||
],
|
||||
[
|
||||
"Select a move in the PGN tree",
|
||||
"Выберите ход в дереве PGN",
|
||||
"Sélectionnez un coup dans l’arbre PGN",
|
||||
"Wählen Sie einen Zug im PGN-Baum",
|
||||
"Selecciona una jugada en el árbol PGN",
|
||||
"Seleziona una mossa nell’albero PGN",
|
||||
"Selecione um lance na árvore PGN",
|
||||
"PGN daraxtidan yurishni tanlang",
|
||||
"PGN ағашынан жүрісті таңдаңыз",
|
||||
],
|
||||
[
|
||||
"Main answer",
|
||||
"Основной ответ",
|
||||
"Réponse principale",
|
||||
"Hauptzug",
|
||||
"Respuesta principal",
|
||||
"Risposta principale",
|
||||
"Resposta principal",
|
||||
"Asosiy javob",
|
||||
"Негізгі жауап",
|
||||
],
|
||||
[
|
||||
"Make main answer",
|
||||
"Сделать основным ответом",
|
||||
"Définir comme réponse principale",
|
||||
"Als Hauptzug festlegen",
|
||||
"Establecer como respuesta principal",
|
||||
"Imposta come risposta principale",
|
||||
"Definir como resposta principal",
|
||||
"Asosiy javob qilib belgilash",
|
||||
"Негізгі жауап етіп белгілеу",
|
||||
],
|
||||
[
|
||||
"Clear override",
|
||||
"Убрать переопределение",
|
||||
"Supprimer la surcharge",
|
||||
"Überschreibung aufheben",
|
||||
"Quitar anulación",
|
||||
"Rimuovi sostituzione",
|
||||
"Remover substituição",
|
||||
"Almashtirishni bekor qilish",
|
||||
"Қайта анықтауды жою",
|
||||
],
|
||||
[
|
||||
"Enable",
|
||||
"Включить",
|
||||
"Activer",
|
||||
"Aktivieren",
|
||||
"Activar",
|
||||
"Attiva",
|
||||
"Ativar",
|
||||
"Yoqish",
|
||||
"Қосу",
|
||||
],
|
||||
[
|
||||
"Disable",
|
||||
"Отключить",
|
||||
"Désactiver",
|
||||
"Deaktivieren",
|
||||
"Desactivar",
|
||||
"Disattiva",
|
||||
"Desativar",
|
||||
"O‘chirish",
|
||||
"Өшіру",
|
||||
],
|
||||
[
|
||||
"Disabled for training",
|
||||
"Отключено для тренировки",
|
||||
"Désactivé pour l’entraînement",
|
||||
"Für das Training deaktiviert",
|
||||
"Desactivado para el entrenamiento",
|
||||
"Disattivato per l’allenamento",
|
||||
"Desativado para treinamento",
|
||||
"Mashg‘ulot uchun o‘chirilgan",
|
||||
"Жаттығу үшін өшірілген",
|
||||
],
|
||||
[
|
||||
"PGN tree",
|
||||
"Дерево PGN",
|
||||
"Arbre PGN",
|
||||
"PGN-Baum",
|
||||
"Árbol PGN",
|
||||
"Albero PGN",
|
||||
"Árvore PGN",
|
||||
"PGN daraxti",
|
||||
"PGN ағашы",
|
||||
],
|
||||
[
|
||||
"Initial position",
|
||||
"Начальная позиция",
|
||||
"Position initiale",
|
||||
"Anfangsstellung",
|
||||
"Posición inicial",
|
||||
"Posizione iniziale",
|
||||
"Posição inicial",
|
||||
"Boshlang‘ich pozitsiya",
|
||||
"Бастапқы позиция",
|
||||
],
|
||||
[
|
||||
"main",
|
||||
"основной",
|
||||
"principal",
|
||||
"Hauptzug",
|
||||
"principal",
|
||||
"principale",
|
||||
"principal",
|
||||
"asosiy",
|
||||
"негізгі",
|
||||
],
|
||||
[
|
||||
"disabled",
|
||||
"отключено",
|
||||
"désactivé",
|
||||
"deaktiviert",
|
||||
"desactivado",
|
||||
"disattivato",
|
||||
"desativado",
|
||||
"o‘chirilgan",
|
||||
"өшірілген",
|
||||
],
|
||||
[
|
||||
"Move analytics",
|
||||
"Аналитика хода",
|
||||
"Statistiques du coup",
|
||||
"Zugstatistik",
|
||||
"Estadísticas de la jugada",
|
||||
"Statistiche della mossa",
|
||||
"Estatísticas do lance",
|
||||
"Yurish statistikasi",
|
||||
"Жүріс статистикасы",
|
||||
],
|
||||
[
|
||||
"Select a move to see its learning analytics",
|
||||
"Выберите ход, чтобы увидеть аналитику его обучения",
|
||||
"Sélectionnez un coup pour voir ses statistiques d’apprentissage",
|
||||
"Wählen Sie einen Zug, um seine Lernstatistik zu sehen",
|
||||
"Selecciona una jugada para ver sus estadísticas de aprendizaje",
|
||||
"Seleziona una mossa per vedere le sue statistiche di apprendimento",
|
||||
"Selecione um lance para ver suas estatísticas de aprendizagem",
|
||||
"O‘rganish statistikasini ko‘rish uchun yurishni tanlang",
|
||||
"Үйрену статистикасын көру үшін жүрісті таңдаңыз",
|
||||
],
|
||||
[
|
||||
"Shared learning data is not connected",
|
||||
"Общие данные обучения не подключены",
|
||||
"Les données d’apprentissage partagées ne sont pas connectées",
|
||||
"Gemeinsame Lerndaten sind nicht verbunden",
|
||||
"Los datos de aprendizaje compartidos no están conectados",
|
||||
"I dati di apprendimento condivisi non sono collegati",
|
||||
"Os dados de aprendizagem compartilhados não estão conectados",
|
||||
"Umumiy o‘rganish ma’lumotlari ulanmagan",
|
||||
"Ортақ үйрену деректері қосылмаған",
|
||||
],
|
||||
[
|
||||
"Learning analytics is kept for the current main answer",
|
||||
"Аналитика обучения ведётся для текущего основного ответа",
|
||||
"Les statistiques d’apprentissage sont conservées pour la réponse principale actuelle",
|
||||
"Lernstatistik wird für den aktuellen Hauptzug geführt",
|
||||
"Las estadísticas de aprendizaje se guardan para la respuesta principal actual",
|
||||
"Le statistiche di apprendimento sono conservate per la risposta principale attuale",
|
||||
"As estatísticas de aprendizagem são mantidas para a resposta principal atual",
|
||||
"O‘rganish statistikasi joriy asosiy javob uchun saqlanadi",
|
||||
"Үйрену статистикасы ағымдағы негізгі жауап үшін сақталады",
|
||||
],
|
||||
[
|
||||
"The selected move cannot be the main answer for this position",
|
||||
"Выбранный ход не может быть основным ответом в этой позиции",
|
||||
"Le coup sélectionné ne peut pas être la réponse principale pour cette position",
|
||||
"Der ausgewählte Zug kann in dieser Stellung nicht der Hauptzug sein",
|
||||
"La jugada seleccionada no puede ser la respuesta principal para esta posición",
|
||||
"La mossa selezionata non può essere la risposta principale per questa posizione",
|
||||
"O lance selecionado não pode ser a resposta principal para esta posição",
|
||||
"Tanlangan yurish bu pozitsiyada asosiy javob bo‘la olmaydi",
|
||||
"Таңдалған жүріс бұл позицияда негізгі жауап бола алмайды",
|
||||
],
|
||||
[
|
||||
"The selected PGN branch cannot be disabled",
|
||||
"Выбранную ветку PGN нельзя отключить",
|
||||
"La variante PGN sélectionnée ne peut pas être désactivée",
|
||||
"Der ausgewählte PGN-Zweig kann nicht deaktiviert werden",
|
||||
"La variante PGN seleccionada no se puede desactivar",
|
||||
"La variante PGN selezionata non può essere disattivata",
|
||||
"A variante PGN selecionada não pode ser desativada",
|
||||
"Tanlangan PGN variantini o‘chirish mumkin emas",
|
||||
"Таңдалған PGN нұсқасын өшіру мүмкін емес",
|
||||
],
|
||||
[
|
||||
"The selected PGN branch cannot be enabled",
|
||||
"Выбранную ветку PGN нельзя включить",
|
||||
"La variante PGN sélectionnée ne peut pas être activée",
|
||||
"Der ausgewählte PGN-Zweig kann nicht aktiviert werden",
|
||||
"La variante PGN seleccionada no se puede activar",
|
||||
"La variante PGN selezionata non può essere attivata",
|
||||
"A variante PGN selecionada não pode ser ativada",
|
||||
"Tanlangan PGN variantini yoqish mumkin emas",
|
||||
"Таңдалған PGN нұсқасын қосу мүмкін емес",
|
||||
],
|
||||
[
|
||||
"Next due",
|
||||
"Следующее повторение",
|
||||
"Prochaine révision",
|
||||
"Nächste Wiederholung",
|
||||
"Próximo repaso",
|
||||
"Prossimo ripasso",
|
||||
"Próxima revisão",
|
||||
"Keyingi takrorlash",
|
||||
"Келесі қайталау",
|
||||
],
|
||||
[
|
||||
"Response median",
|
||||
"Медиана времени ответа",
|
||||
"Médiane du temps de réponse",
|
||||
"Median der Antwortzeit",
|
||||
"Mediana del tiempo de respuesta",
|
||||
"Mediana del tempo di risposta",
|
||||
"Mediana do tempo de resposta",
|
||||
"Javob vaqti medianasi",
|
||||
"Жауап уақытының медианасы",
|
||||
],
|
||||
[
|
||||
"Wrong moves",
|
||||
"Ошибочные ходы",
|
||||
"Coups erronés",
|
||||
"Falsche Züge",
|
||||
"Jugadas erróneas",
|
||||
"Mosse errate",
|
||||
"Lances errados",
|
||||
"Noto‘g‘ri yurishlar",
|
||||
"Қате жүрістер",
|
||||
],
|
||||
[
|
||||
"Unknown move",
|
||||
"Неизвестный ход",
|
||||
"Coup inconnu",
|
||||
"Unbekannter Zug",
|
||||
"Jugada desconocida",
|
||||
"Mossa sconosciuta",
|
||||
"Lance desconhecido",
|
||||
"Noma’lum yurish",
|
||||
"Белгісіз жүріс",
|
||||
],
|
||||
// --- learning dashboard ---
|
||||
[
|
||||
"Learning dashboard",
|
||||
|
|
@ -19496,6 +19749,7 @@ mod tests {
|
|||
include_str!("learning_branches.rs"),
|
||||
include_str!("learning_charts.rs"),
|
||||
include_str!("learning_dashboard.rs"),
|
||||
include_str!("repertoire_editor.rs"),
|
||||
];
|
||||
let mut chars = std::collections::BTreeSet::new();
|
||||
for row in ROWS.iter() {
|
||||
|
|
@ -19573,6 +19827,7 @@ mod tests {
|
|||
include_str!("learning_branches.rs"),
|
||||
include_str!("learning_charts.rs"),
|
||||
include_str!("learning_dashboard.rs"),
|
||||
include_str!("repertoire_editor.rs"),
|
||||
include_str!("repertoire_ui.rs"),
|
||||
include_str!("repertoire_training.rs"),
|
||||
];
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ const WIDE_WIDTH: f32 = 900.0;
|
|||
const HEADER_HEIGHT: f32 = 40.0;
|
||||
const ROW_HEIGHT: f32 = 24.0;
|
||||
const BODY_TEXT_SIZE: f32 = 14.0;
|
||||
const WIDE_NUMERIC_WIDTHS: [f32; 9] = [56.0, 60.0, 80.0, 64.0, 108.0, 96.0, 88.0, 64.0, 136.0];
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct BranchSelection {
|
||||
|
|
@ -161,7 +162,7 @@ fn show_wide(
|
|||
.max_scroll_height(360.0)
|
||||
.cell_layout(Layout::left_to_right(Align::Center))
|
||||
.column(Column::remainder().at_least(120.0).clip(true));
|
||||
for width in [30.0, 66.0, 70.0, 52.0, 72.0, 46.0, 68.0, 64.0, 136.0] {
|
||||
for width in WIDE_NUMERIC_WIDTHS {
|
||||
table = table.column(Column::exact(width).clip(true));
|
||||
}
|
||||
table
|
||||
|
|
@ -280,42 +281,39 @@ fn show_details(
|
|||
("Accuracy", format_percent(row.summary.accuracy_percent)),
|
||||
("Last trained", format_time(row.last_independent_at)),
|
||||
];
|
||||
egui::Grid::new("learning_branches_details")
|
||||
.num_columns(2)
|
||||
.spacing([12.0, 5.0])
|
||||
.show(ui, |ui| {
|
||||
for (label, value) in details {
|
||||
ui.add(
|
||||
egui::Label::new(RichText::new(tr(label)).weak().size(BODY_TEXT_SIZE)).wrap(),
|
||||
);
|
||||
ui.add(egui::Label::new(RichText::new(value).size(BODY_TEXT_SIZE)).wrap());
|
||||
ui.end_row();
|
||||
}
|
||||
show_details_rows(ui, &details);
|
||||
}
|
||||
|
||||
fn show_details_rows(ui: &mut Ui, details: &[(&'static str, String)]) {
|
||||
let label_width = (ui.available_width() * 0.36).clamp(110.0, 160.0);
|
||||
TableBuilder::new(ui)
|
||||
.id_salt("learning_branches_details")
|
||||
.vscroll(false)
|
||||
.cell_layout(Layout::left_to_right(Align::Min))
|
||||
.column(Column::exact(label_width).clip(true))
|
||||
.column(Column::remainder().at_least(80.0).clip(true))
|
||||
.body(|body| {
|
||||
body.rows(ROW_HEIGHT * 1.5, details.len(), |mut row| {
|
||||
let (label, value) = &details[row.index()];
|
||||
row.col(|ui| {
|
||||
ui.add(
|
||||
egui::Label::new(RichText::new(tr(label)).weak().size(BODY_TEXT_SIZE))
|
||||
.wrap(),
|
||||
);
|
||||
});
|
||||
row.col(|ui| {
|
||||
ui.add(egui::Label::new(RichText::new(value).size(BODY_TEXT_SIZE)).wrap());
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
fn header_cell(ui: &mut Ui, text: &str, numeric: bool) -> egui::Response {
|
||||
let text = RichText::new(text).strong().size(BODY_TEXT_SIZE);
|
||||
if numeric {
|
||||
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
|
||||
ui.add(egui::Label::new(text).wrap())
|
||||
})
|
||||
.inner
|
||||
} else {
|
||||
ui.add(egui::Label::new(text).wrap())
|
||||
}
|
||||
fn header_cell(ui: &mut Ui, text: &str, _numeric: bool) -> egui::Response {
|
||||
ui.add(egui::Label::new(RichText::new(text).strong().size(BODY_TEXT_SIZE)).wrap())
|
||||
}
|
||||
|
||||
fn text_cell(ui: &mut Ui, text: &str, numeric: bool) -> egui::Response {
|
||||
let text = RichText::new(text).size(BODY_TEXT_SIZE);
|
||||
if numeric {
|
||||
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
|
||||
ui.add(egui::Label::new(text).truncate())
|
||||
})
|
||||
.inner
|
||||
} else {
|
||||
ui.add(egui::Label::new(text).truncate())
|
||||
}
|
||||
fn text_cell(ui: &mut Ui, text: &str, _numeric: bool) -> egui::Response {
|
||||
ui.add(egui::Label::new(RichText::new(text).size(BODY_TEXT_SIZE)).truncate())
|
||||
}
|
||||
|
||||
fn format_percent(value: Option<f64>) -> String {
|
||||
|
|
@ -535,7 +533,7 @@ mod tests {
|
|||
fn wide_and_narrow_layouts_stay_in_bounds_in_light_and_dark() {
|
||||
let fixture = fixture();
|
||||
for visuals in [egui::Visuals::light(), egui::Visuals::dark()] {
|
||||
for (width, height) in [(1200.0, 800.0), (640.0, 480.0)] {
|
||||
for (width, height) in [(1400.0, 900.0), (960.0, 600.0), (640.0, 480.0)] {
|
||||
let ctx = egui::Context::default();
|
||||
ctx.set_visuals(visuals.clone());
|
||||
let mut selected = None;
|
||||
|
|
@ -592,6 +590,99 @@ mod tests {
|
|||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wide_headers_fit_accepted_matrix_in_russian_and_german() {
|
||||
let cases = [
|
||||
[
|
||||
"Ветка",
|
||||
"Итого",
|
||||
"Новый",
|
||||
"Изучается",
|
||||
"Изучено",
|
||||
"Не подтверждено",
|
||||
"К повторению",
|
||||
"Точность",
|
||||
"Изучено %",
|
||||
"Последняя тренировка",
|
||||
],
|
||||
[
|
||||
"Variante",
|
||||
"Gesamt",
|
||||
"Neu",
|
||||
"Lernen",
|
||||
"Gelernt",
|
||||
"Unsicher",
|
||||
"Fällig",
|
||||
"Genauigkeit",
|
||||
"Gelernt %",
|
||||
"Letztes Training",
|
||||
],
|
||||
];
|
||||
for visuals in [egui::Visuals::light(), egui::Visuals::dark()] {
|
||||
for (width, height) in [(960.0, 600.0), (1400.0, 900.0)] {
|
||||
for headers in &cases {
|
||||
let ctx = egui::Context::default();
|
||||
ctx.set_visuals(visuals.clone());
|
||||
let output = ctx.run_ui(
|
||||
egui::RawInput {
|
||||
screen_rect: Some(egui::Rect::from_min_size(
|
||||
egui::Pos2::ZERO,
|
||||
egui::vec2(width, height),
|
||||
)),
|
||||
..Default::default()
|
||||
},
|
||||
|ui| {
|
||||
let mut table = TableBuilder::new(ui)
|
||||
.id_salt("learning_branches_wide_header_test")
|
||||
.cell_layout(Layout::left_to_right(Align::Center))
|
||||
.column(Column::remainder().at_least(120.0).clip(true));
|
||||
for width in WIDE_NUMERIC_WIDTHS {
|
||||
table = table.column(Column::exact(width).clip(true));
|
||||
}
|
||||
table.header(HEADER_HEIGHT, |mut header| {
|
||||
for (index, key) in headers.iter().enumerate() {
|
||||
header.col(|ui| {
|
||||
header_cell(ui, tr(key), index > 0);
|
||||
});
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
let shapes = output.shapes.clone();
|
||||
output.drop_without_applying_deltas();
|
||||
assert_bounds(&shapes, width, height);
|
||||
for expected in headers {
|
||||
let (rect, clip, lines) = shapes
|
||||
.iter()
|
||||
.find_map(|clipped| match &clipped.shape {
|
||||
egui::Shape::Text(text)
|
||||
if text.galley.text().replace('\n', " ") == *expected =>
|
||||
{
|
||||
Some((
|
||||
egui::Rect::from_min_size(text.pos, text.galley.size()),
|
||||
clipped.clip_rect,
|
||||
text.galley.text().lines().count(),
|
||||
))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or_else(|| {
|
||||
panic!("missing full header {expected} at {width}x{height}")
|
||||
});
|
||||
assert!(lines <= 2, "header wraps too much: {expected}");
|
||||
assert!(
|
||||
rect.min.x >= clip.min.x - 0.1
|
||||
&& rect.min.y >= clip.min.y - 0.1
|
||||
&& rect.max.x <= clip.max.x + 0.1
|
||||
&& rect.max.y <= clip.max.y + 0.1,
|
||||
"clipped header {expected} at {width}x{height}: {rect:?} {clip:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn narrow_details_are_visible_and_click_selects_the_branch() {
|
||||
let fixture = fixture();
|
||||
|
|
@ -637,6 +728,78 @@ mod tests {
|
|||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn narrow_details_keep_long_labels_readable_at_all_widths() {
|
||||
let cases: Vec<Vec<(&str, String)>> = vec![
|
||||
vec![
|
||||
("Новый", "2".to_owned()),
|
||||
("Изучается", "1".to_owned()),
|
||||
("Изучено", "4".to_owned()),
|
||||
("Не подтверждено", "1".to_owned()),
|
||||
("К повторению", "3".to_owned()),
|
||||
("Точность", "75 %".to_owned()),
|
||||
("Последняя тренировка", "2026-11-04 08:26".to_owned()),
|
||||
],
|
||||
vec![
|
||||
("Neu", "2".to_owned()),
|
||||
("Wird gelernt", "1".to_owned()),
|
||||
("Gelernt", "4".to_owned()),
|
||||
("Nicht bestätigt", "1".to_owned()),
|
||||
("Fällig", "3".to_owned()),
|
||||
("Genauigkeit", "75 %".to_owned()),
|
||||
("Zuletzt trainiert", "2026-11-04 08:26".to_owned()),
|
||||
],
|
||||
];
|
||||
for visuals in [egui::Visuals::light(), egui::Visuals::dark()] {
|
||||
for width in [320.0, 360.0, 420.0, 640.0] {
|
||||
for details in &cases {
|
||||
let ctx = egui::Context::default();
|
||||
ctx.set_visuals(visuals.clone());
|
||||
let mut expected_label_width = 0.0;
|
||||
let output = ctx.run_ui(
|
||||
egui::RawInput {
|
||||
screen_rect: Some(egui::Rect::from_min_size(
|
||||
egui::Pos2::ZERO,
|
||||
egui::vec2(width, 700.0),
|
||||
)),
|
||||
..Default::default()
|
||||
},
|
||||
|ui| {
|
||||
egui::CentralPanel::default().show(ui, |ui| {
|
||||
expected_label_width =
|
||||
(ui.available_width() * 0.36).clamp(110.0, 160.0);
|
||||
show_details_rows(ui, details);
|
||||
});
|
||||
},
|
||||
);
|
||||
let shapes = output.shapes.clone();
|
||||
output.drop_without_applying_deltas();
|
||||
assert_bounds(&shapes, width, 700.0);
|
||||
for (label, _) in details {
|
||||
let (clip, lines) = shapes
|
||||
.iter()
|
||||
.find_map(|clipped| match &clipped.shape {
|
||||
egui::Shape::Text(text)
|
||||
if text.galley.text().replace('\n', " ") == *label =>
|
||||
{
|
||||
Some((clipped.clip_rect, text.galley.text().lines().count()))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or_else(|| panic!("missing full label {label} at {width}"));
|
||||
assert!(
|
||||
(clip.width() - expected_label_width).abs() < 0.1,
|
||||
"label column at {width}: {clip:?}, expected {expected_label_width}: {label}"
|
||||
);
|
||||
assert!(lines <= 2, "label wraps too much at {width}: {label}");
|
||||
}
|
||||
assert!(has_text(&shapes, "2026-11-04 08:26"));
|
||||
assert!(has_text(&shapes, "75 %"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn null_accuracy_and_last_training_render_as_dashes() {
|
||||
let fixture = fixture();
|
||||
|
|
|
|||
|
|
@ -11,8 +11,9 @@ use trainer::repertoire::{
|
|||
BranchLearningAnalytics, LearningAggregate, LearningItemKey, LearningSide, LearningSnapshot,
|
||||
LearningStore, LearningStoreData, Library, LocalDatePolicy, MoveLearningStatus,
|
||||
PersistedLearningSnapshot, RepertoireId, RepertoireTree, ScheduledBuckets, SequenceHistograms,
|
||||
SrsSettings, StatsScope, aggregate_scope, branch_learning_analytics, scheduled_buckets,
|
||||
scoped_move_learning_analytics, sequence_histograms,
|
||||
SrsSettings, StatsScope, aggregate_scope, branch_learning_analytics,
|
||||
log_global_total_invariant, scheduled_buckets, scoped_move_learning_analytics,
|
||||
sequence_histograms,
|
||||
};
|
||||
|
||||
use crate::i18n::{tr, trf};
|
||||
|
|
@ -68,6 +69,24 @@ struct DashboardData {
|
|||
labels: HashMap<(RepertoireId, Vec<String>), Vec<String>>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
std::thread_local! {
|
||||
static GLOBAL_TOTAL_INVARIANT_CALLS: std::cell::Cell<usize> =
|
||||
const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
fn log_dashboard_global_total_invariant(global_total: usize, summary: &[SummaryRow]) {
|
||||
log_global_total_invariant(
|
||||
global_total,
|
||||
summary
|
||||
.iter()
|
||||
.filter(|row| row.id.is_some())
|
||||
.map(|row| row.summary.total),
|
||||
);
|
||||
#[cfg(test)]
|
||||
GLOBAL_TOTAL_INVARIANT_CALLS.with(|calls| calls.set(calls.get() + 1));
|
||||
}
|
||||
|
||||
struct MoveRow {
|
||||
key: LearningItemKey,
|
||||
san: String,
|
||||
|
|
@ -597,11 +616,13 @@ impl DashboardData {
|
|||
});
|
||||
views.push(view);
|
||||
}
|
||||
let global_total = global_summary.total;
|
||||
summary.push(SummaryRow {
|
||||
id: None,
|
||||
name: String::new(),
|
||||
summary: global_summary,
|
||||
});
|
||||
log_dashboard_global_total_invariant(global_total, &summary);
|
||||
Ok(Self {
|
||||
side,
|
||||
as_of,
|
||||
|
|
@ -784,9 +805,22 @@ fn error_body(ui: &mut Ui, error: &str) {
|
|||
);
|
||||
}
|
||||
|
||||
const SUMMARY_HEADER_HEIGHT: f32 = 40.0;
|
||||
|
||||
fn summary_number_width(ui: &Ui) -> f32 {
|
||||
let available_width = ui.available_width();
|
||||
if available_width < 700.0 {
|
||||
60.0
|
||||
} else {
|
||||
(available_width / 9.0)
|
||||
.min(108.0)
|
||||
.min((available_width - 80.0 - 8.0 * ui.spacing().item_spacing.x) / 8.0)
|
||||
}
|
||||
}
|
||||
|
||||
fn show_summary(ui: &mut Ui, data: &DashboardData, view: &DashboardView) {
|
||||
let compact = ui.available_width() < 700.0;
|
||||
let number_width = 60.0;
|
||||
let number_width = summary_number_width(ui);
|
||||
let headers = [
|
||||
"Name",
|
||||
"Total",
|
||||
|
|
@ -808,7 +842,7 @@ fn show_summary(ui: &mut Ui, data: &DashboardData, view: &DashboardView) {
|
|||
table = table.column(Column::exact(number_width).clip(true));
|
||||
}
|
||||
table
|
||||
.header(if compact { 40.0 } else { 30.0 }, |mut header| {
|
||||
.header(SUMMARY_HEADER_HEIGHT, |mut header| {
|
||||
for (index, key) in headers.into_iter().enumerate() {
|
||||
header.col(|ui| {
|
||||
let response = if index == 0 {
|
||||
|
|
@ -1716,6 +1750,25 @@ mod tests {
|
|||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn global_total_invariant_runs_on_empty_build_without_changing_data() {
|
||||
GLOBAL_TOTAL_INVARIANT_CALLS.with(|calls| calls.set(0));
|
||||
|
||||
let dashboard = build(&Library::default(), &LearningStoreData::default()).unwrap();
|
||||
|
||||
assert_eq!(GLOBAL_TOTAL_INVARIANT_CALLS.with(|calls| calls.get()), 1);
|
||||
assert_eq!(dashboard.side, LearningSide::White);
|
||||
assert_eq!(dashboard.as_of, BASE);
|
||||
assert_eq!(dashboard.timezone, LocalDatePolicy::UTC);
|
||||
assert_eq!(dashboard.summary.len(), 1);
|
||||
assert!(dashboard.summary[0].id.is_none());
|
||||
assert_eq!(dashboard.summary[0].summary, LearningAggregate::default());
|
||||
assert_eq!(dashboard.views.len(), 1);
|
||||
assert_eq!(dashboard.views[0].summary, LearningAggregate::default());
|
||||
assert!(dashboard.names.is_empty());
|
||||
assert!(dashboard.labels.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_scope_has_no_false_percentages_or_buckets() {
|
||||
let dashboard = build(&Library::default(), &LearningStoreData::default()).unwrap();
|
||||
|
|
@ -1919,6 +1972,143 @@ mod tests {
|
|||
assert_eq!(store.load().unwrap().snapshots.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepted_summary_headers_fit_full_russian_and_german_words() {
|
||||
let cases = [
|
||||
[
|
||||
"Название",
|
||||
"Итого",
|
||||
"Новый",
|
||||
"Изучается",
|
||||
"Изучено",
|
||||
"Не подтверждено",
|
||||
"К повторению",
|
||||
"Изучено %",
|
||||
"Надёжно изучено",
|
||||
],
|
||||
[
|
||||
"Name",
|
||||
"Gesamt",
|
||||
"Neu",
|
||||
"Lernen",
|
||||
"Gelernt",
|
||||
"Unsicher",
|
||||
"Fällig",
|
||||
"Gelernt %",
|
||||
"Bestätigt %",
|
||||
],
|
||||
];
|
||||
for visuals in [egui::Visuals::light(), egui::Visuals::dark()] {
|
||||
for (width, height) in [(960.0, 600.0), (1400.0, 900.0)] {
|
||||
for headers in &cases {
|
||||
let ctx = egui::Context::default();
|
||||
ctx.set_visuals(visuals.clone());
|
||||
let mut expected_number_width = 0.0;
|
||||
let output = ctx.run_ui(
|
||||
egui::RawInput {
|
||||
screen_rect: Some(egui::Rect::from_min_size(
|
||||
egui::Pos2::ZERO,
|
||||
egui::vec2(width, height),
|
||||
)),
|
||||
..Default::default()
|
||||
},
|
||||
|ui| {
|
||||
expected_number_width = summary_number_width(ui);
|
||||
let number_width = expected_number_width;
|
||||
let mut table = TableBuilder::new(ui)
|
||||
.id_salt("learning_dashboard_summary_header_test")
|
||||
.cell_layout(Layout::left_to_right(Align::Center))
|
||||
.column(Column::remainder().at_least(80.0).clip(true));
|
||||
for _ in 1..headers.len() {
|
||||
table = table.column(Column::exact(number_width).clip(true));
|
||||
}
|
||||
table.header(SUMMARY_HEADER_HEIGHT, |mut header| {
|
||||
for (index, key) in headers.iter().enumerate() {
|
||||
header.col(|ui| {
|
||||
if index == 0 {
|
||||
header_cell(ui, tr(key), false)
|
||||
} else {
|
||||
summary_metric_header(ui, tr(key), false)
|
||||
}
|
||||
.on_hover_text(tr(key));
|
||||
});
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
let shapes = output.shapes.clone();
|
||||
output.drop_without_applying_deltas();
|
||||
for clipped in &shapes {
|
||||
let bounds = clipped.shape.visual_bounding_rect();
|
||||
if bounds.is_finite() && bounds.is_positive() {
|
||||
assert!(
|
||||
bounds.min.x >= -0.1
|
||||
&& bounds.min.y >= -0.1
|
||||
&& bounds.max.x <= width + 0.1
|
||||
&& bounds.max.y <= height + 0.1,
|
||||
"summary shape outside {width}x{height}: {bounds:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
for (index, &expected) in headers.iter().enumerate() {
|
||||
let (rect, clip, lines) = shapes
|
||||
.iter()
|
||||
.find_map(|clipped| match &clipped.shape {
|
||||
egui::Shape::Text(text)
|
||||
if text.galley.text().replace('\n', " ") == expected =>
|
||||
{
|
||||
Some((
|
||||
egui::Rect::from_min_size(text.pos, text.galley.size()),
|
||||
clipped.clip_rect,
|
||||
text.galley.text().lines().count(),
|
||||
))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or_else(|| {
|
||||
panic!("missing full summary header {expected} at {width}x{height}")
|
||||
});
|
||||
assert!(lines <= 2, "summary header wraps too much: {expected}");
|
||||
assert!(
|
||||
text_lines_have_complete_words(&shapes, expected),
|
||||
"summary header has a one-character fragment: {expected}"
|
||||
);
|
||||
assert!(
|
||||
rect.min.x >= clip.min.x - 0.1
|
||||
&& rect.min.y >= clip.min.y - 0.1
|
||||
&& rect.max.x <= clip.max.x + 0.1
|
||||
&& rect.max.y <= clip.max.y + 0.1,
|
||||
"clipped summary header {expected}: {rect:?} {clip:?}"
|
||||
);
|
||||
assert!(clip.height() >= SUMMARY_HEADER_HEIGHT);
|
||||
if index == 0 {
|
||||
assert!(clip.width() >= 80.0);
|
||||
} else {
|
||||
assert!(
|
||||
(clip.width() - expected_number_width).abs() < 0.1,
|
||||
"numeric width at {width}: {clip:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn text_lines_have_complete_words(
|
||||
shapes: &[egui::epaint::ClippedShape],
|
||||
expected: &str,
|
||||
) -> bool {
|
||||
shapes.iter().any(|clipped| match &clipped.shape {
|
||||
egui::Shape::Text(text) if text.galley.text().replace('\n', " ") == expected => text
|
||||
.galley
|
||||
.text()
|
||||
.lines()
|
||||
.all(|line| line.chars().count() > 1),
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_tab_renders_at_both_window_sizes() {
|
||||
let dir = TestDir::new("layout");
|
||||
|
|
@ -1953,7 +2143,7 @@ mod tests {
|
|||
loaded_dashboard(library, dir.store(), ScopeSelection::Repertoire(id), data);
|
||||
let settings = Settings::default();
|
||||
let ctx = egui::Context::default();
|
||||
for (width, height) in [(1400.0, 900.0), (640.0, 480.0)] {
|
||||
for (width, height) in [(1400.0, 900.0), (960.0, 600.0), (640.0, 480.0)] {
|
||||
for tab in [
|
||||
DashboardTab::Summary,
|
||||
DashboardTab::Branches,
|
||||
|
|
|
|||
|
|
@ -407,21 +407,21 @@ impl LearningTrainingUi {
|
|||
}
|
||||
}
|
||||
self.ready_since = None;
|
||||
if !self.board_shown {
|
||||
self.board_position = match parse_position(¤t) {
|
||||
Ok(position) => position,
|
||||
Err(error) => {
|
||||
self.error = Some(error);
|
||||
return;
|
||||
}
|
||||
};
|
||||
self.last_move = None;
|
||||
self.playback = None;
|
||||
self.pending_automatic = Some(steps);
|
||||
let Some(first) = steps.front() else {
|
||||
self.error = Some("automatic context has no visual step".to_owned());
|
||||
return;
|
||||
}
|
||||
self.pending_automatic = None;
|
||||
self.start_next_automatic(steps, now, 0);
|
||||
};
|
||||
self.board_position = match parse_position(&first.from) {
|
||||
Ok(position) => position,
|
||||
Err(error) => {
|
||||
self.error = Some(error);
|
||||
return;
|
||||
}
|
||||
};
|
||||
self.board_shown = false;
|
||||
self.pending_automatic = Some(steps);
|
||||
self.playback = None;
|
||||
self.last_move = None;
|
||||
return;
|
||||
}
|
||||
self.pending_automatic = None;
|
||||
|
|
@ -923,6 +923,9 @@ impl LearningTrainingUi {
|
|||
}
|
||||
|
||||
fn board_animation_seconds(&self, settings: &Settings) -> f32 {
|
||||
if self.pending_automatic.is_some() {
|
||||
return 0.0;
|
||||
}
|
||||
match &self.playback {
|
||||
Some(Playback::Automatic { duration, .. }) => duration.as_secs_f32(),
|
||||
_ => settings.animation.seconds(),
|
||||
|
|
@ -1216,6 +1219,10 @@ impl LearningTrainingUi {
|
|||
.playback_deadline()
|
||||
.map_or(started, |deadline| deadline.max(started));
|
||||
self.tick_at(at, Duration::ZERO, now());
|
||||
if self.pending_automatic.is_some() {
|
||||
self.board_shown = true;
|
||||
self.tick_at(at, Duration::ZERO, now());
|
||||
}
|
||||
if matches!(self.playback, Some(Playback::Wrong { .. })) {
|
||||
let until = self.playback_deadline().unwrap_or(at);
|
||||
self.tick_at(until, Duration::ZERO, now());
|
||||
|
|
@ -1224,7 +1231,7 @@ impl LearningTrainingUi {
|
|||
|
||||
pub fn debug_hint(&mut self) {
|
||||
if self.needs_prepare {
|
||||
self.tick_at(Instant::now(), Duration::ZERO, now());
|
||||
self.debug_settle();
|
||||
}
|
||||
let id = unique_id(self.session.id());
|
||||
self.request_hint_with_id_at(id, Instant::now(), now());
|
||||
|
|
@ -1232,7 +1239,7 @@ impl LearningTrainingUi {
|
|||
|
||||
pub fn debug_moves(&mut self, moves: &str) {
|
||||
if self.needs_prepare {
|
||||
self.tick_at(Instant::now(), Duration::ZERO, now());
|
||||
self.debug_settle();
|
||||
}
|
||||
for text in moves.split_whitespace() {
|
||||
match text {
|
||||
|
|
@ -1516,7 +1523,7 @@ mod tests {
|
|||
fn answer_current(f: &mut Fixture, at: Instant, happened_at: i64, id: &str) {
|
||||
let expected = f.ui.session.current_expected_uci().unwrap().to_owned();
|
||||
assert!(f.ui.play_uci_with_id_at(&expected, id.to_owned(), at, happened_at,));
|
||||
f.ui.tick_at(at, Duration::ZERO, happened_at);
|
||||
tick_with_prime(&mut f.ui, at, Duration::ZERO, happened_at);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -1603,6 +1610,35 @@ mod tests {
|
|||
.drop_without_applying_deltas();
|
||||
}
|
||||
|
||||
fn tick_with_prime(
|
||||
ui: &mut LearningTrainingUi,
|
||||
at: Instant,
|
||||
animation: Duration,
|
||||
happened_at: i64,
|
||||
) {
|
||||
ui.tick_at(at, animation, happened_at);
|
||||
if ui.pending_automatic.is_none() {
|
||||
return;
|
||||
}
|
||||
let ctx = egui::Context::default();
|
||||
let settings = Settings::default();
|
||||
ctx.run_ui(
|
||||
egui::RawInput {
|
||||
screen_rect: Some(egui::Rect::from_min_size(
|
||||
egui::Pos2::ZERO,
|
||||
egui::vec2(800.0, 800.0),
|
||||
)),
|
||||
time: Some(0.0),
|
||||
..Default::default()
|
||||
},
|
||||
|root| ui.board_ui(root, &settings),
|
||||
)
|
||||
.drop_without_applying_deltas();
|
||||
assert!(ui.board_shown);
|
||||
assert!(ui.board.animation_at(0.0).is_none());
|
||||
ui.tick_at(at, animation, happened_at);
|
||||
}
|
||||
|
||||
fn automatic_duration(f: &Fixture) -> Duration {
|
||||
match &f.ui.playback {
|
||||
Some(Playback::Automatic { duration, .. }) => *duration,
|
||||
|
|
@ -1653,7 +1689,7 @@ mod tests {
|
|||
assert_current_slide(f, 0.01, first, Square::E2, Square::E4);
|
||||
assert!(f.ui.message.is_none());
|
||||
|
||||
f.ui.tick_at(start + first, normal(), NOW);
|
||||
tick_with_prime(&mut f.ui, start + first, normal(), NOW);
|
||||
let last = automatic_duration(f);
|
||||
assert_eq!(last.as_millis(), last_ms);
|
||||
assert_eq!(f.ui.session.context_index, 1);
|
||||
|
|
@ -1661,7 +1697,7 @@ mod tests {
|
|||
assert_current_slide(f, 0.02, last, Square::E7, Square::E5);
|
||||
assert!(f.ui.message.is_none());
|
||||
|
||||
f.ui.tick_at(start + first + last, normal(), NOW);
|
||||
tick_with_prime(&mut f.ui, start + first + last, normal(), NOW);
|
||||
assert_eq!(f.ui.session.context_index, 2);
|
||||
assert!(f.ui.can_input());
|
||||
board_frame(f, &ctx, 10.0, &settings);
|
||||
|
|
@ -1697,6 +1733,100 @@ mod tests {
|
|||
assert_adaptive_board_slides(&mut slow, 1000, 1000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn next_target_primes_a_new_automatic_sequence_without_reverse_slide() {
|
||||
fn settle_to_input(f: &mut Fixture, at: Instant) {
|
||||
let mut at = at;
|
||||
for _ in 0..32 {
|
||||
if f.ui.can_input() {
|
||||
return;
|
||||
}
|
||||
let next = f.ui.playback_deadline().unwrap_or(at);
|
||||
tick_with_prime(&mut f.ui, next, normal(), NOW);
|
||||
at = next;
|
||||
}
|
||||
panic!("training did not reach independent input");
|
||||
}
|
||||
|
||||
let mut f = Fixture::new(
|
||||
"1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 *",
|
||||
LearningSide::Black,
|
||||
&["e7e5", "b8c6", "a7a6"],
|
||||
"next-target-prime",
|
||||
);
|
||||
f.ui.session.context_policy.use_fixed_piece_speed = false;
|
||||
f.ui.session.context_policy.move_speed_adjustment = 0.0;
|
||||
let start = Instant::now();
|
||||
settle_to_input(&mut f, start);
|
||||
assert_eq!(f.ui.session.current_expected_uci(), Some("e7e5"));
|
||||
answer_current(
|
||||
&mut f,
|
||||
start + Duration::from_secs(1),
|
||||
NOW,
|
||||
"first-target-e5",
|
||||
);
|
||||
|
||||
settle_to_input(&mut f, start + Duration::from_secs(1) + normal());
|
||||
assert_eq!(f.ui.session.current_expected_uci(), Some("b8c6"));
|
||||
answer_current(
|
||||
&mut f,
|
||||
start + Duration::from_secs(3),
|
||||
NOW + 1,
|
||||
"second-target-nc6",
|
||||
);
|
||||
|
||||
let prime_at = start + Duration::from_secs(3) + normal();
|
||||
f.ui.tick_at(prime_at, normal(), NOW);
|
||||
assert!(f.ui.pending_automatic.is_some());
|
||||
assert!(!f.ui.board_shown);
|
||||
let ctx = egui::Context::default();
|
||||
let settings = Settings::default();
|
||||
board_frame(&mut f, &ctx, 10.0, &settings);
|
||||
assert!(
|
||||
f.ui.board.animation_at(10.0).is_none(),
|
||||
"prime must not animate the previous target backwards"
|
||||
);
|
||||
|
||||
f.ui.tick_at(prime_at, normal(), NOW);
|
||||
let duration = automatic_duration(&f);
|
||||
assert_eq!(duration, Duration::from_millis(1000));
|
||||
board_frame(&mut f, &ctx, 10.01, &settings);
|
||||
assert_current_slide(&f, 10.01, duration, Square::E2, Square::E4);
|
||||
let (_, slides, _) = f.ui.board.animation_at(10.01).unwrap();
|
||||
assert!(
|
||||
slides
|
||||
.iter()
|
||||
.all(|(_, from, to)| !(*from == Square::F3 && *to == Square::G1)),
|
||||
"next target started with a reverse slide: {slides:?}"
|
||||
);
|
||||
assert!(matches!(
|
||||
f.ui.playback,
|
||||
Some(Playback::Automatic { total: 5, .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn debug_moves_settles_prime_between_targets() {
|
||||
let mut f = Fixture::new(
|
||||
"1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 *",
|
||||
LearningSide::Black,
|
||||
&["e7e5", "b8c6", "a7a6"],
|
||||
"debug-prime-between-targets",
|
||||
);
|
||||
f.ui.debug_moves("e7e5 settle b8c6 settle");
|
||||
assert!(f.ui.can_input());
|
||||
assert_eq!(f.ui.session.current_expected_uci(), Some("a7a6"));
|
||||
f.ui.debug_moves("a7a6 settle");
|
||||
assert!(f.ui.is_finished());
|
||||
assert_eq!(
|
||||
f.attempts()
|
||||
.iter()
|
||||
.filter(|attempt| attempt.event_type.is_independent())
|
||||
.count(),
|
||||
3
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reinforcement_does_not_count_as_completed_main_target() {
|
||||
let mut f = Fixture::new(
|
||||
|
|
@ -1707,7 +1837,7 @@ mod tests {
|
|||
);
|
||||
f.ui.session.context_policy.consider_leadup_moves = true;
|
||||
let start = Instant::now();
|
||||
f.ui.tick_at(start, Duration::ZERO, NOW);
|
||||
tick_with_prime(&mut f.ui, start, Duration::ZERO, NOW);
|
||||
assert_eq!(
|
||||
f.ui.session.phase,
|
||||
LearningSessionPhase::AwaitingContextIndependent
|
||||
|
|
@ -1734,25 +1864,25 @@ mod tests {
|
|||
"context-normal",
|
||||
);
|
||||
let start = Instant::now();
|
||||
f.ui.tick_at(start, normal(), NOW);
|
||||
tick_with_prime(&mut f.ui, start, normal(), NOW);
|
||||
assert_eq!(f.ui.visual_log, ["e2e4"]);
|
||||
assert_eq!(f.ui.session.context_index, 0);
|
||||
assert!(!f.ui.can_input());
|
||||
|
||||
f.ui.tick_at(start + Duration::from_millis(249), normal(), NOW);
|
||||
tick_with_prime(&mut f.ui, start + Duration::from_millis(249), normal(), NOW);
|
||||
assert_eq!(f.ui.session.context_index, 0);
|
||||
assert!(f.attempts().is_empty());
|
||||
|
||||
f.ui.tick_at(start + normal(), normal(), NOW);
|
||||
tick_with_prime(&mut f.ui, start + normal(), normal(), NOW);
|
||||
assert_eq!(f.ui.session.context_index, 1);
|
||||
assert_eq!(f.ui.visual_log, ["e2e4", "e7e5"]);
|
||||
f.ui.tick_at(start + normal(), normal(), NOW);
|
||||
tick_with_prime(&mut f.ui, start + normal(), normal(), NOW);
|
||||
assert_eq!(f.ui.session.context_index, 1);
|
||||
|
||||
f.ui.tick_at(start + normal() * 2, normal(), NOW);
|
||||
tick_with_prime(&mut f.ui, start + normal() * 2, normal(), NOW);
|
||||
assert_eq!(f.ui.session.context_index, 2);
|
||||
assert_eq!(f.ui.visual_log, ["e2e4", "e7e5", "g1f3"]);
|
||||
f.ui.tick_at(start + normal() * 3, normal(), NOW);
|
||||
tick_with_prime(&mut f.ui, start + normal() * 3, normal(), NOW);
|
||||
assert_eq!(f.ui.session.context_index, 3);
|
||||
assert_eq!(
|
||||
f.ui.session.phase,
|
||||
|
|
@ -1775,8 +1905,8 @@ mod tests {
|
|||
"pause-after-second",
|
||||
);
|
||||
let start = Instant::now();
|
||||
f.ui.tick_at(start, normal(), NOW);
|
||||
f.ui.tick_at(start + normal(), normal(), NOW);
|
||||
tick_with_prime(&mut f.ui, start, normal(), NOW);
|
||||
tick_with_prime(&mut f.ui, start + normal(), normal(), NOW);
|
||||
assert_eq!(f.ui.session.context_index, 1);
|
||||
assert_eq!(f.ui.visual_log, ["e2e4", "e7e5"]);
|
||||
|
||||
|
|
@ -1784,24 +1914,24 @@ mod tests {
|
|||
assert!(f.ui.pause_requested);
|
||||
assert!(matches!(f.ui.playback, Some(Playback::Automatic { .. })));
|
||||
assert_eq!(f.attempts().len(), 1);
|
||||
f.ui.tick_at(start + normal() * 2, normal(), NOW);
|
||||
tick_with_prime(&mut f.ui, start + normal() * 2, normal(), NOW);
|
||||
assert!(f.ui.autoplay_paused());
|
||||
assert_eq!(f.ui.session.context_index, 2);
|
||||
assert_eq!(f.ui.visual_log, ["e2e4", "e7e5"]);
|
||||
assert_eq!(f.attempts().len(), 2);
|
||||
assert!(!f.ui.can_input());
|
||||
|
||||
f.ui.tick_at(start + normal() * 10, normal(), NOW);
|
||||
tick_with_prime(&mut f.ui, start + normal() * 10, normal(), NOW);
|
||||
assert_eq!(f.ui.session.context_index, 2);
|
||||
assert_eq!(f.attempts().len(), 2);
|
||||
assert!(f.ui.continue_autoplay(start + normal() * 20));
|
||||
assert_eq!(f.ui.visual_log, ["e2e4", "e7e5", "g1f3"]);
|
||||
assert_eq!(f.ui.session.context_index, 2);
|
||||
assert_eq!(f.attempts().len(), 2);
|
||||
f.ui.tick_at(start + normal() * 20, normal(), NOW);
|
||||
tick_with_prime(&mut f.ui, start + normal() * 20, normal(), NOW);
|
||||
assert_eq!(f.attempts().len(), 2);
|
||||
|
||||
f.ui.tick_at(start + normal() * 21, normal(), NOW);
|
||||
tick_with_prime(&mut f.ui, start + normal() * 21, normal(), NOW);
|
||||
assert_eq!(f.ui.session.context_index, 3);
|
||||
assert_eq!(f.attempts().len(), 3);
|
||||
assert!(f.ui.can_input());
|
||||
|
|
@ -1817,7 +1947,7 @@ mod tests {
|
|||
"autoplay-keyboard-stop",
|
||||
);
|
||||
let start = Instant::now();
|
||||
f.ui.tick_at(start, normal(), NOW);
|
||||
tick_with_prime(&mut f.ui, start, normal(), NOW);
|
||||
let ctx = egui::Context::default();
|
||||
let press = |key: Key,
|
||||
training: &mut LearningTrainingUi,
|
||||
|
|
@ -1843,7 +1973,7 @@ mod tests {
|
|||
assert!(f.ui.pause_requested);
|
||||
assert!(actions.is_empty());
|
||||
|
||||
f.ui.tick_at(start + normal(), normal(), NOW);
|
||||
tick_with_prime(&mut f.ui, start + normal(), normal(), NOW);
|
||||
assert!(f.ui.autoplay_paused());
|
||||
assert_eq!(f.attempts().len(), 1);
|
||||
press(Key::Space, &mut f.ui, &mut actions);
|
||||
|
|
@ -1857,7 +1987,7 @@ mod tests {
|
|||
assert!(f.ui.playback.is_none());
|
||||
assert!(!f.ui.can_input());
|
||||
assert_eq!(f.ui.visual_log, ["e2e4", "e7e5"]);
|
||||
f.ui.tick_at(start + normal() * 20, normal(), NOW);
|
||||
tick_with_prime(&mut f.ui, start + normal() * 20, normal(), NOW);
|
||||
assert_eq!(f.attempts().len(), 1);
|
||||
let data = f.store.load().unwrap();
|
||||
assert_eq!(data.learning.attempts.len(), 1);
|
||||
|
|
@ -1877,7 +2007,7 @@ mod tests {
|
|||
&["b8c6"],
|
||||
"context-off",
|
||||
);
|
||||
f.ui.tick_at(Instant::now(), Duration::ZERO, NOW);
|
||||
tick_with_prime(&mut f.ui, Instant::now(), Duration::ZERO, NOW);
|
||||
assert_eq!(f.ui.visual_log, ["e2e4", "e7e5", "g1f3"]);
|
||||
assert_eq!(f.ui.session.context_index, 3);
|
||||
assert!(f.ui.can_input());
|
||||
|
|
@ -1905,7 +2035,7 @@ mod tests {
|
|||
"autoplay-input",
|
||||
);
|
||||
let start = Instant::now();
|
||||
f.ui.tick_at(start, normal(), NOW);
|
||||
tick_with_prime(&mut f.ui, start, normal(), NOW);
|
||||
assert!(!f.ui.play_uci_with_id_at(
|
||||
"e7e5",
|
||||
"blocked-input".to_owned(),
|
||||
|
|
@ -1921,7 +2051,7 @@ mod tests {
|
|||
fn wrong_answer_replays_without_a_second_independent_error() {
|
||||
let mut f = Fixture::new("1. e4 *", LearningSide::White, &["e2e4"], "wrong-replay");
|
||||
let start = Instant::now();
|
||||
f.ui.tick_at(start, normal(), NOW);
|
||||
tick_with_prime(&mut f.ui, start, normal(), NOW);
|
||||
assert!(f.ui.play_uci_with_id_at(
|
||||
"d2d4",
|
||||
"wrong-d4".to_owned(),
|
||||
|
|
@ -1929,7 +2059,8 @@ mod tests {
|
|||
NOW,
|
||||
));
|
||||
assert!(matches!(f.ui.playback, Some(Playback::Wrong { .. })));
|
||||
f.ui.tick_at(
|
||||
tick_with_prime(
|
||||
&mut f.ui,
|
||||
start + Duration::from_millis(1500) + WRONG_SHOWN,
|
||||
normal(),
|
||||
NOW,
|
||||
|
|
@ -1950,14 +2081,24 @@ mod tests {
|
|||
NOW,
|
||||
));
|
||||
assert_eq!(f.attempts().len(), 1);
|
||||
f.ui.tick_at(start + Duration::from_secs(3) + WRONG_SHOWN, normal(), NOW);
|
||||
tick_with_prime(
|
||||
&mut f.ui,
|
||||
start + Duration::from_secs(3) + WRONG_SHOWN,
|
||||
normal(),
|
||||
NOW,
|
||||
);
|
||||
assert!(f.ui.play_uci_with_id_at(
|
||||
"e2e4",
|
||||
"replay-e4".to_owned(),
|
||||
start + Duration::from_secs(4),
|
||||
NOW,
|
||||
));
|
||||
f.ui.tick_at(start + Duration::from_secs(4) + normal(), normal(), NOW);
|
||||
tick_with_prime(
|
||||
&mut f.ui,
|
||||
start + Duration::from_secs(4) + normal(),
|
||||
normal(),
|
||||
NOW,
|
||||
);
|
||||
assert!(f.ui.is_finished());
|
||||
let attempts = f.attempts();
|
||||
assert_eq!(attempts.len(), 2);
|
||||
|
|
@ -1984,7 +2125,7 @@ mod tests {
|
|||
fn preview_is_idempotent_and_shown_move_is_not_success() {
|
||||
let mut f = Fixture::new("1. e4 *", LearningSide::White, &["e2e4"], "preview");
|
||||
let start = Instant::now();
|
||||
f.ui.tick_at(start, normal(), NOW);
|
||||
tick_with_prime(&mut f.ui, start, normal(), NOW);
|
||||
assert!(f.ui.request_hint_with_id_at(
|
||||
"preview-e4".to_owned(),
|
||||
start + Duration::from_millis(100),
|
||||
|
|
@ -2003,7 +2144,12 @@ mod tests {
|
|||
start + Duration::from_secs(1),
|
||||
NOW,
|
||||
));
|
||||
f.ui.tick_at(start + Duration::from_secs(1) + normal(), normal(), NOW);
|
||||
tick_with_prime(
|
||||
&mut f.ui,
|
||||
start + Duration::from_secs(1) + normal(),
|
||||
normal(),
|
||||
NOW,
|
||||
);
|
||||
assert!(f.ui.is_finished());
|
||||
assert!(
|
||||
f.ui.message
|
||||
|
|
@ -2038,7 +2184,7 @@ mod tests {
|
|||
"duplicate",
|
||||
);
|
||||
let start = Instant::now();
|
||||
f.ui.tick_at(start, normal(), NOW);
|
||||
tick_with_prime(&mut f.ui, start, normal(), NOW);
|
||||
assert!(f.ui.advance_context_with_id_at(
|
||||
"duplicate-context".to_owned(),
|
||||
start + normal(),
|
||||
|
|
@ -2062,7 +2208,7 @@ mod tests {
|
|||
fn store_error_is_visible_blocking_and_retryable() {
|
||||
let mut f = Fixture::new("1. e4 *", LearningSide::White, &["e2e4"], "store-error");
|
||||
let start = Instant::now();
|
||||
f.ui.tick_at(start, normal(), NOW);
|
||||
tick_with_prime(&mut f.ui, start, normal(), NOW);
|
||||
let valid_store = f.ui.store.clone();
|
||||
f.ui.store = LearningStore::with_legacy(valid_store.path(), valid_store.path());
|
||||
assert!(f.ui.play_uci_with_id_at(
|
||||
|
|
@ -2087,7 +2233,12 @@ mod tests {
|
|||
f.ui.retry_pending(start + Duration::from_millis(300));
|
||||
assert!(!f.ui.has_unsaved());
|
||||
assert!(matches!(f.ui.playback, Some(Playback::Accepted { .. })));
|
||||
f.ui.tick_at(start + Duration::from_millis(300) + normal(), normal(), NOW);
|
||||
tick_with_prime(
|
||||
&mut f.ui,
|
||||
start + Duration::from_millis(300) + normal(),
|
||||
normal(),
|
||||
NOW,
|
||||
);
|
||||
assert!(f.ui.is_finished());
|
||||
assert_eq!(f.attempts().len(), 1);
|
||||
}
|
||||
|
|
@ -2096,7 +2247,7 @@ mod tests {
|
|||
fn reload_resumes_preview_and_partially_presented_context() {
|
||||
let mut preview = Fixture::new("1. e4 *", LearningSide::White, &["e2e4"], "resume-preview");
|
||||
let start = Instant::now();
|
||||
preview.ui.tick_at(start, normal(), NOW);
|
||||
tick_with_prime(&mut preview.ui, start, normal(), NOW);
|
||||
preview
|
||||
.ui
|
||||
.request_hint_with_id_at("resume-preview-event".to_owned(), start, NOW);
|
||||
|
|
@ -2120,8 +2271,8 @@ mod tests {
|
|||
&["b8c6"],
|
||||
"resume-context",
|
||||
);
|
||||
context.ui.tick_at(start, normal(), NOW);
|
||||
context.ui.tick_at(start + normal(), normal(), NOW);
|
||||
tick_with_prime(&mut context.ui, start, normal(), NOW);
|
||||
tick_with_prime(&mut context.ui, start + normal(), normal(), NOW);
|
||||
assert_eq!(context.ui.session.context_index, 1);
|
||||
let id = context.ui.session_id().to_owned();
|
||||
drop(context.ui);
|
||||
|
|
@ -2136,8 +2287,7 @@ mod tests {
|
|||
.unwrap();
|
||||
assert_eq!(resumed.session_id(), id);
|
||||
assert_eq!(resumed.session.context_index, 1);
|
||||
resumed.board_shown = true;
|
||||
resumed.tick_at(start + normal() * 2, Duration::ZERO, NOW);
|
||||
tick_with_prime(&mut resumed, start + normal() * 2, Duration::ZERO, NOW);
|
||||
assert_eq!(resumed.session.context_index, 3);
|
||||
assert_eq!(context.store.load().unwrap().learning.attempts.len(), 3);
|
||||
}
|
||||
|
|
@ -2171,7 +2321,7 @@ mod tests {
|
|||
true,
|
||||
);
|
||||
let start = Instant::now();
|
||||
f.ui.tick_at(start, Duration::ZERO, NOW);
|
||||
tick_with_prime(&mut f.ui, start, Duration::ZERO, NOW);
|
||||
assert!(f.ui.request_hint_with_id_at(
|
||||
"preview-before-new-introduction".to_owned(),
|
||||
start,
|
||||
|
|
@ -2217,7 +2367,7 @@ mod tests {
|
|||
LearningPriority::DepthFirst,
|
||||
);
|
||||
let start = Instant::now();
|
||||
f.ui.tick_at(start, Duration::ZERO, NOW);
|
||||
tick_with_prime(&mut f.ui, start, Duration::ZERO, NOW);
|
||||
answer_current(
|
||||
&mut f,
|
||||
start + Duration::from_millis(10),
|
||||
|
|
@ -2281,7 +2431,7 @@ mod tests {
|
|||
"g1f3"
|
||||
);
|
||||
let start = Instant::now();
|
||||
f.ui.tick_at(start, Duration::ZERO, NOW);
|
||||
tick_with_prime(&mut f.ui, start, Duration::ZERO, NOW);
|
||||
assert!(f.ui.can_input());
|
||||
assert!(f.ui.playback.is_none());
|
||||
assert!(f.ui.visual_log.is_empty());
|
||||
|
|
@ -2379,7 +2529,7 @@ mod tests {
|
|||
LearningPriority::MainLinesFirst,
|
||||
);
|
||||
let start = Instant::now();
|
||||
f.ui.tick_at(start, Duration::ZERO, NOW);
|
||||
tick_with_prime(&mut f.ui, start, Duration::ZERO, NOW);
|
||||
answer_current(&mut f, start, NOW, "priority-review-first");
|
||||
let review_id = f.ui.session_id().to_owned();
|
||||
assert_eq!(f.ui.session.current_index, 1);
|
||||
|
|
|
|||
|
|
@ -947,6 +947,10 @@ impl RepertoireUi {
|
|||
pub fn show(&mut self, ui: &mut Ui, settings: &mut Settings) -> Vec<RepertoireAction> {
|
||||
self.poll(settings);
|
||||
let mut actions = Vec::new();
|
||||
let available = ui.available_rect_before_wrap();
|
||||
let background = ui.visuals().window_fill();
|
||||
ui.painter_at(available)
|
||||
.rect_filled(available, 0.0, background);
|
||||
#[cfg(test)]
|
||||
{
|
||||
self.debug_layout.editor = None;
|
||||
|
|
|
|||
|
|
@ -348,6 +348,55 @@ fn dashboard_uses_the_full_workspace_at_both_window_sizes() {
|
|||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn early_paths_paint_opaque_window_background_without_allocating() {
|
||||
for visuals in [egui::Visuals::light(), egui::Visuals::dark()] {
|
||||
for (width, height) in [(1400.0, 900.0), (960.0, 600.0), (640.0, 480.0)] {
|
||||
for editor in [false, true] {
|
||||
let mut f = Fixture::new();
|
||||
if editor {
|
||||
f.ui.open_editor();
|
||||
} else {
|
||||
f.ui.open_dashboard();
|
||||
}
|
||||
let ctx = egui::Context::default();
|
||||
ctx.set_visuals(visuals.clone());
|
||||
let mut available = None;
|
||||
let mut content = None;
|
||||
let output = ctx.run_ui(
|
||||
egui::RawInput {
|
||||
screen_rect: Some(egui::Rect::from_min_size(
|
||||
egui::Pos2::ZERO,
|
||||
egui::vec2(width, height),
|
||||
)),
|
||||
..Default::default()
|
||||
},
|
||||
|ui| {
|
||||
egui::CentralPanel::default().show(ui, |ui| {
|
||||
available = Some(ui.available_rect_before_wrap());
|
||||
let actions = f.ui.show(ui, &mut f.settings);
|
||||
assert!(actions.is_empty());
|
||||
content = Some(ui.min_rect());
|
||||
});
|
||||
},
|
||||
);
|
||||
let shapes = output.shapes.clone();
|
||||
output.drop_without_applying_deltas();
|
||||
let available = available.unwrap();
|
||||
assert_rect_inside(available, content.unwrap());
|
||||
assert!(shapes.iter().any(|clipped| {
|
||||
matches!(&clipped.shape, egui::Shape::Rect(shape) if shape.rect == available && shape.fill == visuals.window_fill() && shape.fill.a() == 255)
|
||||
}));
|
||||
if editor {
|
||||
assert!(f.ui.debug_layout.editor.is_some());
|
||||
} else {
|
||||
f.ui.dashboard.as_mut().unwrap().wait_until_idle_for_test();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn creating_an_empty_repertoire_selects_it_in_the_workspace() {
|
||||
let mut f = Fixture::new();
|
||||
|
|
|
|||
|
|
@ -211,6 +211,31 @@ pub fn learning_invariant_violations(summary: &LearningAggregate) -> Vec<&'stati
|
|||
violations
|
||||
}
|
||||
|
||||
pub fn global_total_invariant_violation(
|
||||
global_total: usize,
|
||||
repertoire_totals: impl IntoIterator<Item = usize>,
|
||||
) -> Option<&'static str> {
|
||||
let mut repertoire_total = 0usize;
|
||||
for total in repertoire_totals {
|
||||
let Some(next) = repertoire_total.checked_add(total) else {
|
||||
return Some("repertoire_totals sum overflow");
|
||||
};
|
||||
repertoire_total = next;
|
||||
}
|
||||
(global_total > repertoire_total).then_some("global_total > sum(repertoire_totals)")
|
||||
}
|
||||
|
||||
pub fn log_global_total_invariant(
|
||||
global_total: usize,
|
||||
repertoire_totals: impl IntoIterator<Item = usize>,
|
||||
) {
|
||||
if let Some(violation) = global_total_invariant_violation(global_total, repertoire_totals) {
|
||||
eprintln!(
|
||||
"training: global total invariant violation: {violation}; global_total={global_total}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn is_valid_percentage(value: f64) -> bool {
|
||||
value.is_finite() && (0.0..=100.0).contains(&value)
|
||||
}
|
||||
|
|
@ -343,6 +368,36 @@ mod tests {
|
|||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn global_total_invariant_allows_deduplicated_union() {
|
||||
assert_eq!(global_total_invariant_violation(3, [2, 2]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn global_total_invariant_detects_global_above_repertoire_sum() {
|
||||
assert_eq!(
|
||||
global_total_invariant_violation(5, [2, 2]),
|
||||
Some("global_total > sum(repertoire_totals)")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn global_total_invariant_detects_repertoire_sum_overflow() {
|
||||
assert_eq!(
|
||||
global_total_invariant_violation(0, [usize::MAX, 1]),
|
||||
Some("repertoire_totals sum overflow")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn global_total_invariant_handles_empty_repertoires() {
|
||||
assert_eq!(global_total_invariant_violation(0, []), None);
|
||||
assert_eq!(
|
||||
global_total_invariant_violation(1, []),
|
||||
Some("global_total > sum(repertoire_totals)")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aggregate_output_is_unchanged() {
|
||||
fn item(
|
||||
|
|
|
|||
|
|
@ -18,7 +18,10 @@ mod stats;
|
|||
mod store;
|
||||
mod tree;
|
||||
|
||||
pub use aggregate::{LearningAggregate, RepertoireStatus, aggregate, is_uncertain};
|
||||
pub use aggregate::{
|
||||
LearningAggregate, RepertoireStatus, aggregate, global_total_invariant_violation, is_uncertain,
|
||||
log_global_total_invariant,
|
||||
};
|
||||
pub use branch_analytics::{BranchLearningAnalytics, branch_learning_analytics};
|
||||
pub use learning::{
|
||||
AttemptApplication, IndependentOutcome, IndependentResult, LOCAL_PROFILE_ID, LearningData,
|
||||
|
|
|
|||
|
|
@ -345,4 +345,14 @@
|
|||
- **Context policy.** Шесть параметров контекста/скорости сохраняются отдельно для каждого репертуара в Settings. Сессия получает snapshot политики при создании; изменение настроек не переписывает уже начатую сессию. Дополнительные параметры находятся в collapsed-блоке, доска не перегружается.
|
||||
- **Dashboard.** Details открывает текущие репертуар и сторону, Global выбирается явно. Вместо непонятного `T` используется Total; видно `Learnt = Confident + Uncertain`, знаменатель процентов — Total. Графики разделены по вкладкам History/Scheduled/Sequences, точные значения остаются в таблицах. Снимок текущей статистики сохраняется автоматически при первом просмотре scope в локальный день и доступен вручную; дубли date/scope запрещены, PGN и знание ходов снимок не меняет.
|
||||
- **Depth и линии.** `max_plies` из редактора ограничивает тренировочный scope и его CTA/KPI; полная история dashboard сохраняет полный scope. Статистика конкретной линии допускает пересечения с другими линиями; ветка объединяет свои транспозиции, а весь репертуар/Global — только уникальные LearningItemKey. Среднее арифметическое процентов линий не используется.
|
||||
- **Визуальная матрица.** По решению владельца 2026-11-04 минимальный размер визуальной приёмки — **960×600**, основной — **1400×900**. Размер 640×480 и микро-контейнеры не определяют дизайн и не используются для визуального вердикта; прежние кадры остаются только историческими QA-артефактами.
|
||||
- **Проверка.** AT-01…30 являются обязательными поэтапными критериями, а не формальным списком. До соответствующей реализации не объявлять их выполненными. Production агрегаты проверяют математические инварианты и сообщают нарушения в лог. После UI — отдельный design reviewer с реальными снимками и переходами, согласно `AGENTS.md`.
|
||||
|
||||
## Android: открытие PGN из буфера обмена (2026-11-04)
|
||||
|
||||
Владелец уточнил сценарий задачи 35. При холодном запуске и возврате в приложение оно проверяет текст буфера на PGN, но импортирует только после подтверждения пользователя. При нескольких партиях всегда открывается первая; остальные остаются доступны в локальной копии базы. Диалог использует существующий Material 3 стиль, без нового отдельного экрана-мастера.
|
||||
|
||||
- Текст проверяется существующим PGN-reader на фоновом потоке; некорректный или пустой текст не вызывает предложение. Сетевых вызовов и передачи содержимого наружу нет.
|
||||
- Импорт использует `Library.addCopy`: локальная копия сохраняет полное PGN-дерево, комментарии и анализ. Навигация открывает `GameAt(id, 0)`, независимо от числа записей; поведение обычных файлов `Incoming.Opened` не меняется.
|
||||
- Один и тот же SHA-256 текста не предлагается повторно после открытия или отказа, в том числе при повороте и холодном перезапуске. Сам текст в настройки не записывается; обработанный hash сохраняется локально. Состояние нерешённого вопроса сохраняется в Application, асинхронный результат устаревшего текста отбрасывается.
|
||||
- Диалог не перекрывает `UpdateSheet`, `Incoming.Opening` или `Incoming.Failed`; после подтверждения используется существующий прогресс и обработка ошибок. Если блокировщик появляется поверх нерешённого предложения, оно скрывается без отказа, а после закрытия выполняется свежая проверка.
|
||||
|
|
|
|||
|
|
@ -209,6 +209,7 @@
|
|||
|
||||
- Сноска внизу — единственное место, где объясняется запрет Android. Системный выбор папки сам пишет «Can't use this folder» по-английски и предлагает создать папку; наша строка заранее говорит, что делать.
|
||||
- **«Вставить PGN из буфера»** (§4.5) — первая строка, значок `content_paste`. Она есть, только если в буфере текст. Проверяется лишь описание буфера (`primaryClipDescription`, тип `text/*`): чтение самого текста Android объявляет всплывающим сообщением, поэтому текст читается только по нажатию.
|
||||
- Отдельный автоматический сценарий из уточнения владельца (§4.5) проверяет текст при запуске/возврате в foreground один раз до решения пользователя; он не меняет этот ручной путь и не создаёт постоянного слушателя буфера.
|
||||
- Строка первой, потому что она контекстная: человек только что скопировал партию в другом приложении и пришёл её вставить. «Файл» и «Папка» сдвигаются на 72 dp, но на них не нажимают вслепую — лист читают глазами.
|
||||
- Подсказка до двух строк — допустимо; на 360 dp по-русски она помещается в одну-две строки, по-немецки «In einer anderen App kopierte Partien» — в одну.
|
||||
|
||||
|
|
@ -295,6 +296,18 @@
|
|||
- Нет партий (пустой текст, обычный текст, текст без тегов и ходов) — лист закрыт, снекбар «В буфере нет партий в формате PGN». В список ничего не добавляется.
|
||||
- Тот же текст второй раз открывает уже сохранённую копию (§4.4).
|
||||
|
||||
#### Автоматическое предложение при запуске и возврате
|
||||
|
||||
Уточнение владельца: приложение само проверяет буфер при холодном запуске и возврате в `RESUMED`, но только предлагает открыть его. Это не заменяет ручную строку «Вставить PGN из буфера»: ручной путь остаётся доступен для уже отклонённого текста.
|
||||
|
||||
- Текст разбирается локально на фоновом потоке тем же PGN-reader. Предложение появляется только если первая запись содержит теги или ходы; пустой, обычный и повреждённый текст не вызывает диалог или снекбар. Снимок больше 8 MiB игнорируется, чтобы не блокировать интерфейс и не расходовать память.
|
||||
- Обычный Material 3 `AlertDialog`: заголовок `Партия/Партии в буфере обмена`, короткое пояснение и текстовые кнопки «Открыть»/«Отмена». При нескольких используется локализованное число и явно сказано, что откроется первая. «Назад» и нажатие мимо означают отказ. Залитых кнопок, иконки и нового отдельного экрана нет.
|
||||
- До выбора копии и записи в библиотеку нет. После «Открыть» вызывается `Library.addCopy`, затем стек `Databases → Games(id) → GameAt(id, 0)`: всегда открывается первая запись. `shown` и `lastOpened` этой копии сбрасываются, чтобы старый поиск не изменил выбор. Остальные записи доступны обычными стрелками и в списке после Back.
|
||||
- После успешного открытия или отказа SHA-256 сохраняется в приватных настройках и после холодного перезапуска; сам PGN в настройки не пишется. Нажатие «Открыть» само по себе решённым не считается: digest появляется в настройках только после фактически сохранённой записи, поэтому ошибка записи допускает повторную попытку. Открытый или отклонённый текст повторно не предлагается, новый текст получает новое предложение. Нерешённый offer живёт в Application и переживает поворот без повторного разбора и дублирования.
|
||||
- Пустой или новый буфер инвалидирует предыдущее поколение. Устаревший accept и устаревший импорт не публикуются. Проверка последнего запроса и публикация атомарны; URI и clipboard используют общий порядок последнего запроса и `compareAndSet` при потреблении события, чтобы старый collector не стёр новое.
|
||||
- `UpdateSheet`, `Incoming.Opening` и `Incoming.Failed` имеют приоритет: clipboard-диалог их не перекрывает. Нерешённый вопрос скрывается без отказа, после закрытия блокировщика выполняется свежая проверка.
|
||||
- Чтение только в foreground, без постоянного listener и сетевых вызовов. Необработанный текст не пишется в логи, Bundle и настройки; после отказа остаётся только SHA-256.
|
||||
|
||||
### 4.6. «Открыть с помощью» и «Поделиться»
|
||||
|
||||
- Приложение принимает `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).
|
||||
|
|
|
|||
|
|
@ -966,14 +966,14 @@ KPI — один спокойный блок в выбранной карточ
|
|||
- Доска остаётся центральной; библиотека под активным заданием не показывается. Текстовая нотация не возвращается. Название, scope, прогресс сессии и фиксированная панель состояния остаются на месте.
|
||||
- Неверный легальный ход записывается один раз. После возврата позиции ожидаемый ход показывается стрелкой; повтор продолжает линию как `REPLAY_AFTER_ERROR` и не называется самостоятельным успехом. Повторные ошибки в этой фазе не создают новых независимых попыток.
|
||||
- `PREVIEWED` виден до воспроизведения: серия и Accuracy не растут, требуется поздняя проверка без подсказки. Автоматический context записывает только служебное событие `AUTO_CONTEXT`, не создаёт независимых попыток и не меняет SRS. Если контекстный ход сам проверяется как reinforcement, он имеет явное состояние и записывается один раз.
|
||||
- Автоматические ходы показываются последовательно `position_before → position_after`. При фиксированной скорости каждый занимает `settings.animation.seconds()`: Off=0, Fast=0,12, Normal=0,25, Slow=0,5 с. При адаптивной скорости фактический slide и scheduler используют одну длительность `base / speed_factor` текущего шага, включая последний; переход before→after начинается в начале этого интервала. Два–три ответа/контекстных хода не телепортируются за один кадр. Во время autoplay ввод заблокирован, Pause/Stop доступны; Off разрешает мгновенный переход.
|
||||
- Автоматические ходы показываются последовательно `position_before → position_after`. Каждая новая автоматическая серия начинается со статичного prime-кадра из `from` первого шага: он не анимирует предыдущую позицию и не создаёт обратный slide; только следующий кадр запускает scheduler. При фиксированной скорости каждый шаг занимает `settings.animation.seconds()`: Off=0, Fast=0,12, Normal=0,25, Slow=0,5 с. При адаптивной скорости фактический slide и scheduler используют одну длительность `base / speed_factor` текущего шага, включая последний; переход before→after начинается в начале этого интервала. Два–три ответа/контекстных хода не телепортируются за один кадр. Во время autoplay ввод заблокирован, Pause/Stop доступны; Off разрешает мгновенный переход.
|
||||
- До готовности board ввод невозможен. Результат появляется после завершения последнего визуального шага, а не только после изменения session. Сохранение ошибок блокирует переход как раньше.
|
||||
|
||||
### 23.3. Компоновка и приёмка
|
||||
|
||||
- Wide: доска слева, справа название/scope, сторона/режим, CTA, единый KPI, библиотека. Узкое окно не прячет primary action и не создаёт горизонтальную прокрутку.
|
||||
- Высоты карточек и строк не зависят от появления индекса, статистики, ошибки или длины сообщения. Переходы Wrong→Reveal→Replay→Opponent→Next не двигают доску.
|
||||
- Обязательные снимки 1400×900 и 640×480: empty/new/mixed KPI, Due=0, все Learnt, три режима, wrong/replay, preview, autoplay 1/3→3/3, Pause/Continue, shared reset, save error, Continue/New session. Дополнительно серия кадров доказывает длительность анимации, один статический снимок её не доказывает.
|
||||
- Обязательные снимки 1400×900 (основной размер) и 960×600 (минимальный для визуальной приёмки): empty/new/mixed KPI, Due=0, все Learnt, три режима, wrong/replay, preview, autoplay 1/3→3/3, Pause/Continue, shared reset, save error, Continue/New session. Дополнительно серия кадров доказывает длительность анимации, один статический снимок её не доказывает. Размер 640×480 остаётся только в исторических технических тестах и не определяет дизайн.
|
||||
- Независимый design reviewer сравнивает main/game и рабочую область, а оркестратор проверяет core AT-01…30 отдельно от визуальной приёмки.
|
||||
|
||||
### 23.4. Details, сравнение веток и настройки контекста
|
||||
|
|
@ -985,4 +985,4 @@ KPI — один спокойный блок в выбранной карточ
|
|||
- History содержит линии Learning/Learnt/Uncertain по фактическим ежедневным снимкам; Uncertain — независимая линия-подмножество, не stack. Scheduled — шесть непересекающихся корзин; Sequences — три гистограммы, включая ноль. Точные таблицы остаются под графиками. Один snapshot — видимая точка; отсутствующие данные не синтезируются.
|
||||
- Действие называется `Save statistics to History`, а не «снимок» без контекста. Первый просмотр scope в локальный день сохраняет снимок автоматически, повторное ручное сохранение того же date/scope идемпотентно. PGN и LearningItem не меняются. Фоновое обновление после записи не заменяет уже видимую таблицу коротким loading-body.
|
||||
- Тренировочный KPI и CTA учитывают `max_plies`; полная History остаётся полной по настройке scope. Сравнение веток и линий использует все PGN-пути: общий LearningItem присутствует в каждой подходящей линии, дедуплицируется внутри ветки и не суммируется повторно в Global.
|
||||
- Независимый reviewer проверяет collapsed/expanded, первый вход→loading→loaded→Details→Close, 1400×900 и 640×480, RU/EN/DE и dark/light. Отдельно фиксирует читаемость всех заголовков, отсутствие скачков после Save statistics to History и доступность выбранной строки библиотеки.
|
||||
- Независимый reviewer проверяет collapsed/expanded, первый вход→loading→loaded→Details→Close, 1400×900 и 960×600, RU/EN/DE и dark/light. Отдельно фиксирует читаемость всех заголовков, отсутствие скачков после Save statistics to History и доступность выбранной строки библиотеки. Микро-окна не используются для визуального вердикта.
|
||||
|
|
|
|||
|
|
@ -223,9 +223,10 @@
|
|||
- **С чего начать:** уточнить по документации/релизам ChessBase, с какого выпуска и какие форматы или версии `.cbh`/`.cbv` отличаются; проверить текущий импортёр (`crates/chess-import`) на легальных контрольных файлах разных поколений; зафиксировать поддерживаемые версии, ограничения и варианты реализации. Исходные файлы использовать только для чтения.
|
||||
|
||||
### 35. Android: вставка PGN из буфера обмена для просмотра и анализа (2026-11-03)
|
||||
- **Статус:** новая; исследовать платформенные ограничения и сценарий.
|
||||
- **Статус:** в работе (2026-11-04): владелец уточнил запуск и возврат в приложение, подтверждение открытия и всегда первую партию при нескольких.
|
||||
- **Добавлено:** 2026-11-03.
|
||||
- **Суть (владелец):** при запуске мобильного приложения проверять, содержит ли буфер обмена PGN; дать возможность вставить его в ChessPenguin, открыть партию и затем анализировать её.
|
||||
- **Уточнение (2026-11-04):** проверка при запуске и разворачивании; предложение открыть партию на доске в существующем диалоговом стиле. При нескольких партиях открывается первая. Импорт только после подтверждения; один и тот же текст не предлагается повторно после открытия или отказа.
|
||||
- **С чего начать:** изучить ограничения Android на чтение буфера при запуске/возврате приложения; продумать понятное предложение «Открыть PGN из буфера» без автоматического импорта или изменения файлов; проверить текст PGN и цепочки ходов, несколько партий, некорректный текст, приватность и доступность действия после запуска; найти подходящее место в мобильном интерфейсе и связать с существующими просмотром/анализом партии.
|
||||
|
||||
### 36. Строить дебютный репертуар из партий большой базы (2026-11-03)
|
||||
|
|
@ -236,7 +237,7 @@
|
|||
- **С чего начать:** проверить поиск и выборку партий из существующей базы по позиции/префиксу; уточнить отбор (все партии или только топовых игроков/партий, минимум партий на продолжение, популярность/период), смысл глубины «до 15-го хода» для обеих сторон, контроль взрыва редких веток и повторных позиций; предусмотреть просмотр статистики ходов и источников перед добавлением. Добавление должно менять только репертуар, не исходную базу; повторный сбор — слияние/обновление вариантов без потери аннотаций и статистики тренировки.
|
||||
|
||||
### 37. Реализовать тренажёр дебютов по ТЗ ChessTempo (2026-11-04)
|
||||
- **Статус:** desktop MVP и F1 **приняты независимым reviewer**; core F2 (analytics + reinforcement) также принят. Независимая повторная проверка подтвердила Continue частичной сессии, стартовую позицию automatic context, счётчик задач и отсутствие дублирования статуса. Adaptive slide синхронизирован с scheduler через реальный `Anim`; требуется повторная независимая приёмка. Dashboard, графики, Branches/Lines и пользовательские context-политики интегрированы. Выявленные AT-аудитом пробелы `max_plies` и line-scope закрыты; до завершения V1 остаются визуальная приёмка и живые AT-сценарии.
|
||||
- **Статус:** **сделано (2026-11-04): V1 принят независимыми core, tester и design reviewers; выпуск не назначен.** Независимая повторная проверка подтвердила Continue частичной сессии, стартовую позицию automatic context, счётчик задач и отсутствие дублирования статуса. Adaptive slide и prime каждой автоматической серии синхронизированы с scheduler через реальный `Anim` и **приняты независимым tester**. Dashboard, графики, Branches/Lines и пользовательские context-политики интегрированы. Выявленные AT-аудитом пробелы `max_plies` и line-scope закрыты. Фон, Branches, Summary и RU/DE-локализация исправлены и приняты на 960×600 и 1400×900. Полный workspace: **201 desktop + 184 trainer tests**, Clippy и wasm check зелёные. Локальный checkpoint — `d1733b4`, последующие исправления остаются рабочими изменениями до отдельного коммита.
|
||||
- **Источник и приоритет:** `docs/chesstempo_opening_trainer_TZ.md`. Владелец подтвердил приоритет ТЗ над прежними упрощениями задачи 24 и своими импровизированными правилами случайного старта.
|
||||
- **Решение:** `docs/decisions.md`, «Тренажёр по ТЗ ChessTempo: новая модель обучения». Общий LearningItem по `(profile, FEN4, expected UCI)`, типизированные попытки, независимая Accuracy, streak 3, SRS, union-статистика, shared reset, идемпотентность и миграция v3. Текущий workspace, PGN, FEN4 и визуальная система сохраняются.
|
||||
- **Этапы:** (A) LearningItem/SRS/aggregates и AT-ядро; (B) граф/one-answer/scope; (C) хранилище и идемпотентность; (D) строгая session; (E) desktop MVP; (F) режимы, контекст, Uncertain/Resistant, истории и dashboards V1.
|
||||
|
|
|
|||
77
docs/qa/android-clipboard.md
Normal file
77
docs/qa/android-clipboard.md
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
# Android: открытие PGN из буфера обмена
|
||||
|
||||
Статус: **ACCEPTED** независимыми architecture и visual reviewers. Ветка —
|
||||
`feature/android-clipboard-pgn` от `main`. Релиз, теги и публикация не выполнялись.
|
||||
|
||||
## Поведение
|
||||
|
||||
При холодном запуске и возврате в `RESUMED` приложение проверяет текстовый буфер на PGN,
|
||||
но копию не создаёт до подтверждения. Первая запись должна содержать теги или ходы.
|
||||
Обычный, пустой или повреждённый текст и снимок больше 8 MiB игнорируются без диалога.
|
||||
|
||||
Обычный Material 3 `AlertDialog` предлагает сохранить PGN и открыть его на доске.
|
||||
При нескольких записях показывается локализованное число и всегда открывается первая.
|
||||
Остальные доступны в списке после Back. `shown` и `lastOpened` сбрасываются, поэтому
|
||||
старый поиск не меняет выбор первой записи. Обычный `Incoming.Opened` не изменён.
|
||||
|
||||
После успешного открытия или отказа SHA-256 сохраняется в приватных настройках и после
|
||||
холодного перезапуска. Нажатие Open само по себе решением не считается: digest появляется
|
||||
только после успешного `addCopy`, поэтому ошибка записи допускает retry. Нерешённый вопрос
|
||||
сохраняется в Application при configuration change. Сам PGN не попадает в настройки, Bundle
|
||||
или логи; сети нет.
|
||||
|
||||
Последний запрос и его публикация атомарны через общий lock. Устаревший snapshot, accept,
|
||||
импорт и dismiss не перезаписывают новое состояние. `Incoming.Failed` тоже использует CAS.
|
||||
`UpdateSheet`, `Incoming.Opening` и `Incoming.Failed` не перекрываются clipboard-диалогом.
|
||||
|
||||
## Автоматические проверки
|
||||
|
||||
- `./gradlew :app:testLightDebugUnitTest` — **21 test, 0 failures**: дедупликация digest,
|
||||
blank invalidation, stale accept/publication, холодный retry, успешное сохранение digest,
|
||||
первая запись valid/malformed/tag-only, фильтр существующей копии, последний запрос,
|
||||
CAS dismiss, размер и Unicode/CRLF/BOM.
|
||||
- `./gradlew :app:assembleLightDebug :app:lintLightDebug` — успешно.
|
||||
- `cargo test -p mobile-api --locked` — **25 passed, 2 ignored**.
|
||||
- `git diff --check` — успешно.
|
||||
- Отдельная сборка после переноса ветки от `main` — успешно.
|
||||
|
||||
APK: `androidApp/app/build/outputs/apk/light/debug/app-light-debug.apk`.
|
||||
|
||||
## Реальный Android-экран
|
||||
|
||||
`cp-phone` запускался с `-no-snapshot -no-snapshot-save -read-only`, затем остановлен.
|
||||
Проверены и просмотрены кадры в `target/qa-android-clipboard/`:
|
||||
|
||||
- одиночная PGN: до Open копии нет, после — Alice/Bob, `1 of 1`, дерево и варианты;
|
||||
- несколько записей: диалог с числом, открывается именно первая `1 of 2`;
|
||||
- Back после multiple: видны обе записи;
|
||||
- Cancel и Open после холодного перезапуска: повторного предложения нет;
|
||||
- существующая копия после пустого поиска: снова первая, число файлов 13 → 13;
|
||||
- первая malformed + вторая valid: предложения нет;
|
||||
- tag-only: предложение есть;
|
||||
- valid → blank: старое предложение исчезает, библиотека не меняется;
|
||||
- landscape configuration change: один диалог с тем же содержимым, без дублей и обрезок.
|
||||
|
||||
Ключевые доказательства: `02-single-offer.png`, `03-single-opened.png`,
|
||||
`04-multiple-offer.png`, `06-cancel-cold-reopen.png`, `07-multiple-first.png`,
|
||||
`08-multiple-list.png`, `10-filter-existing-first.png`, `14-blank-invalidation.png`,
|
||||
`16-rotation-config-change.png`, `17-atomic-opened.png`.
|
||||
|
||||
Визуальный reviewer подтвердил Material 3, scrim, контраст, TextButton, plural, открытие
|
||||
первой записи, список после Back, отсутствие повторов, blank и landscape. Системные
|
||||
clipboard-preview/toast Android не перекрывают кнопки диалога.
|
||||
|
||||
Architecture reviewer подтвердил атомарность публикации, отсутствие deadlock по порядку
|
||||
`LatestIncoming.lock → ClipboardPromptGate`, digest только после успешной записи, retry и
|
||||
CAS dismiss. IO выполняется вне request lock.
|
||||
|
||||
## Не проверено / ограничения
|
||||
|
||||
- Полная матрица всех девяти языков; ресурсы проходят сборку и lint.
|
||||
- TalkBack и физический поворот устройства. Проверено реальное landscape-изменение
|
||||
конфигурации через `cmd window size 2400x1080`.
|
||||
- Одновременная ручная и автоматическая вставка на устройстве; final-lock digest-логика и
|
||||
JVM-тест покрывают этот случай.
|
||||
- Реальная ошибка записи на устройстве; failed-import/cold-retry проверен JVM-тестом.
|
||||
- Размер выше 8 MiB на устройстве через Binder; граница проверена JVM-тестом.
|
||||
- Многопоточный stress-test; публикация проверена детерминированными тестами и lock-моделью.
|
||||
|
|
@ -221,3 +221,97 @@ Review in Order/Least Recent, четыре Learning priority, reinforcement и U
|
|||
реализованы. Dashboard подключён к рабочему дереву, но его новые экраны, графики, сравнение
|
||||
веток и редактор ещё не прошли отдельную визуальную приёмку. AT-аудит дополнительно выявил
|
||||
неподключённый `max_plies` и отсутствие отдельной line-scope модели для AT-30.
|
||||
|
||||
## Checkpoint d1733b4, 2026-11-04
|
||||
|
||||
Локальный коммит `d1733b4 feat: implement ChessTempo opening learning trainer` включает
|
||||
реализацию dashboard, графиков, Branches/Lines, context-политик, `max_plies`, ежедневных
|
||||
снимков и синхронизации adaptive slide. Прежние пробелы AT-17 и AT-30 закрыты на уровне кода
|
||||
и автоматических проверок. Проверка выбора Branches выявила и исправила перехват клика
|
||||
selectable labels; широкая/узкая компоновка и клик покрыты egui-тестами.
|
||||
|
||||
Перед коммитом: **194 desktop + 180 trainer tests**, Clippy обоих пакетов и `git diff --check` —
|
||||
зелёные. После коммита `cargo test --workspace --locked --quiet`, полный workspace Clippy и
|
||||
`cargo check -p chesspenguin-web --target wasm32-unknown-unknown --locked` также успешны,
|
||||
включая `mobile-api`. Игнорируемые corpus/real-engine тесты не считаются выполненными.
|
||||
|
||||
Это checkpoint реализации, а не итоговая приёмка V1: независимая adaptive и визуальная
|
||||
приёмки продолжаются, живые AT-сценарии ещё должны быть задокументированы.
|
||||
|
||||
Повторный независимый AT-аудит принял AT-17 (depth/full dashboard/resume), AT-30 на уровне
|
||||
core (фактические PGN-линии, branch/global dedup, `line_learnt`/`line_fresh`) и структурную
|
||||
интеграцию Branches/Charts. Source-line статистика не описывает дополнительные гибридные
|
||||
`training_paths`; канонические тренировочные сессии не изменены. Отдельного desktop-представления
|
||||
именно Lines нет: dashboard показывает Summary/Branches/History/Scheduled/Sequences/Moves.
|
||||
Аудит потребовал дополнительно вынести `GlobalTotal <= sum(T per repertoire)` из тестовой
|
||||
проверки в production-логирование. После реализации `global_total_invariant_violation` и его
|
||||
вызова в `DashboardData::build` тот же независимый reviewer закрыл замечание: **ACCEPTED**.
|
||||
Проверяются переполнение суммы и empty build, union и возвращаемые данные не изменены.
|
||||
|
||||
Финальный после этого изменения workspace-прогон: **195 desktop + 184 trainer tests**, остальные
|
||||
пакеты и Clippy зелёные, WebAssembly check успешен. Текущее дерево содержит это исправление поверх
|
||||
checkpoint d1733b4; новый коммит отдельно не запрашивался и не создавался.
|
||||
|
||||
### Повторная adaptive-приёмка
|
||||
|
||||
Независимый tester подтвердил functional regression fast **83/166 мс**, slow **1000/1000 мс**,
|
||||
from/to и отсутствие settings-slide после последнего deadline. X11-серия внутри одной серии
|
||||
подтвердила промежуточные e2→e4 и g1→f3, custom policy в Settings/session JSON, Pause/Off/resume
|
||||
и единственный automatic progress. Эти части приняты.
|
||||
|
||||
Общий вердикт пока **NOT ACCEPTED** из-за следующего boundary-case: после обычного ответа на
|
||||
следующий target `board_shown` остаётся true, prime больше не выполняется, и первый automatic step
|
||||
строит переход из предыдущей позиции вместо своего `from`. На снимке
|
||||
`target/qa-reinforcement-final-agent59/10-normal-next-target-small.png` виден обратный ход коня
|
||||
f3→g1; JSON в этот момент содержит `context_index=0` и `ADVANCING_CONTEXT`. Нужен отдельный
|
||||
prime без анимации для каждой новой автоматической последовательности и regression двух обычных
|
||||
targets подряд.
|
||||
|
||||
Исправление реализовано: `prepare_presentation` берёт `steps.front().from`, создаёт отдельный
|
||||
prime для каждой серии с `animation=0`, а запуск pending происходит только после реального
|
||||
`board_ui`. Добавлены `next_target_primes_a_new_automatic_sequence_without_reverse_slide` и
|
||||
`debug_moves_settles_prime_between_targets`. Независимый tester проверил семь точечных regressions
|
||||
и новые кадры `target/qa-next-target-prime-main/`: e2→e4 идёт внутри scheduler-интервала, обратного
|
||||
f3→g1 нет, JSON меняет `context_index` согласованно. **Вердикт — ACCEPTED.**
|
||||
|
||||
После prime-исправления полный workspace: **197 desktop + 184 trainer tests**, Clippy и
|
||||
WebAssembly check зелёные. Отдельная визуальная приёмка dashboard/редактора продолжается.
|
||||
|
||||
### Первая визуальная приёмка V1
|
||||
|
||||
Независимый design reviewer запустил приложение и просмотрел 55 hook-кадров и 41 интерактивный
|
||||
кадр. Полный отчёт и доказательства — `target/qa-opening-v1-design/verdict.md`. Вердикт —
|
||||
**NOT ACCEPTED** по трём дефектам:
|
||||
|
||||
1. Dashboard/editor имеют alpha=180 вместо 255, что снижает контраст в обеих темах. Ранние
|
||||
full-workspace paths требуют общей непрозрачной заливки.
|
||||
2. Детали Branches при 640×480 сжимают подписи до 35–45 px и переносят их по 1–3 буквы;
|
||||
требуется стабильная ширина label-колонки без горизонтальной прокрутки.
|
||||
3. Редактор смешивает RU/DE с английскими контролами; `repertoire_editor.rs` также отсутствовал
|
||||
в source scanners i18n. Нужны переводы всех отсутствующих ключей, а не только замеченных.
|
||||
|
||||
При этом подтверждены общая визуальная система workspace, доступность шести context-политик,
|
||||
Global union 11 вместо 12 с корректными процентами, все вкладки и SAN, одиночная/четырёхдневная
|
||||
History, автоматический и ручной snapshot без дубля и скачков, Close/Escape с прежним scroll,
|
||||
сохранность PGN/learning при Cancel/Applied и HiDPI 2×. Дефекты исправляются с последующей
|
||||
повторной приёмкой, а не признаются визуально незначительными.
|
||||
|
||||
После этого отчёта владелец изменил матрицу: **минимум 960×600, основная 1400×900**. Кадры 640×480
|
||||
и микро-контейнеры остаются только историческими техническими артефактами и не определяют дизайн.
|
||||
Повторная приёмка исправлений выполняется только на новой матрице.
|
||||
|
||||
### Финальная приёмка V1
|
||||
|
||||
Фон dashboard/editor получил `window_fill` без изменения geometry, Branches — responsive
|
||||
колонки деталей и полные wide headers, Summary — responsive numeric widths и высоту header 40 pt.
|
||||
Добавлены 23 ключа редактора во все девять языков и `repertoire_editor.rs` в оба i18n scanners.
|
||||
|
||||
Независимый reviewer подтвердил фон и board bbox, Branches и RU/DE-редактор, затем Summary:
|
||||
`Изучается`, `Не подтверждено`, `К повторению` читаются полностью, максимум две строки, все девять
|
||||
колонок помещаются при 960×600 и 1400×900. Все 12 исходных after-кадров и четыре
|
||||
`summary-fixed-*.png` имеют `alpha=(255,255)`. **Вердикт по V1 — ACCEPTED.**
|
||||
|
||||
Финальный workspace после исправлений: **201 desktop + 184 trainer tests**, остальные пакеты,
|
||||
Clippy и WebAssembly check зелёные. AT-17/30, GlobalTotal и adaptive prime приняты отдельно.
|
||||
Сохранность PGN/learning, Global dedup, History, Close/Escape и Branches click подтверждены живыми
|
||||
сценариями. Выпуск и новые теги не создавались; follow-up изменения находятся поверх d1733b4.
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue