Modern Apps git

← Modern-Apps.git

flashcards: add study modes, media, bulk ops, stats charts, and FSRS tuning

Commit
0b271687d4682792482eb1c36c440ee26119b450
Author
Vayun Mathur <[email protected]>
When
2026-08-15 02:00 UTC (3 months ago)
Parents
117e140

Diff

flashcards/build.gradle.kts
diff --git a/flashcards/build.gradle.kts b/flashcards/build.gradle.ktsindex c7b62a5515..77a1e9fe7d 100644--- a/flashcards/build.gradle.kts+++ b/flashcards/build.gradle.kts@@ -19,5 +19,6 @@ android { dependencies {     implementRoom(libs)     implementation(project(":library:room"))+    implementation(project(":library:image"))     implementation(libs.androidx.work.runtime.ktx) }
flashcards/src/main/java/com/vayunmathur/flashcards/MainActivity.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/MainActivity.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/MainActivity.ktindex 16f11cca6e..ba935f553f 100644--- a/flashcards/src/main/java/com/vayunmathur/flashcards/MainActivity.kt+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/MainActivity.kt@@ -118,7 +118,13 @@ sealed interface Route : NavKey {     data class NoteEdit(val deckId: Long, val noteId: Long) : Route      @Serializable-    data class Review(val deckId: Long) : Route+    data class Review(+        val deckId: Long,+        val mode: Int = 0,+        val count: Int = 20,+        val daysAhead: Int = 3,+        val tags: List<String> = emptyList(),+    ) : Route }  @Composable@@ -148,6 +154,6 @@ fun Navigation(viewModel: FlashcardsViewModel) {         entry<Route.NoteTypeEdit> { NoteTypeEditPage(backStack, viewModel, it.noteTypeId) }         entry<Route.CardList> { NoteListPage(backStack, viewModel, it.deckId) }         entry<Route.NoteEdit> { NoteEditPage(backStack, viewModel, it.deckId, it.noteId) }-        entry<Route.Review> { ReviewPage(backStack, viewModel, it.deckId) }+        entry<Route.Review> { ReviewPage(backStack, viewModel, it.deckId, it.mode, it.count, it.daysAhead, it.tags) }     } }
flashcards/src/main/java/com/vayunmathur/flashcards/data/Card.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/data/Card.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/data/Card.ktindex d3a7ea1043..87f2837662 100644--- a/flashcards/src/main/java/com/vayunmathur/flashcards/data/Card.kt+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/data/Card.kt@@ -49,10 +49,15 @@ data class Card(     val easeFactor: Double = 2.5,     val intervalDays: Int = 0,     val repetitions: Int = 0,+    /** 0 = active, 1 = suspended (excluded from every study queue). */+    val suspended: Int = 0,     override val position: Double = 0.0, ) : ReorderableDatabaseItem<Card> {     override fun withPosition(position: Double) = copy(position = position)      /** True while the card has never been graded. */     val isNew: Boolean get() = state == CardState.NEW++    /** True while the card is suspended and excluded from study. */+    val isSuspended: Boolean get() = suspended == 1 }
flashcards/src/main/java/com/vayunmathur/flashcards/data/Deck.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/data/Deck.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/data/Deck.ktindex ee4f8ca7a2..15836e8c03 100644--- a/flashcards/src/main/java/com/vayunmathur/flashcards/data/Deck.kt+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/data/Deck.kt@@ -10,7 +10,9 @@ import kotlinx.serialization.Serializable  *  * [newPerDay]/[maxReviewsPerDay] cap how many cards a session introduces, and  * [desiredRetention] (0..1) is the FSRS target recall probability that drives the- * scheduled intervals.+ * scheduled intervals. [fsrsWeights] holds a JSON array of 19 FSRS doubles+ * (empty = use `Scheduler.DEFAULT_W`) and [leechThreshold] is the number of lapses+ * before a card is auto-suspended as a leech (0 = disabled).  */ @Serializable @Entity@@ -20,6 +22,8 @@ data class Deck(     val newPerDay: Int = 20,     val maxReviewsPerDay: Int = 200,     val desiredRetention: Double = 0.9,+    val fsrsWeights: String = "",+    val leechThreshold: Int = 8,     override val position: Double = 0.0, ) : ReorderableDatabaseItem<Deck> {     override fun withPosition(position: Double) = copy(position = position)
flashcards/src/main/java/com/vayunmathur/flashcards/data/FlashcardsDatabase.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/data/FlashcardsDatabase.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/data/FlashcardsDatabase.ktindex 39fd10f4db..a8cf3fb9e4 100644--- a/flashcards/src/main/java/com/vayunmathur/flashcards/data/FlashcardsDatabase.kt+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/data/FlashcardsDatabase.kt@@ -117,6 +117,9 @@ interface NoteDao {     @Query("SELECT * FROM Note WHERE id = :id")     suspend fun getById(id: Long): Note? +    @Query("SELECT * FROM Note WHERE id IN (:ids)")+    suspend fun getByIds(ids: List<Long>): List<Note>+     @Query("SELECT * FROM Note WHERE id = :id")     fun getByIdFlow(id: Long): Flow<Note?> @@ -129,6 +132,9 @@ interface NoteDao {     @Delete     suspend fun delete(value: Note): Int +    @Query("DELETE FROM Note WHERE id IN (:ids)")+    suspend fun deleteByIds(ids: List<Long>)+     @Query("DELETE FROM Note WHERE deckId = :deckId")     suspend fun deleteByDeck(deckId: Long) }@@ -147,15 +153,21 @@ interface CardDao {     @Query("SELECT * FROM Card WHERE deckId = :deckId")     suspend fun getByDeck(deckId: Long): List<Card> -    @Query("SELECT * FROM Card WHERE deckId = :deckId AND dueDate <= :now")+    @Query("SELECT * FROM Card WHERE deckId = :deckId AND dueDate <= :now AND suspended = 0")     fun getDueByDeckFlow(deckId: Long, now: Long): Flow<List<Card>>      @Query("SELECT * FROM Card WHERE id = :id")     fun getByIdFlow(id: Long): Flow<Card?> +    @Query("SELECT * FROM Card WHERE id IN (:ids)")+    suspend fun getByIds(ids: List<Long>): List<Card>+     @Query("SELECT * FROM Card WHERE noteId = :noteId")     suspend fun getByNote(noteId: Long): List<Card> +    @Query("SELECT * FROM Card WHERE noteId IN (:noteIds)")+    suspend fun getByNotes(noteIds: List<Long>): List<Card>+     @Upsert     suspend fun upsert(value: Card): Long @@ -165,12 +177,24 @@ interface CardDao {     @Delete     suspend fun delete(value: Card): Int +    @Query("UPDATE Card SET suspended = :value WHERE id IN (:ids)")+    suspend fun setSuspended(ids: List<Long>, value: Int)++    @Query("UPDATE Card SET suspended = :value WHERE noteId IN (:noteIds)")+    suspend fun setSuspendedByNotes(noteIds: List<Long>, value: Int)++    @Query("UPDATE Card SET deckId = :deckId WHERE noteId IN (:noteIds)")+    suspend fun moveByNotes(noteIds: List<Long>, deckId: Long)+     @Query("DELETE FROM Card WHERE deckId = :deckId")     suspend fun deleteByDeck(deckId: Long)      @Query("DELETE FROM Card WHERE noteId = :noteId")     suspend fun deleteByNote(noteId: Long) +    @Query("DELETE FROM Card WHERE noteId IN (:noteIds)")+    suspend fun deleteByNotes(noteIds: List<Long>)+     @Query("DELETE FROM Card WHERE noteId = :noteId AND templateOrd NOT IN (:keepOrds)")     suspend fun deleteRemovedTemplates(noteId: Long, keepOrds: List<Int>) }@@ -183,6 +207,9 @@ interface ReviewLogDao {     @Query("SELECT * FROM ReviewLog WHERE deckId = :deckId")     fun getByDeckFlow(deckId: Long): Flow<List<ReviewLog>> +    @Query("SELECT * FROM ReviewLog WHERE deckId = :deckId ORDER BY cardId, reviewedAt")+    suspend fun getByDeckOrdered(deckId: Long): List<ReviewLog>+     @Query("SELECT * FROM ReviewLog WHERE cardId = :cardId")     suspend fun getByCard(cardId: Long): List<ReviewLog> @@ -192,6 +219,9 @@ interface ReviewLogDao {     @Query("DELETE FROM ReviewLog WHERE id = :id")     suspend fun deleteById(id: Long) +    @Query("DELETE FROM ReviewLog WHERE cardId IN (:cardIds)")+    suspend fun deleteByCards(cardIds: List<Long>)+     @Query("DELETE FROM ReviewLog WHERE deckId = :deckId")     suspend fun deleteByDeck(deckId: Long) }@@ -206,7 +236,7 @@ interface ReviewLogDao {         CardTemplate::class,         Note::class,     ],-    version = 3,+    version = 4,     exportSchema = false, ) abstract class FlashcardsDatabase : RoomDatabase() {@@ -247,6 +277,7 @@ abstract class FlashcardsDatabase : RoomDatabase() {                 )             },             MIGRATION_2_3,+            MIGRATION_3_4,         )     } }@@ -371,3 +402,15 @@ val MIGRATION_2_3 = Migration(2, 3) { db ->     )     db.execSQL("DROP TABLE `Card_old`") }++/**+ * Adds suspend/leech + per-deck FSRS columns. Plain `ALTER TABLE ADD COLUMN`s with+ * defaults so legacy rows populate correctly; the entity fields carry no+ * `@ColumnInfo(defaultValue=…)`, so Room skips the default-value comparison on open+ * (same pattern as [MIGRATION_2_3]).+ */+val MIGRATION_3_4 = Migration(3, 4) { db ->+    db.execSQL("ALTER TABLE Card ADD COLUMN suspended INTEGER NOT NULL DEFAULT 0")+    db.execSQL("ALTER TABLE Deck ADD COLUMN fsrsWeights TEXT NOT NULL DEFAULT ''")+    db.execSQL("ALTER TABLE Deck ADD COLUMN leechThreshold INTEGER NOT NULL DEFAULT 8")+}
flashcards/src/main/java/com/vayunmathur/flashcards/ui/FlashcardsCharts.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/ui/FlashcardsCharts.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/ui/FlashcardsCharts.ktindex 55c0dec4bb..938e2ab494 100644--- a/flashcards/src/main/java/com/vayunmathur/flashcards/ui/FlashcardsCharts.kt+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/ui/FlashcardsCharts.kt@@ -271,3 +271,47 @@ private fun BoxScope.yAxisLabel(             .padding(start = 4.dp),     ) }++/**+ * A GitHub-style activity heatmap: [weeks] columns of 7 day-cells, the last cell+ * being today, with each cell's opacity scaled by its review count over the max.+ * Built from a `byDay` list of [DailyStat].+ */+@Composable+fun ReviewHeatmap(+    days: List<com.vayunmathur.flashcards.util.DailyStat>,+    modifier: Modifier = Modifier,+    weeks: Int = 26,+    color: Color = MaterialTheme.colorScheme.primary,+) {+    val counts = remember(days) { days.associate { it.epochDay to it.count } }+    val maxCount = (days.maxOfOrNull { it.count } ?: 0).coerceAtLeast(1)+    val today = java.time.LocalDate.now().toEpochDay()+    val emptyColor = color.copy(alpha = 0.10f)++    BoxWithConstraints(modifier.fillMaxWidth()) {+        val density = LocalDensity.current+        val cell = with(density) { (maxWidth.toPx() / weeks) }+        Canvas(+            modifier = Modifier+                .fillMaxWidth()+                .height(with(density) { (cell * 7).toDp() }),+        ) {+            val gap = cell * 0.14f+            val total = weeks * 7+            for (i in 0 until total) {+                val epochDay = today - (total - 1 - i)+                val col = i / 7+                val row = i % 7+                val count = counts[epochDay] ?: 0+                val alpha = if (count <= 0) 0f else 0.2f + 0.8f * (count.toFloat() / maxCount)+                drawRoundRect(+                    color = if (count <= 0) emptyColor else color.copy(alpha = alpha),+                    topLeft = Offset(col * cell + gap / 2, row * cell + gap / 2),+                    size = Size(cell - gap, cell - gap),+                    cornerRadius = CornerRadius(2.dp.toPx(), 2.dp.toPx()),+                )+            }+        }+    }+}
flashcards/src/main/java/com/vayunmathur/flashcards/ui/MarkdownContent.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/ui/MarkdownContent.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/ui/MarkdownContent.ktnew file mode 100644index 0000000000..8911de6d3b--- /dev/null+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/ui/MarkdownContent.kt@@ -0,0 +1,81 @@+package com.vayunmathur.flashcards.ui++import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.heightIn+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.runtime.remember+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.text.TextStyle+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp+import com.vayunmathur.flashcards.util.MediaStore+import com.vayunmathur.library.image.compose.AsyncImage+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.util.parseMarkdown++private val imageRegex = Regex("""!\[([^\]]*)]\(([^)]+)\)""")++/**+ * Renders markdown [text] that may embed images as `![alt](filename)`. Text runs+ * render through [parseMarkdown]; image runs resolve the filename against+ * [MediaStore] and draw via the shared [AsyncImage]. Used on the review card and+ * the note-type live preview.+ */+@Composable+fun MarkdownContent(+    text: String,+    modifier: Modifier = Modifier,+    style: TextStyle = MaterialTheme.typography.bodyLarge,+    textAlign: TextAlign = TextAlign.Center,+) {+    val context = LocalContext.current+    val media = remember { MediaStore(context) }+    val segments = remember(text) { splitSegments(text) }++    Column(modifier = modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) {+        segments.forEach { segment ->+            when (segment) {+                is Segment.TextRun -> if (segment.value.isNotBlank()) {+                    Text(+                        parseMarkdown(segment.value.trim(), showMarkers = false),+                        style = style,+                        textAlign = textAlign,+                    )+                }+                is Segment.ImageRun -> AsyncImage(+                    model = media.resolve(segment.name),+                    contentDescription = segment.alt,+                    modifier = Modifier+                        .fillMaxWidth()+                        .heightIn(max = 240.dp)+                        .padding(vertical = 8.dp),+                )+            }+        }+    }+}++private sealed interface Segment {+    data class TextRun(val value: String) : Segment+    data class ImageRun(val alt: String, val name: String) : Segment+}++private fun splitSegments(text: String): List<Segment> {+    val out = mutableListOf<Segment>()+    var last = 0+    imageRegex.findAll(text).forEach { match ->+        if (match.range.first > last) {+            out.add(Segment.TextRun(text.substring(last, match.range.first)))+        }+        out.add(Segment.ImageRun(match.groupValues[1], match.groupValues[2].trim()))+        last = match.range.last + 1+    }+    if (last < text.length) out.add(Segment.TextRun(text.substring(last)))+    if (out.isEmpty()) out.add(Segment.TextRun(text))+    return out+}
flashcards/src/main/java/com/vayunmathur/flashcards/ui/NoteEditPage.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/ui/NoteEditPage.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/ui/NoteEditPage.ktindex bad509d0c3..7c54211b77 100644--- a/flashcards/src/main/java/com/vayunmathur/flashcards/ui/NoteEditPage.kt+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/ui/NoteEditPage.kt@@ -1,8 +1,12 @@ package com.vayunmathur.flashcards.ui +import androidx.activity.compose.rememberLauncherForActivityResult+import androidx.activity.result.PickVisualMediaRequest+import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding@@ -16,8 +20,10 @@ import androidx.compose.runtime.mutableLongStateOf import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.TextRange import androidx.compose.ui.text.input.TextFieldValue@@ -27,6 +33,7 @@ import com.vayunmathur.flashcards.R import com.vayunmathur.flashcards.Route import com.vayunmathur.flashcards.util.DeckOption import com.vayunmathur.flashcards.util.FlashcardsViewModel+import com.vayunmathur.flashcards.util.MediaStore import com.vayunmathur.flashcards.util.NoteEditActions import com.vayunmathur.flashcards.util.NoteEditUiState import com.vayunmathur.flashcards.util.NoteTypeConfig@@ -35,13 +42,20 @@ import com.vayunmathur.library.ui.DropdownMenu import com.vayunmathur.library.ui.DropdownMenuItem import com.vayunmathur.library.ui.IconButton import com.vayunmathur.library.ui.IconDelete+import com.vayunmathur.library.ui.IconImage+import com.vayunmathur.library.ui.IconRestore import com.vayunmathur.library.ui.IconSave+import com.vayunmathur.library.ui.IconVisibilityOff import com.vayunmathur.library.ui.MarkdownEditor import com.vayunmathur.library.ui.MarkdownFormatToolbar import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.OutlinedTextField import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton import com.vayunmathur.library.util.NavBackStack+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext  /**  * Binds the note with [noteId] (0 for a new note) in [deckId] to the stateless@@ -58,9 +72,29 @@ fun NoteEditPage(         .collectAsStateWithLifecycle(null)     val noteTypes by viewModel.noteTypes.collectAsStateWithLifecycle()     val decks by viewModel.decks.collectAsStateWithLifecycle()+    val allCards by viewModel.cards.collectAsStateWithLifecycle()      val configs = noteTypes.map { NoteTypeConfig(it.noteType.id, it.noteType.name, it.fields.map { f -> f.name }) }     val isNew = noteId == 0L+    val noteCards = allCards.filter { it.noteId == noteId }+    val suspended = noteCards.isNotEmpty() && noteCards.all { it.isSuspended }++    val context = LocalContext.current+    val media = remember { MediaStore(context) }+    val scope = rememberCoroutineScope()+    var pendingInsert by remember { mutableStateOf<((String) -> Unit)?>(null) }+    val imagePicker = rememberLauncherForActivityResult(+        ActivityResultContracts.PickVisualMedia(),+    ) { uri ->+        val callback = pendingInsert+        pendingInsert = null+        if (uri != null && callback != null) {+            scope.launch {+                val name = withContext(Dispatchers.IO) { media.import(context, uri) }+                if (name != null) callback(name)+            }+        }+    }      val actions = remember(backStack, viewModel, deckId, noteId) {         object : NoteEditActions {@@ -73,6 +107,9 @@ fun NoteEditPage(                 dbNote?.let { viewModel.deleteNote(it) }                 backStack.pop()             }+            override fun setSuspended(suspended: Boolean) {+                viewModel.setNoteSuspended(noteId, suspended)+            }         }     } @@ -83,10 +120,17 @@ fun NoteEditPage(             initialFieldValues = dbNote?.fieldList ?: emptyList(),             initialTags = dbNote?.tags.orEmpty(),             isNew = isNew,+            isSuspended = suspended,             noteTypes = configs,             decks = decks.map { DeckOption(it.id, it.name) },         ),         actions = actions,+        onPickImage = { insert ->+            pendingInsert = insert+            imagePicker.launch(+                PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly),+            )+        },     ) } @@ -99,6 +143,7 @@ fun NoteEditPage( fun NoteEditScreen(     state: NoteEditUiState,     actions: NoteEditActions,+    onPickImage: (insert: (String) -> Unit) -> Unit = {}, ) {     var typeId by remember { mutableLongStateOf(state.initialNoteTypeId) }     var deckId by remember { mutableLongStateOf(state.initialDeckId) }@@ -116,6 +161,34 @@ fun NoteEditScreen(         fields.forEach { name -> fieldTfv.add(TextFieldValue(values[name].orEmpty())) }     } +    /** Inserts [text] at the active field's cursor (replacing any selection). */+    fun insertAtCursor(text: String) {+        val i = activeField+        if (i !in fieldTfv.indices) return+        val tfv = fieldTfv[i]+        val sel = tfv.selection+        val body = tfv.text+        val newText = body.substring(0, sel.start) + text + body.substring(sel.end)+        fieldTfv[i] = tfv.copy(text = newText, selection = TextRange(sel.start + text.length))+        values[currentFields()[i]] = newText+    }++    /** Wraps the active field's selection in the next `{{cN::…}}` cloze. */+    fun insertCloze() {+        val i = activeField+        if (i !in fieldTfv.indices) return+        val tfv = fieldTfv[i]+        val sel = tfv.selection+        val body = tfv.text+        val next = (Regex("""\{\{c(\d+)::""").findAll(body)+            .mapNotNull { it.groupValues[1].toIntOrNull() }.maxOrNull() ?: 0) + 1+        val selected = body.substring(sel.start, sel.end)+        val wrapped = "{{c$next::$selected}}"+        val newText = body.substring(0, sel.start) + wrapped + body.substring(sel.end)+        fieldTfv[i] = tfv.copy(text = newText, selection = TextRange(sel.start + wrapped.length))+        values[currentFields()[i]] = newText+    }+     LaunchedEffect(state) {         typeId = state.initialNoteTypeId         deckId = state.initialDeckId@@ -131,6 +204,9 @@ fun NoteEditScreen(         onNavigateBack = { actions.back() },         actions = {             if (!state.isNew) {+                IconButton(onClick = { actions.setSuspended(!state.isSuspended) }) {+                    if (state.isSuspended) IconRestore() else IconVisibilityOff()+                }                 IconButton(onClick = { actions.deleteNote() }) { IconDelete() }             }             IconButton(onClick = {@@ -141,13 +217,23 @@ fun NoteEditScreen(         bottomBar = {             val index = activeField             if (index in fieldTfv.indices) {-                MarkdownFormatToolbar(-                    value = fieldTfv[index],-                    onValueChange = {-                        fieldTfv[index] = it-                        values[currentFields()[index]] = it.text-                    },-                )+                Column {+                    Row(Modifier.fillMaxWidth().padding(horizontal = 4.dp)) {+                        IconButton(onClick = { onPickImage { name -> insertAtCursor("![]($name)") } }) {+                            IconImage()+                        }+                        TextButton(onClick = { insertCloze() }) {+                            Text(stringResource(R.string.insert_cloze))+                        }+                    }+                    MarkdownFormatToolbar(+                        value = fieldTfv[index],+                        onValueChange = {+                            fieldTfv[index] = it+                            values[currentFields()[index]] = it.text+                        },+                    )+                }             }         },     ) { paddingValues ->
flashcards/src/main/java/com/vayunmathur/flashcards/ui/NoteListPage.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/ui/NoteListPage.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/ui/NoteListPage.ktindex b0101653e2..013f66ad41 100644--- a/flashcards/src/main/java/com/vayunmathur/flashcards/ui/NoteListPage.kt+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/ui/NoteListPage.kt@@ -1,12 +1,14 @@ package com.vayunmathur.flashcards.ui  import android.content.Intent-import android.widget.Toast import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.animation.core.animateDpAsState import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.clickable+import androidx.compose.foundation.combinedClickable+import androidx.compose.foundation.horizontalScroll+import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row@@ -16,6 +18,7 @@ import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.rememberLazyListState+import androidx.compose.foundation.rememberScrollState import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue@@ -32,26 +35,39 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.vayunmathur.flashcards.R import com.vayunmathur.flashcards.Route import com.vayunmathur.flashcards.data.Note+import com.vayunmathur.flashcards.util.DeckOption import com.vayunmathur.flashcards.util.FlashcardsViewModel import com.vayunmathur.flashcards.util.NoteListActions import com.vayunmathur.flashcards.util.NoteListUiState import com.vayunmathur.flashcards.util.NoteRow+import com.vayunmathur.flashcards.util.StudyParams import com.vayunmathur.library.ui.AppScaffold import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.Checkbox import com.vayunmathur.library.ui.CommonSearchBar+import com.vayunmathur.library.ui.ConfirmDialog+import com.vayunmathur.library.ui.DropdownMenu+import com.vayunmathur.library.ui.DropdownMenuItem import com.vayunmathur.library.ui.EmptyState+import com.vayunmathur.library.ui.FilterChip import com.vayunmathur.library.ui.FloatingActionButton import com.vayunmathur.library.ui.IconAdd import com.vayunmathur.library.ui.IconButton import com.vayunmathur.library.ui.IconDelete import com.vayunmathur.library.ui.IconDragHandle+import com.vayunmathur.library.ui.IconFolderOpen+import com.vayunmathur.library.ui.IconMoreVert+import com.vayunmathur.library.ui.IconRestore import com.vayunmathur.library.ui.IconShare import com.vayunmathur.library.ui.IconUpload+import com.vayunmathur.library.ui.IconVisibilityOff import com.vayunmathur.library.ui.ListItem+import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.ReorderableItem import com.vayunmathur.library.ui.Surface import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.rememberReorderableLazyListState+import com.vayunmathur.library.ui.rememberSelectionState import com.vayunmathur.library.ui.reorderDragHandle import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.library.util.parseMarkdown@@ -99,11 +115,6 @@ fun NoteListPage(             )         }     }-    LaunchedEffect(viewModel) {-        viewModel.messages.collect { message ->-            Toast.makeText(context, message, Toast.LENGTH_LONG).show()-        }-    }      val actions = remember(backStack, viewModel, deckId) {         object : NoteListActions {@@ -111,19 +122,56 @@ fun NoteListPage(             override fun openNote(id: Long) { backStack.add(Route.NoteEdit(deckId, id)) }             override fun addNote() { backStack.add(Route.NoteEdit(deckId, 0)) }             override fun deleteNote(note: Note) { viewModel.deleteNote(note) }-            override fun study() { backStack.add(Route.Review(deckId)) }+            override fun study(tags: Set<String>) {+                backStack.add(Route.Review(deckId, tags = tags.toList()))+            }+            override fun customStudy(params: StudyParams, tags: Set<String>) {+                backStack.add(+                    Route.Review(+                        deckId = deckId,+                        mode = params.mode.ordinal,+                        count = params.count,+                        daysAhead = params.daysAhead,+                        tags = tags.toList(),+                    ),+                )+            }             override fun reorder(notes: List<Note>) { viewModel.reorderNotes(notes) }             override fun openStats() { backStack.add(Route.Stats) }             override fun share() { viewModel.exportApkg(deckId) }+            override fun exportCsv() { viewModel.exportCsv(deckId) }+            override fun deleteNotes(ids: List<Long>) { viewModel.deleteNotes(ids) }+            override fun moveNotes(ids: List<Long>, deckId: Long) { viewModel.moveNotes(ids, deckId) }+            override fun addTag(ids: List<Long>, tag: String) { viewModel.addTag(ids, tag) }+            override fun removeTag(ids: List<Long>, tag: String) { viewModel.removeTag(ids, tag) }+            override fun setSuspended(ids: List<Long>, suspended: Boolean) {+                viewModel.setNotesSuspended(ids, suspended)+            }+            override fun resetScheduling(ids: List<Long>) { viewModel.resetSchedulingForNotes(ids) }         }     } +    val rows = notes.sortedBy { it.position }.map { note ->+        val noteCards = cardsByNote[note.id].orEmpty()+        NoteRow(+            note = note,+            cardCount = noteCards.size,+            suspended = noteCards.isNotEmpty() && noteCards.all { it.isSuspended },+        )+    }+    val allTags = notes+        .flatMap { it.tags.split(" ") }+        .filter { it.isNotBlank() }+        .distinct()+        .sorted()+     NoteListScreen(         state = NoteListUiState(             deckName = deckName,-            notes = notes.sortedBy { it.position }-                .map { NoteRow(it, cardsByNote[it.id]?.size ?: 0) },-            dueCount = cards.count { (!it.isNew && it.dueDate <= now) || it.isNew },+            notes = rows,+            dueCount = cards.count { !it.isSuspended && ((!it.isNew && it.dueDate <= now) || it.isNew) },+            tags = allTags,+            decks = decks.filter { it.id != deckId }.map { DeckOption(it.id, it.name) },         ),         actions = actions,         onImport = {@@ -153,34 +201,109 @@ fun NoteListScreen(     onImport: () -> Unit = {}, ) {     var query by remember { mutableStateOf("") }-    val filtered = if (query.isBlank()) {+    var selectedTags by remember { mutableStateOf(emptySet<String>()) }+    val selection = rememberSelectionState<Long>()+    var showCustomStudy by remember { mutableStateOf(false) }+    var showMove by remember { mutableStateOf(false) }+    var tagDialog by remember { mutableStateOf<TagDialogKind?>(null) }+    var showReset by remember { mutableStateOf(false) }+    var overflow by remember { mutableStateOf(false) }++    val byQuery = if (query.isBlank()) {         state.notes     } else {         state.notes.filter {             it.note.flds.contains(query, true) || it.note.tags.contains(query, true)         }     }+    val filtered = if (selectedTags.isEmpty()) {+        byQuery+    } else {+        byQuery.filter { row ->+            val tags = row.note.tags.split(" ").toSet()+            selectedTags.all { it in tags }+        }+    }+    val plainList = query.isNotBlank() || selectedTags.isNotEmpty() || selection.isActive      AppScaffold(-        title = state.deckName,-        onNavigateBack = { actions.back() },+        title = if (selection.isActive) {+            stringResource(R.string.selected_count, selection.count)+        } else {+            state.deckName+        },+        onNavigateBack = { if (selection.isActive) selection.clear() else actions.back() },         actions = {-            IconButton(onClick = onImport) { IconUpload() }-            IconButton(onClick = { actions.share() }) { IconShare() }+            if (selection.isActive) {+                val ids = { selection.selected.toList() }+                IconButton(onClick = { showMove = true }) { IconFolderOpen() }+                IconButton(onClick = { actions.setSuspended(ids(), true); selection.clear() }) {+                    IconVisibilityOff()+                }+                IconButton(onClick = { actions.deleteNotes(ids()); selection.clear() }) { IconDelete() }+                IconButton(onClick = { overflow = true }) { IconMoreVert() }+                DropdownMenu(expanded = overflow, onDismissRequest = { overflow = false }) {+                    DropdownMenuItem(+                        text = { Text(stringResource(R.string.add_tag)) },+                        onClick = { overflow = false; tagDialog = TagDialogKind.ADD },+                    )+                    DropdownMenuItem(+                        text = { Text(stringResource(R.string.remove_tag)) },+                        onClick = { overflow = false; tagDialog = TagDialogKind.REMOVE },+                    )+                    DropdownMenuItem(+                        text = { Text(stringResource(R.string.unsuspend)) },+                        onClick = {+                            overflow = false+                            actions.setSuspended(selection.selected.toList(), false)+                            selection.clear()+                        },+                    )+                    DropdownMenuItem(+                        text = { Text(stringResource(R.string.reset_scheduling)) },+                        onClick = { overflow = false; showReset = true },+                    )+                }+            } else {+                IconButton(onClick = onImport) { IconUpload() }+                IconButton(onClick = { actions.share() }) { IconShare() }+                IconButton(onClick = { overflow = true }) { IconMoreVert() }+                DropdownMenu(expanded = overflow, onDismissRequest = { overflow = false }) {+                    DropdownMenuItem(+                        text = { Text(stringResource(R.string.custom_study)) },+                        onClick = { overflow = false; showCustomStudy = true },+                    )+                    DropdownMenuItem(+                        text = { Text(stringResource(R.string.export_csv)) },+                        onClick = { overflow = false; actions.exportCsv() },+                    )+                }+            }         },         floatingActionButton = {-            FloatingActionButton(onClick = { actions.addNote() }) { IconAdd() }+            if (!selection.isActive) {+                FloatingActionButton(onClick = { actions.addNote() }) { IconAdd() }+            }         },     ) { paddingValues ->         Column(Modifier.fillMaxSize().padding(paddingValues)) {-            if (state.dueCount > 0) {+            if (state.dueCount > 0 && !selection.isActive) {                 Button(-                    onClick = { actions.study() },+                    onClick = { actions.study(selectedTags) },                     modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp),                 ) {                     Text(stringResource(R.string.study))                 }             }+            if (state.tags.isNotEmpty()) {+                TagFilterRow(+                    tags = state.tags,+                    selected = selectedTags,+                    onToggle = { tag ->+                        selectedTags = if (tag in selectedTags) selectedTags - tag else selectedTags + tag+                    },+                )+            }             if (state.notes.isNotEmpty()) {                 CommonSearchBar(                     value = query,@@ -196,20 +319,108 @@ fun NoteListScreen(                     icon = { IconAdd() },                     modifier = Modifier.fillMaxSize(),                 )-                query.isBlank() -> ReorderableNoteList(filtered, actions)+                !plainList -> ReorderableNoteList(filtered, actions, selection)                 else -> LazyColumn(Modifier.fillMaxSize()) {                     items(filtered, key = { it.note.id }) { row ->-                        NoteRowItem(row, onOpen = { actions.openNote(row.note.id) }, onDelete = { actions.deleteNote(row.note) })+                        NoteRowItem(+                            row = row,+                            selection = selection,+                            onOpen = {+                                if (selection.isActive) selection.toggle(row.note.id)+                                else actions.openNote(row.note.id)+                            },+                            onLongPress = { selection.toggle(row.note.id) },+                        )                     }                 }             }         }     }++    if (showCustomStudy) {+        CustomStudyDialog(+            onStart = { params ->+                showCustomStudy = false+                actions.customStudy(params, selectedTags)+            },+            onDismiss = { showCustomStudy = false },+        )+    }++    if (showMove) {+        MoveDeckDialog(+            decks = state.decks,+            onPick = { deckId ->+                showMove = false+                actions.moveNotes(selection.selected.toList(), deckId)+                selection.clear()+            },+            onDismiss = { showMove = false },+        )+    }++    tagDialog?.let { kind ->+        TagDialog(+            title = stringResource(if (kind == TagDialogKind.ADD) R.string.add_tag else R.string.remove_tag),+            onConfirm = { tag ->+                val ids = selection.selected.toList()+                if (kind == TagDialogKind.ADD) actions.addTag(ids, tag) else actions.removeTag(ids, tag)+                tagDialog = null+                selection.clear()+            },+            onDismiss = { tagDialog = null },+        )+    }++    if (showReset) {+        ConfirmDialog(+            title = stringResource(R.string.reset_scheduling),+            message = stringResource(R.string.reset_scheduling_message),+            confirmLabel = stringResource(R.string.reset_scheduling),+            dismissLabel = stringResource(R.string.cancel),+            destructive = true,+            onConfirm = {+                actions.resetScheduling(selection.selected.toList())+                showReset = false+                selection.clear()+            },+            onDismiss = { showReset = false },+        )+    }+}++private enum class TagDialogKind { ADD, REMOVE }++@Composable+private fun TagFilterRow(+    tags: List<String>,+    selected: Set<String>,+    onToggle: (String) -> Unit,+) {+    Row(+        Modifier+            .fillMaxWidth()+            .horizontalScroll(rememberScrollState())+            .padding(horizontal = 12.dp, vertical = 4.dp),+        horizontalArrangement = Arrangement.spacedBy(8.dp),+    ) {+        tags.forEach { tag ->+            FilterChip(+                selected = tag in selected,+                onClick = { onToggle(tag) },+                label = { Text(tag) },+            )+        }+    } }  @OptIn(ExperimentalFoundationApi::class) @Composable-private fun ReorderableNoteList(rows: List<NoteRow>, actions: NoteListActions) {+private fun ReorderableNoteList(+    rows: List<NoteRow>,+    actions: NoteListActions,+    selection: com.vayunmathur.library.ui.SelectionState<Long>,+) {     val listState = rememberLazyListState()     var local by remember { mutableStateOf(rows) }     var hasDragged by remember { mutableStateOf(false) }@@ -240,8 +451,9 @@ private fun ReorderableNoteList(rows: List<NoteRow>, actions: NoteListActions) {                 Surface(shadowElevation = elevation) {                     NoteRowItem(                         row = row,+                        selection = selection,                         onOpen = { actions.openNote(row.note.id) },-                        onDelete = { actions.deleteNote(row.note) },+                        onLongPress = { selection.toggle(row.note.id) },                         dragHandle = Modifier.reorderDragHandle(reorderState, key = row.note.id),                     )                 }@@ -250,15 +462,28 @@ private fun ReorderableNoteList(rows: List<NoteRow>, actions: NoteListActions) {     } } +@OptIn(ExperimentalFoundationApi::class) @Composable private fun NoteRowItem(     row: NoteRow,+    selection: com.vayunmathur.library.ui.SelectionState<Long>,     onOpen: () -> Unit,-    onDelete: () -> Unit,+    onLongPress: () -> Unit,     dragHandle: Modifier? = null, ) {     val fields = row.note.fieldList+    val muted = row.suspended     ListItem(+        leadingContent = if (selection.isActive) {+            {+                Checkbox(+                    checked = selection.isSelected(row.note.id),+                    onCheckedChange = { selection.toggle(row.note.id) },+                )+            }+        } else {+            null+        },         headlineContent = {             Text(parseMarkdown(row.note.sortField.substringBefore('\n').take(60), showMarkers = false))         },@@ -267,16 +492,151 @@ private fun NoteRowItem(         },         trailingContent = {             Row {+                if (muted) {+                    Text(+                        stringResource(R.string.suspended_badge),+                        style = MaterialTheme.typography.labelSmall,+                        color = MaterialTheme.colorScheme.error,+                    )+                }                 if (row.cardCount != 1) {                     Text(stringResource(R.string.card_count_badge, row.cardCount))                 }-                IconButton(onClick = onDelete) { IconDelete() }-                if (dragHandle != null) {-                    IconButton(onClick = {}, modifier = dragHandle) { IconDragHandle() }+                if (!selection.isActive) {+                    if (dragHandle != null) {+                        IconButton(onClick = {}, modifier = dragHandle) { IconDragHandle() }+                    }                 }             }         },-        modifier = Modifier.clickable { onOpen() },+        modifier = Modifier.combinedClickable(onClick = onOpen, onLongClick = onLongPress),+    )+}++@Composable+private fun CustomStudyDialog(+    onStart: (StudyParams) -> Unit,+    onDismiss: () -> Unit,+) {+    var mode by remember { mutableStateOf(com.vayunmathur.flashcards.util.StudyMode.AHEAD) }+    var count by remember { mutableStateOf("20") }+    var days by remember { mutableStateOf("3") }+    com.vayunmathur.library.ui.AlertDialog(+        onDismissRequest = onDismiss,+        title = { Text(stringResource(R.string.custom_study)) },+        text = {+            Column {+                ModeRow(R.string.custom_study_ahead, com.vayunmathur.flashcards.util.StudyMode.AHEAD, mode) { mode = it }+                ModeRow(R.string.custom_study_lapses, com.vayunmathur.flashcards.util.StudyMode.LAPSES, mode) { mode = it }+                ModeRow(R.string.custom_study_new, com.vayunmathur.flashcards.util.StudyMode.NEW_ONLY, mode) { mode = it }+                ModeRow(R.string.custom_study_cram, com.vayunmathur.flashcards.util.StudyMode.CRAM, mode) { mode = it }+                com.vayunmathur.library.ui.OutlinedTextField(+                    value = count,+                    onValueChange = { count = it.filter { c -> c.isDigit() } },+                    label = { Text(stringResource(R.string.custom_study_count)) },+                    singleLine = true,+                    modifier = Modifier.fillMaxWidth().padding(top = 8.dp),+                )+                if (mode == com.vayunmathur.flashcards.util.StudyMode.AHEAD) {+                    com.vayunmathur.library.ui.OutlinedTextField(+                        value = days,+                        onValueChange = { days = it.filter { c -> c.isDigit() } },+                        label = { Text(stringResource(R.string.custom_study_days)) },+                        singleLine = true,+                        modifier = Modifier.fillMaxWidth().padding(top = 8.dp),+                    )+                }+            }+        },+        confirmButton = {+            com.vayunmathur.library.ui.TextButton(onClick = {+                onStart(+                    StudyParams(+                        mode = mode,+                        count = count.toIntOrNull()?.coerceAtLeast(1) ?: 20,+                        daysAhead = days.toIntOrNull()?.coerceAtLeast(1) ?: 3,+                    ),+                )+            }) { Text(stringResource(R.string.start)) }+        },+        dismissButton = {+            com.vayunmathur.library.ui.TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) }+        },+    )+}++@Composable+private fun ModeRow(+    labelRes: Int,+    value: com.vayunmathur.flashcards.util.StudyMode,+    selected: com.vayunmathur.flashcards.util.StudyMode,+    onSelect: (com.vayunmathur.flashcards.util.StudyMode) -> Unit,+) {+    Row(+        Modifier.fillMaxWidth().clickable { onSelect(value) }.padding(vertical = 4.dp),+        verticalAlignment = androidx.compose.ui.Alignment.CenterVertically,+    ) {+        com.vayunmathur.library.ui.RadioButton(selected = selected == value, onClick = { onSelect(value) })+        Text(stringResource(labelRes), modifier = Modifier.padding(start = 8.dp))+    }+}++@Composable+private fun MoveDeckDialog(+    decks: List<DeckOption>,+    onPick: (Long) -> Unit,+    onDismiss: () -> Unit,+) {+    com.vayunmathur.library.ui.AlertDialog(+        onDismissRequest = onDismiss,+        title = { Text(stringResource(R.string.move_to_deck)) },+        text = {+            Column {+                decks.forEach { deck ->+                    Row(+                        Modifier.fillMaxWidth()+                            .clickable { deck.id?.let(onPick) }+                            .padding(vertical = 12.dp),+                    ) {+                        Text(deck.name)+                    }+                }+            }+        },+        confirmButton = {},+        dismissButton = {+            com.vayunmathur.library.ui.TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) }+        },+    )+}++@Composable+private fun TagDialog(+    title: String,+    onConfirm: (String) -> Unit,+    onDismiss: () -> Unit,+) {+    var tag by remember { mutableStateOf("") }+    com.vayunmathur.library.ui.AlertDialog(+        onDismissRequest = onDismiss,+        title = { Text(title) },+        text = {+            com.vayunmathur.library.ui.OutlinedTextField(+                value = tag,+                onValueChange = { tag = it },+                label = { Text(stringResource(R.string.tag_name)) },+                singleLine = true,+                modifier = Modifier.fillMaxWidth(),+            )+        },+        confirmButton = {+            com.vayunmathur.library.ui.TextButton(onClick = { if (tag.isNotBlank()) onConfirm(tag.trim()) }) {+                Text(stringResource(R.string.save))+            }+        },+        dismissButton = {+            com.vayunmathur.library.ui.TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) }+        },     ) } 
flashcards/src/main/java/com/vayunmathur/flashcards/ui/NoteTypeEditorPage.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/ui/NoteTypeEditorPage.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/ui/NoteTypeEditorPage.ktindex 9966f78855..4c328027d8 100644--- a/flashcards/src/main/java/com/vayunmathur/flashcards/ui/NoteTypeEditorPage.kt+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/ui/NoteTypeEditorPage.kt@@ -49,7 +49,8 @@ import com.vayunmathur.library.ui.OutlinedButton import com.vayunmathur.library.ui.OutlinedTextField import com.vayunmathur.library.ui.Text import com.vayunmathur.library.util.NavBackStack-import com.vayunmathur.library.util.parseMarkdown++// -------  // --------------------------------------------------------------------------- // Note type list@@ -346,8 +347,8 @@ private fun TemplatePreview(draft: TemplateDraft, fields: List<String>, isCloze:     )     Column(Modifier.padding(top = 8.dp)) {         Text(stringResource(R.string.preview), style = MaterialTheme.typography.labelMedium)-        Text(parseMarkdown(front, showMarkers = false), style = MaterialTheme.typography.bodyMedium)+        MarkdownContent(text = front, style = MaterialTheme.typography.bodyMedium, textAlign = androidx.compose.ui.text.style.TextAlign.Start)         HorizontalDivider(Modifier.padding(vertical = 6.dp))-        Text(parseMarkdown(back, showMarkers = false), style = MaterialTheme.typography.bodyMedium)+        MarkdownContent(text = back, style = MaterialTheme.typography.bodyMedium, textAlign = androidx.compose.ui.text.style.TextAlign.Start)     } }
flashcards/src/main/java/com/vayunmathur/flashcards/ui/ReviewPage.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/ui/ReviewPage.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/ui/ReviewPage.ktindex ef3fa7da01..5f72cefb0d 100644--- a/flashcards/src/main/java/com/vayunmathur/flashcards/ui/ReviewPage.kt+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/ui/ReviewPage.kt@@ -3,6 +3,7 @@ package com.vayunmathur.flashcards.ui import androidx.compose.animation.core.animateFloatAsState import androidx.compose.animation.core.tween import androidx.compose.foundation.clickable+import androidx.compose.foundation.gestures.detectDragGestures import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column@@ -22,8 +23,14 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.AnnotatedString+import androidx.compose.ui.text.SpanStyle+import androidx.compose.ui.text.buildAnnotatedString+import androidx.compose.ui.text.input.TextFieldValue import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.text.withStyle import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.vayunmathur.flashcards.R@@ -32,6 +39,8 @@ import com.vayunmathur.flashcards.util.FlashcardsViewModel import com.vayunmathur.flashcards.util.Grade import com.vayunmathur.flashcards.util.ReviewActions import com.vayunmathur.flashcards.util.ReviewUiState+import com.vayunmathur.flashcards.util.StudyMode+import com.vayunmathur.flashcards.util.StudyParams import com.vayunmathur.library.ui.AppScaffold import com.vayunmathur.library.ui.Button import com.vayunmathur.library.ui.ButtonDefaults@@ -39,11 +48,14 @@ import com.vayunmathur.library.ui.EmptyState import com.vayunmathur.library.ui.HorizontalDivider import com.vayunmathur.library.ui.IconButton import com.vayunmathur.library.ui.IconUndo+import com.vayunmathur.library.ui.IconVisibilityOff+import com.vayunmathur.library.ui.IconVolumeUp import com.vayunmathur.library.ui.LinearProgressIndicator import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedTextField import com.vayunmathur.library.ui.Text import com.vayunmathur.library.util.NavBackStack-import com.vayunmathur.library.util.parseMarkdown+import kotlin.math.abs  /** Binds an in-memory review session over [deckId] to the stateless [ReviewScreen]. */ @Composable@@ -51,8 +63,19 @@ fun ReviewPage(     backStack: NavBackStack<Route>,     viewModel: FlashcardsViewModel,     deckId: Long,+    mode: Int = 0,+    count: Int = 20,+    daysAhead: Int = 3,+    tags: List<String> = emptyList(), ) {-    LaunchedEffect(deckId) { viewModel.startSession(deckId) }+    LaunchedEffect(deckId, mode, count, daysAhead, tags) {+        val params = StudyParams(+            mode = StudyMode.entries.getOrElse(mode) { StudyMode.DUE },+            count = count,+            daysAhead = daysAhead,+        )+        viewModel.startSession(deckId, params, tags.toSet())+    }     val state by viewModel.review.collectAsStateWithLifecycle()      ReviewScreen(@@ -61,6 +84,8 @@ fun ReviewPage(             override fun back() { backStack.pop() }             override fun grade(grade: Grade) { viewModel.gradeCurrent(grade) }             override fun undo() { viewModel.undoReview() }+            override fun suspend() { viewModel.suspendCurrentCard() }+            override fun speak(text: String) { viewModel.speak(text) }         },     ) }@@ -77,7 +102,19 @@ fun ReviewScreen(     initialRevealed: Boolean = false, ) {     var revealed by remember { mutableStateOf(initialRevealed) }-    LaunchedEffect(state.front, state.done) { revealed = initialRevealed }+    var typed by remember { mutableStateOf(TextFieldValue("")) }+    LaunchedEffect(state.front, state.done) {+        revealed = initialRevealed+        typed = TextFieldValue("")+    }++    // Auto-play: speak the front as each card appears, and the back on reveal.+    LaunchedEffect(state.front) {+        if (state.autoPlay && !state.done && state.front.isNotBlank()) actions.speak(state.front)+    }+    LaunchedEffect(revealed) {+        if (revealed && state.autoPlay && state.back.isNotBlank()) actions.speak(state.back)+    }      AppScaffold(         title = {@@ -95,6 +132,12 @@ fun ReviewScreen(         },         onNavigateBack = { actions.back() },         actions = {+            if (!state.done) {+                IconButton(onClick = { actions.speak(if (revealed) state.back else state.front) }) {+                    IconVolumeUp()+                }+                IconButton(onClick = { actions.suspend() }) { IconVisibilityOff() }+            }             if (state.canUndo) {                 IconButton(onClick = { actions.undo() }) { IconUndo() }             }@@ -118,8 +161,39 @@ fun ReviewScreen(                 front = state.front,                 back = state.back,                 revealed = revealed,-                modifier = Modifier.weight(1f).fillMaxWidth().clickable { revealed = true },+                typeField = state.typeField,+                typeAnswer = state.typeAnswer,+                typed = typed.text,+                modifier = Modifier+                    .weight(1f)+                    .fillMaxWidth()+                    .clickable { revealed = true }+                    .then(+                        if (revealed) {+                            Modifier.pointerInput(state.front) {+                                var total = androidx.compose.ui.geometry.Offset.Zero+                                detectDragGestures(+                                    onDragStart = { total = androidx.compose.ui.geometry.Offset.Zero },+                                    onDrag = { change, delta -> change.consume(); total += delta },+                                    onDragEnd = {+                                        gradeForSwipe(total.x, total.y)?.let(actions::grade)+                                    },+                                )+                            }+                        } else {+                            Modifier+                        },+                    ),             )+            if (state.typeField != null && !revealed) {+                OutlinedTextField(+                    value = typed,+                    onValueChange = { typed = it },+                    label = { Text(stringResource(R.string.type_answer)) },+                    singleLine = true,+                    modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 4.dp),+                )+            }             if (revealed) {                 GradeButtons(state = state, onGrade = { actions.grade(it) })             } else {@@ -134,11 +208,25 @@ fun ReviewScreen(     } } +/** Maps a drag displacement to a grade: left=Again, right=Good, up=Easy, down=Hard. */+private fun gradeForSwipe(dx: Float, dy: Float): Grade? {+    val threshold = 120f+    if (abs(dx) < threshold && abs(dy) < threshold) return null+    return if (abs(dx) > abs(dy)) {+        if (dx < 0) Grade.AGAIN else Grade.GOOD+    } else {+        if (dy < 0) Grade.EASY else Grade.HARD+    }+}+ @Composable private fun FlipCard(     front: String,     back: String,     revealed: Boolean,+    typeField: String?,+    typeAnswer: String?,+    typed: String,     modifier: Modifier = Modifier, ) {     val rotation by animateFloatAsState(@@ -155,26 +243,31 @@ private fun FlipCard(     ) {         if (rotation <= 90f) {             CardFace {-                Text(-                    parseMarkdown(front, showMarkers = false),+                MarkdownContent(+                    text = front,                     style = MaterialTheme.typography.headlineSmall,-                    textAlign = TextAlign.Center,                 )             }         } else {             // Counter-rotate so the back face reads correctly.             Box(Modifier.graphicsLayer { rotationY = 180f }) {                 CardFace {-                    Text(-                        parseMarkdown(front, showMarkers = false),+                    MarkdownContent(+                        text = front,                         style = MaterialTheme.typography.titleMedium,-                        textAlign = TextAlign.Center,                     )+                    if (typeField != null && typeAnswer != null) {+                        HorizontalDivider(Modifier.padding(vertical = 12.dp))+                        Text(+                            diffAnnotated(typed, typeAnswer),+                            style = MaterialTheme.typography.titleMedium,+                            textAlign = TextAlign.Center,+                        )+                    }                     HorizontalDivider(Modifier.padding(vertical = 20.dp))-                    Text(-                        parseMarkdown(back, showMarkers = false),+                    MarkdownContent(+                        text = back,                         style = MaterialTheme.typography.bodyLarge,-                        textAlign = TextAlign.Center,                     )                 }             }@@ -182,6 +275,45 @@ private fun FlipCard(     } } +/**+ * Highlights [typed] against [expected] char-by-char via a longest-common-subsequence:+ * matched characters are green, unmatched typed characters red.+ */+private fun diffAnnotated(typed: String, expected: String): AnnotatedString {+    val n = typed.length+    val m = expected.length+    val lcs = Array(n + 1) { IntArray(m + 1) }+    for (i in n - 1 downTo 0) {+        for (j in m - 1 downTo 0) {+            lcs[i][j] = if (typed[i] == expected[j]) {+                lcs[i + 1][j + 1] + 1+            } else {+                maxOf(lcs[i + 1][j], lcs[i][j + 1])+            }+        }+    }+    val matched = BooleanArray(n)+    var i = 0+    var j = 0+    while (i < n && j < m) {+        when {+            typed[i] == expected[j] -> { matched[i] = true; i++; j++ }+            lcs[i + 1][j] >= lcs[i][j + 1] -> i+++            else -> j+++        }+    }+    val green = SpanStyle(color = Color(0xFF2E7D32))+    val red = SpanStyle(color = Color(0xFFC62828))+    return buildAnnotatedString {+        if (typed.isEmpty()) {+            withStyle(red) { append("—") }+        }+        typed.forEachIndexed { index, c ->+            withStyle(if (matched[index]) green else red) { append(c.toString()) }+        }+    }+}+ @Composable private fun CardFace(content: @Composable () -> Unit) {     Column(
flashcards/src/main/java/com/vayunmathur/flashcards/ui/SettingsPage.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/ui/SettingsPage.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/ui/SettingsPage.ktindex 5b87df2f3d..acbabda3c1 100644--- a/flashcards/src/main/java/com/vayunmathur/flashcards/ui/SettingsPage.kt+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/ui/SettingsPage.kt@@ -33,6 +33,10 @@ import com.vayunmathur.flashcards.util.ThemeMode import com.vayunmathur.library.ui.AlertDialog import com.vayunmathur.library.ui.AppScaffold import com.vayunmathur.library.ui.FilterChip+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconDelete+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedTextField import com.vayunmathur.library.ui.SettingsRow import com.vayunmathur.library.ui.SettingsSection import com.vayunmathur.library.ui.SettingsSwitchRow@@ -47,6 +51,7 @@ import kotlin.math.roundToInt @Composable fun SettingsPage(backStack: NavBackStack<Route>, viewModel: FlashcardsViewModel) {     val settings by viewModel.settings.collectAsStateWithLifecycle()+    val presets by viewModel.deckPresets.collectAsStateWithLifecycle()     val context = LocalContext.current      val permissionLauncher = rememberLauncherForActivityResult(@@ -72,6 +77,7 @@ fun SettingsPage(backStack: NavBackStack<Route>, viewModel: FlashcardsViewModel)         override fun setNewPerDay(value: Int) { viewModel.setNewPerDay(value) }         override fun setMaxReviews(value: Int) { viewModel.setMaxReviews(value) }         override fun setThemeMode(mode: Int) { viewModel.setThemeMode(mode) }+        override fun setAutoPlay(enabled: Boolean) { viewModel.setAutoPlay(enabled) }         override fun setReminderEnabled(enabled: Boolean) {             if (enabled && Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {                 permissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)@@ -81,17 +87,22 @@ fun SettingsPage(backStack: NavBackStack<Route>, viewModel: FlashcardsViewModel)         override fun setReminderTime(hour: Int, minute: Int) {             viewModel.setReminderTime(hour, minute)         }+        override fun saveDeckPreset(name: String) { viewModel.saveDeckPreset(name) }+        override fun applyDeckPreset(name: String) { viewModel.applyDeckPreset(name) }+        override fun deleteDeckPreset(name: String) { viewModel.deleteDeckPreset(name) }+        override fun optimizeFsrs() { viewModel.optimizeAllDecks() }         override fun manageNoteTypes() { backStack.add(Route.NoteTypeList) }         override fun exportCollection() { viewModel.exportApkg(null) }     } -    SettingsScreen(state = settings, actions = actions)+    SettingsScreen(state = settings.copy(presets = presets), actions = actions) }  /** The settings screen. ViewModel-free so previews can render it. */ @Composable fun SettingsScreen(state: SettingsUiState, actions: SettingsActions) {     var showTimePicker by remember { mutableStateOf(false) }+    var showPresetDialog by remember { mutableStateOf(false) }      AppScaffold(         title = stringResource(R.string.nav_settings),@@ -128,6 +139,12 @@ fun SettingsScreen(state: SettingsUiState, actions: SettingsActions) {                     steps = 0,                     onChange = { actions.setMaxReviews((it / 10).roundToInt() * 10) },                 )+                SettingsSwitchRow(+                    title = stringResource(R.string.setting_auto_play),+                    supportingText = stringResource(R.string.setting_auto_play_hint),+                    checked = state.autoPlay,+                    onCheckedChange = { actions.setAutoPlay(it) },+                )             }              SettingsSection(title = stringResource(R.string.settings_reminders)) {@@ -165,10 +182,51 @@ fun SettingsScreen(state: SettingsUiState, actions: SettingsActions) {                     supportingText = stringResource(R.string.export_collection_hint),                     onClick = { actions.exportCollection() },                 )+                SettingsRow(+                    title = stringResource(R.string.optimize_fsrs),+                    supportingText = stringResource(R.string.optimize_fsrs_hint, FSRS_MIN_REVIEWS),+                    onClick = { actions.optimizeFsrs() },+                )+            }++            SettingsSection(title = stringResource(R.string.settings_presets)) {+                SettingsRow(+                    title = stringResource(R.string.save_preset),+                    onClick = { showPresetDialog = true },+                )+                state.presets.forEach { preset ->+                    Row(+                        Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 4.dp),+                        horizontalArrangement = Arrangement.SpaceBetween,+                        verticalAlignment = androidx.compose.ui.Alignment.CenterVertically,+                    ) {+                        Column(Modifier.weight(1f)) {+                            Text(preset.name)+                            Text(+                                "${preset.newPerDay} · ${preset.maxReviews} · ${(preset.desiredRetention * 100).roundToInt()}%",+                                style = MaterialTheme.typography.bodySmall,+                            )+                        }+                        TextButton(onClick = { actions.applyDeckPreset(preset.name) }) {+                            Text(stringResource(R.string.apply_preset))+                        }+                        IconButton(onClick = { actions.deleteDeckPreset(preset.name) }) { IconDelete() }+                    }+                }             }         }     } +    if (showPresetDialog) {+        PresetNameDialog(+            onConfirm = { name ->+                actions.saveDeckPreset(name)+                showPresetDialog = false+            },+            onDismiss = { showPresetDialog = false },+        )+    }+     if (showTimePicker) {         TimePickerDialog(             initialHour = state.reminderHour,@@ -214,6 +272,35 @@ private fun SliderRow(     } } +@Composable+private fun PresetNameDialog(onConfirm: (String) -> Unit, onDismiss: () -> Unit) {+    var name by remember { mutableStateOf("") }+    AlertDialog(+        onDismissRequest = onDismiss,+        title = { Text(stringResource(R.string.save_preset)) },+        text = {+            OutlinedTextField(+                value = name,+                onValueChange = { name = it },+                label = { Text(stringResource(R.string.preset_name)) },+                singleLine = true,+                modifier = Modifier.fillMaxWidth(),+            )+        },+        confirmButton = {+            TextButton(onClick = { if (name.isNotBlank()) onConfirm(name.trim()) }) {+                Text(stringResource(R.string.save))+            }+        },+        dismissButton = {+            TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) }+        },+    )+}++/** Minimum review count before FSRS optimization is meaningful. Mirrors the VM guard. */+private const val FSRS_MIN_REVIEWS = 200+ @Composable private fun TimePickerDialog(     initialHour: Int,
flashcards/src/main/java/com/vayunmathur/flashcards/ui/StatsPage.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/ui/StatsPage.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/ui/StatsPage.ktindex f75171daa9..fdb34088d7 100644--- a/flashcards/src/main/java/com/vayunmathur/flashcards/ui/StatsPage.kt+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/ui/StatsPage.kt@@ -71,6 +71,34 @@ fun StatsPage(backStack: NavBackStack<Route>, viewModel: FlashcardsViewModel) {      val deckCards = if (selectedDeckId == null) cards else cards.filter { it.deckId == selectedDeckId } +    // Cards becoming due per day over the next 30 days (overdue lumped into today).+    val forecast = (0 until 30).map { offset ->+        val day = today + offset+        val count = deckCards.count { card ->+            if (card.isNew || card.isSuspended) return@count false+            val due = java.time.Instant.ofEpochMilli(card.dueDate).atZone(zone).toLocalDate().toEpochDay()+            if (offset == 0) due <= day else due == day+        }+        DailyStat(day, count)+    }++    // Pass rate bucketed by the elapsed interval at review time.+    val buckets = listOf(+        "≤1" to 1.0,+        "2–3" to 3.0,+        "4–7" to 7.0,+        "8–14" to 14.0,+        "15–30" to 30.0,+        "31+" to Double.MAX_VALUE,+    )+    var lower = 0.0+    val retentionBuckets = buckets.map { (label, upper) ->+        val inBucket = recalls.filter { it.elapsedDays > lower && it.elapsedDays <= upper }+        lower = upper+        val rate = if (inBucket.isEmpty()) 0f else inBucket.count { it.grade > 1 }.toFloat() / inBucket.size+        label to rate+    }+     StatsScreen(         state = StatsUiState(             deckOptions = deckOptions,@@ -81,6 +109,9 @@ fun StatsPage(backStack: NavBackStack<Route>, viewModel: FlashcardsViewModel) {             streakDays = streak,             matureCards = deckCards.count { it.state == CardState.REVIEW },             totalCards = deckCards.size,+            forecast = forecast,+            retentionBuckets = retentionBuckets,+            heatmap = daily,         ),         actions = object : StatsActions {             override fun back() { backStack.pop() }@@ -144,10 +175,47 @@ fun StatsScreen(state: StatsUiState, actions: StatsActions) {                     modifier = Modifier.fillMaxWidth().padding(16.dp),                 )             }++            ChartSection(stringResource(R.string.stat_heatmap)) {+                ReviewHeatmap(+                    days = state.heatmap,+                    modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp),+                )+            }++            if (state.forecast.any { it.count > 0 }) {+                ChartSection(stringResource(R.string.stat_forecast)) {+                    ReviewBarChart(+                        data = state.forecast.map {+                            LocalDate.ofEpochDay(it.epochDay).dayOfMonth.toString() to it.count.toDouble()+                        },+                        modifier = Modifier.fillMaxWidth().padding(16.dp),+                    )+                }+            }++            if (state.retentionBuckets.any { it.second > 0f }) {+                ChartSection(stringResource(R.string.stat_retention_by_interval)) {+                    ReviewBarChart(+                        data = state.retentionBuckets.map { it.first to (it.second * 100).toDouble() },+                        modifier = Modifier.fillMaxWidth().padding(16.dp),+                    )+                }+            }         }     } } +@Composable+private fun ChartSection(title: String, content: @Composable () -> Unit) {+    Text(+        title,+        style = MaterialTheme.typography.titleMedium,+        modifier = Modifier.padding(start = 16.dp, top = 8.dp, end = 16.dp),+    )+    content()+}+ @Composable private fun SummaryRow(state: StatsUiState) {     Row(
flashcards/src/main/java/com/vayunmathur/flashcards/util/ApkgExport.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/util/ApkgExport.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/util/ApkgExport.ktindex c383e4802b..afa0195bfc 100644--- a/flashcards/src/main/java/com/vayunmathur/flashcards/util/ApkgExport.kt+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/util/ApkgExport.kt@@ -43,14 +43,35 @@ object ApkgExport {         } finally {             db.close()         }-        File(work, "media").writeText("{}")++        // Copy referenced images as numbered entries and build the media manifest.+        val mediaStore = MediaStore(context)+        val referenced = notes.flatMap { MediaStore.referenced(it.flds) }.distinct()+        val mediaMap = JSONObject()+        val mediaFiles = mutableListOf<File>()+        var mediaIndex = 0+        referenced.forEach { fileName ->+            val src = mediaStore.resolve(fileName)+            if (src.exists()) {+                val dest = File(work, mediaIndex.toString())+                src.copyTo(dest, overwrite = true)+                mediaMap.put(mediaIndex.toString(), fileName)+                mediaFiles.add(dest)+                mediaIndex+++            }+        }+        File(work, "media").writeText(mediaMap.toString())          val outDir = File(context.cacheDir, "shared_decks").apply { mkdirs() }         val safeName = name.ifBlank { "collection" }.replace(Regex("[^A-Za-z0-9._-]"), "_")         val apkg = File(outDir, "$safeName.apkg")         if (apkg.exists()) apkg.delete()         apkg.outputStream().use { out ->-            BackupHelper.zipFiles(listOf(File(work, "collection.anki2"), File(work, "media")), work, out)+            BackupHelper.zipFiles(+                listOf(File(work, "collection.anki2"), File(work, "media")) + mediaFiles,+                work,+                out,+            )         }         work.deleteRecursively()         return apkg
flashcards/src/main/java/com/vayunmathur/flashcards/util/ApkgImport.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/util/ApkgImport.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/util/ApkgImport.ktindex 2a46656d81..c0be241172 100644--- a/flashcards/src/main/java/com/vayunmathur/flashcards/util/ApkgImport.kt+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/util/ApkgImport.kt@@ -65,7 +65,9 @@ object ApkgImport {              val db = SQLiteDatabase.openDatabase(anki2.absolutePath, null, SQLiteDatabase.OPEN_READONLY)             try {-                return importCollection(db, deckDao, noteTypeDao, fieldDao, templateDao, noteDao, cardDao)+                val result = importCollection(db, deckDao, noteTypeDao, fieldDao, templateDao, noteDao, cardDao)+                importMedia(context, work)+                return result             } finally {                 db.close()             }@@ -74,6 +76,28 @@ object ApkgImport {         }     } +    /**+     * Copies numbered media entries out of the unzipped [work] dir into the app's+     * `filesDir/media`, using the names from the `media` JSON manifest so that the+     * `<img src="name">` → `![](name)` conversion resolves. Existing files with the+     * same name are overwritten (imports normally land in a fresh media dir).+     */+    private fun importMedia(context: Context, work: File) {+        val manifest = File(work, "media")+        if (!manifest.exists()) return+        val map = runCatching { JSONObject(manifest.readText()) }.getOrNull() ?: return+        val store = MediaStore(context)+        val keys = map.keys()+        while (keys.hasNext()) {+            val key = keys.next()+            val name = map.optString(key)+            val src = File(work, key)+            if (name.isNotBlank() && src.exists()) {+                runCatching { store.resolve(name).writeBytes(src.readBytes()) }+            }+        }+    }+     private suspend fun importCollection(         db: SQLiteDatabase,         deckDao: DeckDao,
flashcards/src/main/java/com/vayunmathur/flashcards/util/DeckIo.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/util/DeckIo.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/util/DeckIo.ktindex b0e8e86119..4b1dfd91cb 100644--- a/flashcards/src/main/java/com/vayunmathur/flashcards/util/DeckIo.kt+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/util/DeckIo.kt@@ -3,6 +3,24 @@ package com.vayunmathur.flashcards.util /** CSV import for bulk note creation. Per-deck sharing now uses `.apkg` (see [ApkgExport]). */ object DeckIo { +    /**+     * Serializes notes to `front,back` CSV. [rows] are (front, back) pairs already+     * stripped of HTML/markers by the caller. A header row is written first.+     */+    fun writeCsv(rows: List<Pair<String, String>>): String {+        val sb = StringBuilder("front,back\n")+        rows.forEach { (front, back) ->+            sb.append(escapeCsv(front)).append(',').append(escapeCsv(back)).append('\n')+        }+        return sb.toString()+    }++    private fun escapeCsv(field: String): String {+        val needsQuoting = field.contains(',') || field.contains('"') || field.contains('\n')+        if (!needsQuoting) return field+        return "\"" + field.replace("\"", "\"\"") + "\""+    }+     /**      * Parses CSV text into (front, back) pairs. Accepts two columns per row; a      * standard-quoted first line of `front,back` is skipped as a header. Handles
flashcards/src/main/java/com/vayunmathur/flashcards/util/FlashcardsUiContract.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/util/FlashcardsUiContract.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/util/FlashcardsUiContract.ktindex a0f3251e8a..85f02a42c8 100644--- a/flashcards/src/main/java/com/vayunmathur/flashcards/util/FlashcardsUiContract.kt+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/util/FlashcardsUiContract.kt@@ -55,6 +55,8 @@ interface DeckListActions { data class NoteRow(     val note: Note,     val cardCount: Int = 1,+    /** True when every card of this note is suspended. */+    val suspended: Boolean = false, )  /** Everything the note list draws for a single deck. */@@ -62,6 +64,10 @@ data class NoteListUiState(     val deckName: String = "",     val notes: List<NoteRow> = emptyList(),     val dueCount: Int = 0,+    /** Distinct tags across the deck's notes, for the filter row. */+    val tags: List<String> = emptyList(),+    /** Decks available as move-to targets (excludes the current deck). */+    val decks: List<DeckOption> = emptyList(), )  interface NoteListActions {@@ -69,10 +75,19 @@ interface NoteListActions {     fun openNote(id: Long) {}     fun addNote() {}     fun deleteNote(note: Note) {}-    fun study() {}+    fun study(tags: Set<String>) {}+    fun customStudy(params: StudyParams, tags: Set<String>) {}     fun reorder(notes: List<Note>) {}     fun openStats() {}     fun share() {}+    fun exportCsv() {}+    // Bulk (selection-mode) actions, operating on a set of note ids.+    fun deleteNotes(ids: List<Long>) {}+    fun moveNotes(ids: List<Long>, deckId: Long) {}+    fun addTag(ids: List<Long>, tag: String) {}+    fun removeTag(ids: List<Long>, tag: String) {}+    fun setSuspended(ids: List<Long>, suspended: Boolean) {}+    fun resetScheduling(ids: List<Long>) {}      companion object {         val Noop: NoteListActions = object : NoteListActions {}@@ -98,6 +113,7 @@ data class NoteEditUiState(     val initialFieldValues: List<String> = emptyList(),     val initialTags: String = "",     val isNew: Boolean = true,+    val isSuspended: Boolean = false,     val noteTypes: List<NoteTypeConfig> = emptyList(),     val decks: List<DeckOption> = emptyList(), )@@ -106,6 +122,8 @@ interface NoteEditActions {     fun back() {}     fun save(noteTypeId: Long, deckId: Long, fieldValues: List<String>, tags: String) {}     fun deleteNote() {}+    fun setSuspended(suspended: Boolean) {}+    fun insertImage(fieldIndex: Int) {}      companion object {         val Noop: NoteEditActions = object : NoteEditActions {}@@ -181,6 +199,34 @@ data class NoteTypeWithConfig( // Review session // --------------------------------------------------------------------------- +/** The kind of study session to build (custom study / cram). */+enum class StudyMode {+    /** Normal: due review cards + capped new cards. */+    DUE,++    /** Include review cards due within [StudyParams.daysAhead] days. */+    AHEAD,++    /** Only cards that have lapsed (relearning or lapses > 0). */+    LAPSES,++    /** Only new cards. */+    NEW_ONLY,++    /** Ignore due dates; take [StudyParams.count] cards by position, no schedule writes. */+    CRAM,+}++/** Parameters for a custom study session. */+data class StudyParams(+    val mode: StudyMode = StudyMode.DUE,+    val count: Int = 20,+    val daysAhead: Int = 3,+) {+    /** True when grading must not persist scheduling changes to cards. */+    val previewOnly: Boolean get() = mode == StudyMode.CRAM+}+ /** Everything a review session draws for the current card. */ data class ReviewUiState(     val front: String = "",@@ -196,6 +242,12 @@ data class ReviewUiState(     /** Predicted next-interval label per grade button (e.g. "10m", "4d"). */     val intervalLabels: Map<Grade, String> = emptyMap(),     val canUndo: Boolean = false,+    /** The field name a `{{type:Field}}` template expects, or null when not a type-in card. */+    val typeField: String? = null,+    /** The expected answer for a `{{type:Field}}` card, shown after reveal. */+    val typeAnswer: String? = null,+    /** When true, the front is read aloud automatically as each card appears. */+    val autoPlay: Boolean = false, ) {     fun label(grade: Grade): String = intervalLabels[grade] ?: "" }@@ -204,6 +256,8 @@ interface ReviewActions {     fun back() {}     fun grade(grade: Grade) {}     fun undo() {}+    fun suspend() {}+    fun speak(text: String) {}      companion object {         val Noop: ReviewActions = object : ReviewActions {}@@ -230,6 +284,12 @@ data class StatsUiState(     val streakDays: Int = 0,     val matureCards: Int = 0,     val totalCards: Int = 0,+    /** Cards becoming due per day over the next ~30 days. */+    val forecast: List<DailyStat> = emptyList(),+    /** Pass rate (0..1) bucketed by the elapsed interval at review time. */+    val retentionBuckets: List<Pair<String, Float>> = emptyList(),+    /** Daily review counts for the activity heatmap (~26 weeks). */+    val heatmap: List<DailyStat> = emptyList(), )  interface StatsActions {@@ -251,6 +311,14 @@ object ThemeMode {     const val DARK = 2 } +/** A named bundle of per-deck study settings, saved/applied from Settings. */+data class DeckPreset(+    val name: String,+    val newPerDay: Int,+    val maxReviews: Int,+    val desiredRetention: Double,+)+ data class SettingsUiState(     val desiredRetention: Double = 0.9,     val newPerDay: Int = 20,@@ -259,6 +327,10 @@ data class SettingsUiState(     val reminderHour: Int = 20,     val reminderMinute: Int = 0,     val themeMode: Int = ThemeMode.SYSTEM,+    val autoPlay: Boolean = false,+    val presets: List<DeckPreset> = emptyList(),+    /** True when the deck has enough review history for FSRS optimization. */+    val canOptimize: Boolean = false, )  interface SettingsActions {@@ -269,6 +341,11 @@ interface SettingsActions {     fun setReminderEnabled(enabled: Boolean) {}     fun setReminderTime(hour: Int, minute: Int) {}     fun setThemeMode(mode: Int) {}+    fun setAutoPlay(enabled: Boolean) {}+    fun saveDeckPreset(name: String) {}+    fun applyDeckPreset(name: String) {}+    fun deleteDeckPreset(name: String) {}+    fun optimizeFsrs() {}     fun manageNoteTypes() {}     fun exportCollection() {} 
flashcards/src/main/java/com/vayunmathur/flashcards/util/FlashcardsViewModel.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/util/FlashcardsViewModel.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/util/FlashcardsViewModel.ktindex 42b584f5fb..4807496a2e 100644--- a/flashcards/src/main/java/com/vayunmathur/flashcards/util/FlashcardsViewModel.kt+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/util/FlashcardsViewModel.kt@@ -7,6 +7,7 @@ import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewModelScope+import com.vayunmathur.flashcards.R import com.vayunmathur.flashcards.data.Card import com.vayunmathur.flashcards.data.CardDao import com.vayunmathur.flashcards.data.CardState@@ -24,6 +25,7 @@ import com.vayunmathur.flashcards.data.NoteTypeFieldDao import com.vayunmathur.flashcards.data.NoteTypeKind import com.vayunmathur.flashcards.data.ReviewLog import com.vayunmathur.flashcards.data.ReviewLogDao+import com.vayunmathur.library.util.AppMessages import com.vayunmathur.library.util.DataStoreUtils import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow@@ -34,6 +36,7 @@ import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.combine+import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch import kotlinx.coroutines.withContext@@ -112,6 +115,9 @@ class FlashcardsViewModel(     }         .combine(ds.booleanFlow(KEY_REMINDER_ENABLED)) { core, enabled -> core to enabled }         .combine(ds.longFlow(KEY_REMINDER_MINUTES, 20L * 60)) { (core, enabled), minutes ->+            Triple(core, enabled, minutes)+        }+        .combine(ds.booleanFlow(KEY_AUTO_PLAY)) { (core, enabled, minutes), autoPlay ->             SettingsUiState(                 desiredRetention = (core[0] as Double).takeIf { it > 0.0 } ?: 0.9,                 newPerDay = (core[1] as Long).toInt(),@@ -120,6 +126,7 @@ class FlashcardsViewModel(                 reminderEnabled = enabled,                 reminderHour = (minutes / 60).toInt(),                 reminderMinute = (minutes % 60).toInt(),+                autoPlay = autoPlay,             )         }         .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), SettingsUiState())@@ -133,6 +140,80 @@ class FlashcardsViewModel(      fun setThemeMode(mode: Int) = launchIo { ds.setLong(KEY_THEME_MODE, mode.toLong()) } +    fun setAutoPlay(enabled: Boolean) = launchIo { ds.setBoolean(KEY_AUTO_PLAY, enabled) }++    // -- Deck presets ------------------------------------------------------++    val deckPresets: StateFlow<List<DeckPreset>> = ds.stringFlow(KEY_DECK_PRESETS)+        .map { parsePresets(it) }+        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())++    /** Saves the current study settings under [name] as a reusable preset. */+    fun saveDeckPreset(name: String) = launchIo {+        val clean = name.trim()+        if (clean.isEmpty()) return@launchIo+        val s = settings.value+        val map = parsePresets(ds.getString(KEY_DECK_PRESETS).orEmpty())+            .associateBy { it.name }+            .toMutableMap()+        map[clean] = DeckPreset(clean, s.newPerDay, s.maxReviews, s.desiredRetention)+        ds.setString(KEY_DECK_PRESETS, presetsToJson(map.values.toList()))+        AppMessages.show(getApplication<Application>().getString(R.string.preset_saved))+    }++    /** Applies preset [name] to the global defaults and every existing deck. */+    fun applyDeckPreset(name: String) = launchIo {+        val preset = parsePresets(ds.getString(KEY_DECK_PRESETS).orEmpty())+            .firstOrNull { it.name == name } ?: return@launchIo+        ds.setLong(KEY_NEW_PER_DAY, preset.newPerDay.toLong())+        ds.setLong(KEY_MAX_REVIEWS, preset.maxReviews.toLong())+        ds.setDouble(KEY_RETENTION, preset.desiredRetention)+        deckDao.getAll().forEach { deck ->+            deckDao.upsert(+                deck.copy(+                    newPerDay = preset.newPerDay,+                    maxReviewsPerDay = preset.maxReviews,+                    desiredRetention = preset.desiredRetention,+                ),+            )+        }+        AppMessages.show(getApplication<Application>().getString(R.string.preset_applied))+    }++    fun deleteDeckPreset(name: String) = launchIo {+        val remaining = parsePresets(ds.getString(KEY_DECK_PRESETS).orEmpty()).filterNot { it.name == name }+        ds.setString(KEY_DECK_PRESETS, presetsToJson(remaining))+    }++    // -- FSRS optimization -------------------------------------------------++    /**+     * Runs the pragmatic [FsrsOptimizer] on every deck with enough review history,+     * saving the tuned weights per deck. Reports the outcome via [AppMessages].+     */+    fun optimizeAllDecks() = launchIo {+        val ctx = getApplication<Application>()+        var optimizedReviews = 0+        var optimizedDecks = 0+        var mostReviews = 0+        deckDao.getAll().forEach { deck ->+            val logs = reviewLogDao.getByDeckOrdered(deck.id)+            mostReviews = maxOf(mostReviews, logs.size)+            val byCard = logs.groupBy { it.cardId }.values.toList()+            if (FsrsOptimizer.hasEnough(byCard)) {+                val weights = withContext(Dispatchers.Default) { FsrsOptimizer.optimize(byCard) }+                deckDao.upsert(deck.copy(fsrsWeights = Scheduler.weightsToJson(weights)))+                optimizedReviews += logs.size+                optimizedDecks+++            }+        }+        if (optimizedDecks > 0) {+            AppMessages.show(ctx.getString(R.string.optimize_fsrs_done, optimizedReviews))+        } else {+            AppMessages.show(ctx.getString(R.string.optimize_fsrs_too_few, mostReviews, FsrsOptimizer.MIN_REVIEWS))+        }+    }+     fun setReminderEnabled(enabled: Boolean) = launchIo {         ds.setBoolean(KEY_REMINDER_ENABLED, enabled)         val current = settings.value@@ -161,10 +242,25 @@ class FlashcardsViewModel(     }      fun deleteDeck(deck: Deck) = launchIo {+        val notes = noteDao.getByDeck(deck.id)+        val cards = cardDao.getByDeck(deck.id)+        val logs = reviewLogDao.getByDeckOrdered(deck.id)         cardDao.deleteByDeck(deck.id)         noteDao.deleteByDeck(deck.id)         reviewLogDao.deleteByDeck(deck.id)         deckDao.delete(deck)+        AppMessages.show(+            getApplication<Application>().getString(R.string.deleted),+            actionLabel = getApplication<Application>().getString(R.string.undo),+            duration = AppMessages.Duration.Long,+        ) {+            launchIo {+                deckDao.upsert(deck)+                if (notes.isNotEmpty()) noteDao.upsertAll(notes)+                if (cards.isNotEmpty()) cardDao.upsertAll(cards)+                logs.forEach { reviewLogDao.insert(it) }+            }+        }     }      fun reorderDecks(decks: List<Deck>) = launchIo { decks.forEach { deckDao.upsert(it) } }@@ -206,12 +302,154 @@ class FlashcardsViewModel(     }      fun deleteNote(note: Note) = launchIo {+        val cards = cardDao.getByNote(note.id)+        val logs = cards.flatMap { reviewLogDao.getByCard(it.id) }         cardDao.deleteByNote(note.id)+        if (cards.isNotEmpty()) reviewLogDao.deleteByCards(cards.map { it.id })         noteDao.delete(note)+        AppMessages.show(+            getApplication<Application>().getString(R.string.deleted),+            actionLabel = getApplication<Application>().getString(R.string.undo),+            duration = AppMessages.Duration.Long,+        ) {+            launchIo {+                noteDao.upsert(note)+                if (cards.isNotEmpty()) cardDao.upsertAll(cards)+                logs.forEach { reviewLogDao.insert(it) }+            }+        }+    }++    /** Suspends or unsuspends every card of [noteId], and tracks the leech tag. */+    fun setNoteSuspended(noteId: Long, suspended: Boolean) = launchIo {+        cardDao.setSuspendedByNotes(listOf(noteId), if (suspended) 1 else 0)+    }++    /** Suspends the card currently shown in the review session and advances. */+    fun suspendCurrentCard() = launchIo {+        val s = session ?: return@launchIo+        val card = s.removeCurrent() ?: return@launchIo+        cardDao.setSuspended(listOf(card.id), 1)+        publishReview()     }      fun reorderNotes(notes: List<Note>) = launchIo { noteDao.upsertAll(notes) } +    // -- Bulk note operations ---------------------------------------------++    /** Deletes multiple notes (and their cards/logs) with a single undo action. */+    fun deleteNotes(noteIds: List<Long>) = launchIo {+        if (noteIds.isEmpty()) return@launchIo+        val notes = noteDao.getByIds(noteIds)+        val cards = cardDao.getByNotes(noteIds)+        val logs = cards.flatMap { reviewLogDao.getByCard(it.id) }+        cardDao.deleteByNotes(noteIds)+        if (cards.isNotEmpty()) reviewLogDao.deleteByCards(cards.map { it.id })+        noteDao.deleteByIds(noteIds)+        AppMessages.show(+            getApplication<Application>().getString(R.string.deleted),+            actionLabel = getApplication<Application>().getString(R.string.undo),+            duration = AppMessages.Duration.Long,+        ) {+            launchIo {+                noteDao.upsertAll(notes)+                if (cards.isNotEmpty()) cardDao.upsertAll(cards)+                logs.forEach { reviewLogDao.insert(it) }+            }+        }+    }++    /** Moves notes (and their cards) to another deck. */+    fun moveNotes(noteIds: List<Long>, deckId: Long) = launchIo {+        if (noteIds.isEmpty()) return@launchIo+        val notes = noteDao.getByIds(noteIds)+        var position = noteDao.getByDeck(deckId).maxOfOrNull { it.position } ?: 0.0+        val moved = notes.map { note ->+            position += 1.0+            note.copy(deckId = deckId, position = position)+        }+        noteDao.upsertAll(moved)+        cardDao.moveByNotes(noteIds, deckId)+    }++    fun addTag(noteIds: List<Long>, tag: String) = launchIo {+        val clean = tag.trim()+        if (clean.isEmpty() || noteIds.isEmpty()) return@launchIo+        val updated = noteDao.getByIds(noteIds).map { note ->+            val tags = note.tags.split(" ").filter { it.isNotBlank() }.toMutableSet()+            tags.add(clean)+            note.copy(tags = tags.joinToString(" "))+        }+        noteDao.upsertAll(updated)+    }++    fun removeTag(noteIds: List<Long>, tag: String) = launchIo {+        val clean = tag.trim()+        if (clean.isEmpty() || noteIds.isEmpty()) return@launchIo+        val updated = noteDao.getByIds(noteIds).map { note ->+            val tags = note.tags.split(" ").filter { it.isNotBlank() && it != clean }+            note.copy(tags = tags.joinToString(" "))+        }+        noteDao.upsertAll(updated)+    }++    fun setNotesSuspended(noteIds: List<Long>, suspended: Boolean) = launchIo {+        if (noteIds.isEmpty()) return@launchIo+        cardDao.setSuspendedByNotes(noteIds, if (suspended) 1 else 0)+    }++    /** Resets scheduling for every card of the given notes back to new. */+    fun resetSchedulingForNotes(noteIds: List<Long>) = launchIo {+        if (noteIds.isEmpty()) return@launchIo+        val cards = cardDao.getByNotes(noteIds)+        resetCards(cards)+    }++    /** Resets scheduling for every card in a deck back to new. */+    fun resetSchedulingForDeck(deckId: Long) = launchIo {+        resetCards(cardDao.getByDeck(deckId))+    }++    private suspend fun resetCards(cards: List<Card>) {+        if (cards.isEmpty()) return+        cardDao.upsertAll(+            cards.map {+                it.copy(+                    state = CardState.NEW,+                    stability = 0.0,+                    difficulty = 0.0,+                    reps = 0,+                    lapses = 0,+                    dueDate = 0,+                    lastReview = 0,+                )+            },+        )+        reviewLogDao.deleteByCards(cards.map { it.id })+    }++    /** Exports a deck's notes as `front,back` CSV and shares it. */+    fun exportCsv(deckId: Long) = launchIo {+        val context = getApplication<Application>()+        val notes = noteDao.getByDeck(deckId).sortedBy { it.position }+        val rows = notes.map { note ->+            val fields = note.fieldList+            stripText(fields.getOrNull(0).orEmpty()) to stripText(fields.getOrNull(1).orEmpty())+        }+        val uri = withContext(Dispatchers.IO) {+            val dir = java.io.File(context.cacheDir, "shared_decks").apply { mkdirs() }+            val deck = deckDao.getById(deckId)+            val safe = (deck?.name ?: "deck").replace(Regex("[^A-Za-z0-9._-]"), "_")+            val file = java.io.File(dir, "$safe.csv")+            file.writeText(DeckIo.writeCsv(rows))+            FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", file)+        }+        _shareRequests.emit(uri)+    }++    private fun stripText(md: String): String =+        Regex("<[^>]+>").replace(md, "").replace("\n", " ").trim()+     // -- Note type CRUD ----------------------------------------------------      fun saveNoteType(@@ -262,13 +500,29 @@ class FlashcardsViewModel(     private var session: ReviewSession? = null     private var lastLogId: Long? = null     private var sessionNotes: Map<Long, Note> = emptyMap()+    private var sessionDeck: Deck? = null     private val _review = MutableStateFlow(ReviewUiState())     val review: StateFlow<ReviewUiState> = _review.asStateFlow() -    fun startSession(deckId: Long) = launchIo {+    fun startSession(+        deckId: Long,+        params: StudyParams = StudyParams(),+        tagFilter: Set<String> = emptySet(),+    ) = launchIo {         val deck = deckDao.getById(deckId) ?: return@launchIo-        val cards = cardDao.getByDeck(deckId)-        sessionNotes = noteDao.getByDeck(deckId).associateBy { it.id }+        val notes = noteDao.getByDeck(deckId)+        sessionNotes = notes.associateBy { it.id }+        sessionDeck = deck+        val allCards = cardDao.getByDeck(deckId)+        val cards = if (tagFilter.isEmpty()) {+            allCards+        } else {+            val allowedNoteIds = notes+                .filter { note -> note.tags.split(" ").any { it in tagFilter } }+                .map { it.id }+                .toSet()+            allCards.filter { it.noteId in allowedNoteIds }+        }         val now = System.currentTimeMillis()         session = ReviewSession(             cards = cards,@@ -276,6 +530,8 @@ class FlashcardsViewModel(             maxReviews = deck.maxReviewsPerDay,             now = now,             desiredRetention = deck.desiredRetention,+            weights = Scheduler.parseWeights(deck.fsrsWeights),+            params = params,         )         lastLogId = null         publishReview()@@ -286,8 +542,15 @@ class FlashcardsViewModel(         val original = s.current ?: return@launchIo         val now = System.currentTimeMillis()         val prevLastReview = original.lastReview+        val wasReview = original.state == CardState.REVIEW         val updated = s.grade(grade, now) ?: return@launchIo+        // Cram mode is preview-only: don't persist scheduling or a review log.+        if (s.previewOnly) {+            publishReview()+            return@launchIo+        }         cardDao.upsert(updated)+        maybeMarkLeech(updated, grade, wasReview)         val elapsedDays =             if (prevLastReview > 0) (now - prevLastReview).toDouble() / Scheduler.DAY_MS else 0.0         val scheduledDays = (updated.dueDate - now).toDouble() / Scheduler.DAY_MS@@ -305,6 +568,24 @@ class FlashcardsViewModel(         publishReview()     } +    /**+     * Auto-suspends a card the first time it reaches `leechThreshold` lapses (Anki's+     * leech behaviour): tags its note, evicts the just-re-queued copy from the+     * in-session queue, and surfaces a message. Only fires on the crossing lapse.+     */+    private suspend fun maybeMarkLeech(updated: Card, grade: Grade, wasReview: Boolean) {+        val threshold = sessionDeck?.leechThreshold ?: 0+        if (threshold <= 0 || grade != Grade.AGAIN || !wasReview) return+        if (updated.lapses != threshold) return+        cardDao.setSuspended(listOf(updated.id), 1)+        session?.removeFromQueue(updated.id)+        val note = noteDao.getById(updated.noteId)+        if (note != null && !note.tags.split(" ").contains(LEECH_TAG)) {+            noteDao.upsert(note.copy(tags = (note.tags + " " + LEECH_TAG).trim()))+        }+        AppMessages.show(getApplication<Application>().getString(R.string.leech_suspended))+    }+     fun undoReview() = launchIo {         val s = session ?: return@launchIo         val restored = s.undo() ?: return@launchIo@@ -316,6 +597,32 @@ class FlashcardsViewModel(         publishReview()     } +    // -- Text-to-speech ----------------------------------------------------++    private var tts: TtsSpeaker? = null++    /** Speaks [text] aloud (markdown/HTML stripped). No-op on blank. */+    fun speak(text: String) {+        val clean = Regex("<[^>]+>").replace(text, "")+            .replace(Regex("""[*_`#>\[\]]"""), "")+            .trim()+        if (clean.isEmpty()) return+        val speaker = tts ?: TtsSpeaker(getApplication()).also { tts = it }+        speaker.speak(clean)+    }++    override fun onCleared() {+        tts?.shutdown()+        super.onCleared()+    }++    private data class RenderedCard(+        val front: String,+        val back: String,+        val typeField: String?,+        val typeAnswer: String?,+    )+     private fun publishReview() {         val s = session         _review.value = if (s == null) {@@ -323,10 +630,11 @@ class FlashcardsViewModel(         } else {             val now = System.currentTimeMillis()             val current = s.current-            val (front, back) = current?.let { renderCard(it) } ?: ("" to "")+            val rendered = current?.let { renderCard(it) }+                ?: RenderedCard("", "", null, null)             ReviewUiState(-                front = front,-                back = back,+                front = rendered.front,+                back = rendered.back,                 remaining = s.remaining,                 done = s.done,                 newCount = s.newCount,@@ -335,25 +643,29 @@ class FlashcardsViewModel(                 progress = s.progress,                 intervalLabels = s.previewLabels(now),                 canUndo = s.canUndo,+                typeField = rendered.typeField,+                typeAnswer = rendered.typeAnswer,+                autoPlay = settings.value.autoPlay,             )         }     } -    /** Renders a card's (front, back) markdown from its note and template. */-    private fun renderCard(card: Card): Pair<String, String> {-        val note = sessionNotes[card.noteId] ?: return "" to ""+    /** Renders a card's markdown (+ any type-in field) from its note and template. */+    private fun renderCard(card: Card): RenderedCard {+        val note = sessionNotes[card.noteId] ?: return RenderedCard("", "", null, null)         val cfg = noteTypes.value.firstOrNull { it.noteType.id == note.noteTypeId }-            ?: return note.sortField to ""+            ?: return RenderedCard(note.sortField, "", null, null)         val values = note.fieldValues(cfg.fields)-        return if (cfg.noteType.type == NoteTypeKind.CLOZE) {-            val template = cfg.templates.firstOrNull() ?: return note.sortField to ""-            TemplateEngine.render(template.qfmt, template.afmt, values, clozeOrd = card.templateOrd)+        val template = if (cfg.noteType.type == NoteTypeKind.CLOZE) {+            cfg.templates.firstOrNull()         } else {-            val template = cfg.templates.firstOrNull { it.ord == card.templateOrd }-                ?: cfg.templates.firstOrNull()-                ?: return note.sortField to ""-            TemplateEngine.render(template.qfmt, template.afmt, values, clozeOrd = null)-        }+            cfg.templates.firstOrNull { it.ord == card.templateOrd } ?: cfg.templates.firstOrNull()+        } ?: return RenderedCard(note.sortField, "", null, null)+        val clozeOrd = if (cfg.noteType.type == NoteTypeKind.CLOZE) card.templateOrd else null+        val (front, back) = TemplateEngine.render(template.qfmt, template.afmt, values, clozeOrd)+        val typeField = TemplateEngine.typeField(template.qfmt)+        val typeAnswer = typeField?.let { values[it] }+        return RenderedCard(front, back, typeField, typeAnswer)     }      // -- Import / export / share ------------------------------------------@@ -467,6 +779,37 @@ class FlashcardsViewModel(     private fun launchIo(block: suspend () -> Unit) =         viewModelScope.launch(Dispatchers.IO) { block() } +    private fun parsePresets(json: String): List<DeckPreset> {+        if (json.isBlank()) return emptyList()+        return runCatching {+            val arr = org.json.JSONArray(json)+            (0 until arr.length()).map { i ->+                val o = arr.getJSONObject(i)+                DeckPreset(+                    name = o.optString("name"),+                    newPerDay = o.optInt("newPerDay", 20),+                    maxReviews = o.optInt("maxReviews", 200),+                    desiredRetention = o.optDouble("desiredRetention", 0.9),+                )+            }+        }.getOrDefault(emptyList())+    }++    private fun presetsToJson(presets: List<DeckPreset>): String {+        val arr = org.json.JSONArray()+        presets.forEach { p ->+            arr.put(+                org.json.JSONObject().apply {+                    put("name", p.name)+                    put("newPerDay", p.newPerDay)+                    put("maxReviews", p.maxReviews)+                    put("desiredRetention", p.desiredRetention)+                },+            )+        }+        return arr.toString()+    }+     companion object {         const val KEY_RETENTION = "desired_retention"         const val KEY_NEW_PER_DAY = "new_per_day"@@ -474,10 +817,15 @@ class FlashcardsViewModel(         const val KEY_THEME_MODE = "theme_mode"         const val KEY_REMINDER_ENABLED = "reminder_enabled"         const val KEY_REMINDER_MINUTES = "reminder_minutes"+        const val KEY_AUTO_PLAY = "auto_play_audio"+        const val KEY_DECK_PRESETS = "deck_presets"          const val BASIC_NOTE_TYPE_ID = 1L         val BUILT_IN_NOTE_TYPE_IDS = setOf(1L, 2L, 3L) +        /** Tag added to a note when one of its cards is auto-suspended as a leech. */+        const val LEECH_TAG = "leech"+         private fun nowSeconds(): Long = System.currentTimeMillis() / 1000          /** A 16-hex-char random note guid, matching the migration's format. */
flashcards/src/main/java/com/vayunmathur/flashcards/util/FsrsOptimizer.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/util/FsrsOptimizer.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/util/FsrsOptimizer.ktnew file mode 100644index 0000000000..ab547edb6b--- /dev/null+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/util/FsrsOptimizer.kt@@ -0,0 +1,102 @@+package com.vayunmathur.flashcards.util++import com.vayunmathur.flashcards.data.Card+import com.vayunmathur.flashcards.data.ReviewLog+import kotlin.math.ln++/**+ * A pragmatic FSRS weight optimizer. Given a deck's [ReviewLog] history grouped and+ * ordered per card, it runs **coordinate descent** to minimise the binary log-loss+ * between the model's predicted recall and the observed pass/fail, over a bounded+ * subset of the 19 FSRS weights, seeded from [Scheduler.DEFAULT_W].+ *+ * This is intentionally *not* a bit-exact reimplementation of Anki's optimizer — it+ * is a lightweight, dependency-free, unit-testable estimate. Pure Kotlin.+ */+object FsrsOptimizer {++    /** Minimum total reviews before optimization is attempted. */+    const val MIN_REVIEWS = 200++    // Weights we tune: initial stabilities (0..3), difficulty terms (4..6), and the+    // stability-growth terms (8..10). The rest keep their defaults.+    private val TUNABLE = intArrayOf(0, 1, 2, 3, 4, 5, 6, 8, 9, 10)++    private const val R_EPS = 1e-6++    /** True when [logsByCard] has enough contributing reviews to optimize. */+    fun hasEnough(logsByCard: List<List<ReviewLog>>): Boolean =+        logsByCard.sumOf { (it.size - 1).coerceAtLeast(0) } >= MIN_REVIEWS++    /**+     * Returns tuned weights, or a copy of [Scheduler.DEFAULT_W] when there is too+     * little history. [logsByCard] must be ordered chronologically within each card.+     */+    fun optimize(logsByCard: List<List<ReviewLog>>): DoubleArray {+        val weights = Scheduler.DEFAULT_W.copyOf()+        if (!hasEnough(logsByCard)) return weights++        var best = loss(weights, logsByCard)+        for (rate in doubleArrayOf(0.25, 0.1, 0.05)) {+            var improved = true+            var guard = 0+            while (improved && guard++ < 25) {+                improved = false+                for (idx in TUNABLE) {+                    for (sign in intArrayOf(1, -1)) {+                        val candidate = weights.copyOf()+                        candidate[idx] = clamp(idx, weights[idx] * (1 + sign * rate))+                        if (candidate[idx] == weights[idx]) continue+                        val l = loss(candidate, logsByCard)+                        if (l < best - 1e-9) {+                            weights[idx] = candidate[idx]+                            best = l+                            improved = true+                        }+                    }+                }+            }+        }+        return weights+    }++    /** Keeps a tuned weight positive and within 10x of its default magnitude. */+    private fun clamp(index: Int, value: Double): Double {+        val default = Scheduler.DEFAULT_W[index]+        val lo = maxOf(0.001, default * 0.1)+        val hi = maxOf(lo + 0.001, default * 10.0)+        return value.coerceIn(lo, hi)+    }++    /**+     * Binary log-loss of predicted recall vs observed pass across every review that+     * has a prior memory state (the first review of each card is skipped, since its+     * stability is only established by that review).+     */+    fun loss(weights: DoubleArray, logsByCard: List<List<ReviewLog>>): Double {+        var sum = 0.0+        var count = 0+        for (logs in logsByCard) {+            var card = Card(noteId = 0, templateOrd = 0, deckId = 0)+            var lastReview = 0L+            for (log in logs) {+                val elapsed = log.elapsedDays.coerceAtLeast(0.0)+                if (card.reps > 0 && card.stability > 0.0) {+                    val r = Scheduler.retrievability(elapsed, card.stability)+                        .coerceIn(R_EPS, 1.0 - R_EPS)+                    val observed = if (log.grade > 1) 1.0 else 0.0+                    sum += -(observed * ln(r) + (1.0 - observed) * ln(1.0 - r))+                    count+++                }+                val grade = gradeFrom(log.grade)+                val now = lastReview + (elapsed * Scheduler.DAY_MS).toLong()+                card = Scheduler.schedule(card.copy(lastReview = lastReview), grade, now, weights = weights)+                lastReview = now+            }+        }+        return if (count == 0) Double.MAX_VALUE else sum / count+    }++    private fun gradeFrom(value: Int): Grade =+        Grade.entries.firstOrNull { it.value == value } ?: Grade.GOOD+}
flashcards/src/main/java/com/vayunmathur/flashcards/util/HtmlConvert.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/util/HtmlConvert.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/util/HtmlConvert.ktindex b13c4e0804..1dc34a0ffa 100644--- a/flashcards/src/main/java/com/vayunmathur/flashcards/util/HtmlConvert.kt+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/util/HtmlConvert.kt@@ -14,6 +14,7 @@ object HtmlConvert {     private val bold = Regex("""\*\*(.+?)\*\*""")     private val italic = Regex("""(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)""")     private val code = Regex("`(.+?)`")+    private val image = Regex("""!\[(.*?)]\((.*?)\)""")     private val link = Regex("""\[(.*?)]\((.*?)\)""")      // -- HTML -> Markdown --------------------------------------------------@@ -26,9 +27,14 @@ object HtmlConvert {         s = Regex("""(?is)<a[^>]*?href="([^"]*)"[^>]*>(.*?)</a>""").replace(s) {             "[${it.groupValues[2]}](${it.groupValues[1]})"         }-        // Images -> alt text.-        s = Regex("""(?is)<img[^>]*?alt="([^"]*)"[^>]*>""").replace(s) { it.groupValues[1] }-        s = Regex("""(?is)<img[^>]*>""").replace(s, "")+        // Images -> markdown image, keeping only the basename of the src (the+        // media file is copied alongside on import/export).+        s = Regex("""(?is)<img[^>]*?>""").replace(s) { match ->+            val tag = match.value+            val src = Regex("""src="([^"]*)"""").find(tag)?.groupValues?.get(1).orEmpty()+            val alt = Regex("""alt="([^"]*)"""").find(tag)?.groupValues?.get(1).orEmpty()+            if (src.isBlank()) "" else "![$alt](${src.substringAfterLast('/')})"+        }         s = Regex("""(?i)<br\s*/?>""").replace(s, "\n")         s = Regex("""(?i)<hr[^>]*/?>""").replace(s, "\n---\n")         for (level in 1..6) {@@ -89,6 +95,8 @@ object HtmlConvert {         s = code.replace(s) { "<code>${it.groupValues[1]}</code>" }         s = bold.replace(s) { "<b>${it.groupValues[1]}</b>" }         s = italic.replace(s) { "<i>${it.groupValues[1]}</i>" }+        // Images before links: an image `![]()` also matches the link pattern.+        s = image.replace(s) { "<img src=\"${it.groupValues[2]}\" alt=\"${it.groupValues[1]}\">" }         s = link.replace(s) { "<a href=\"${it.groupValues[2]}\">${it.groupValues[1]}</a>" }         return s     }
flashcards/src/main/java/com/vayunmathur/flashcards/util/MediaStore.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/util/MediaStore.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/util/MediaStore.ktnew file mode 100644index 0000000000..00a1515cb7--- /dev/null+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/util/MediaStore.kt@@ -0,0 +1,82 @@+package com.vayunmathur.flashcards.util++import android.content.Context+import android.net.Uri+import java.io.File++/**+ * App-private storage for card images. Images are referenced from note fields as+ * markdown `![alt](filename)` and stored as files under `filesDir/media/<name>`.+ * Pure file plumbing (no scheduling or DB) so it is easy to reason about.+ */+class MediaStore(context: Context) {++    private val dir: File = File(context.filesDir, DIR).apply { mkdirs() }++    /** Resolves a bare media [name] to its file (may not exist). */+    fun resolve(name: String): File = File(dir, name)++    /**+     * Copies the picked [uri] into media storage under a unique name and returns+     * the bare filename to embed as `![](name)`. Returns null if the copy fails.+     */+    fun import(context: Context, uri: Uri): String? {+        val ext = extensionFor(context, uri)+        val name = "img_${System.currentTimeMillis()}_${(0..9999).random()}$ext"+        val target = File(dir, name)+        return runCatching {+            context.contentResolver.openInputStream(uri)?.use { input ->+                target.outputStream().use { input.copyTo(it) }+            } ?: return null+            name+        }.getOrNull()+    }++    /** Copies raw [bytes] to media storage under [name] (renaming on collision). */+    fun writeBytes(name: String, bytes: ByteArray): String {+        val target = uniqueFile(name)+        target.writeBytes(bytes)+        return target.name+    }++    private fun uniqueFile(name: String): File {+        var candidate = File(dir, name)+        if (!candidate.exists()) return candidate+        val base = name.substringBeforeLast('.', name)+        val ext = name.substringAfterLast('.', "").let { if (it.isEmpty()) "" else ".$it" }+        var i = 1+        while (candidate.exists()) {+            candidate = File(dir, "$base($i)$ext")+            i+++        }+        return candidate+    }++    /** Deletes any media files not present in [usedNames]. */+    fun garbageCollect(usedNames: Set<String>) {+        dir.listFiles()?.forEach { file ->+            if (file.name !in usedNames) file.delete()+        }+    }++    private fun extensionFor(context: Context, uri: Uri): String {+        val type = context.contentResolver.getType(uri)+        return when {+            type == "image/png" -> ".png"+            type == "image/webp" -> ".webp"+            type == "image/gif" -> ".gif"+            type == "image/jpeg" -> ".jpg"+            else -> ".jpg"+        }+    }++    companion object {+        private const val DIR = "media"++        private val imageRegex = Regex("""!\[[^\]]*]\(([^)]+)\)""")++        /** The set of media filenames referenced by an `![alt](name)` in [md]. */+        fun referenced(md: String): Set<String> =+            imageRegex.findAll(md).map { it.groupValues[1].trim() }.toSet()+    }+}
flashcards/src/main/java/com/vayunmathur/flashcards/util/ReviewSession.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/util/ReviewSession.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/util/ReviewSession.ktindex d74c1181af..d344b0ba71 100644--- a/flashcards/src/main/java/com/vayunmathur/flashcards/util/ReviewSession.kt+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/util/ReviewSession.kt@@ -19,9 +19,14 @@ class ReviewSession(     private val maxReviews: Int,     now: Long,     private val desiredRetention: Double,+    private val weights: DoubleArray = Scheduler.DEFAULT_W,+    params: StudyParams = StudyParams(), ) {     private val queue = ArrayDeque<Card>() +    /** True in cram mode: grading is preview-only and must not be persisted. */+    val previewOnly: Boolean = params.previewOnly+     /** Distinct cards this session started with. */     val totalCards: Int     private var completed = 0@@ -30,16 +35,40 @@ class ReviewSession(     private val undoStack = ArrayDeque<Undo>()      init {-        val newCards = cards-            .filter { it.state == CardState.NEW }-            .sortedBy { it.position }-            .take(newPerDay.coerceAtLeast(0))-        val reviewCards = cards-            .filter { it.state != CardState.NEW && it.dueDate <= now }-            .sortedBy { it.dueDate }-            .take(maxReviews.coerceAtLeast(0))-        queue.addAll(reviewCards)-        queue.addAll(newCards)+        val active = cards.filterNot { it.suspended == 1 }+        val dayMs = Scheduler.DAY_MS+        val selected: List<Card> = when (params.mode) {+            StudyMode.DUE -> {+                val newCards = active+                    .filter { it.state == CardState.NEW }+                    .sortedBy { it.position }+                    .take(newPerDay.coerceAtLeast(0))+                val reviewCards = active+                    .filter { it.state != CardState.NEW && it.dueDate <= now }+                    .sortedBy { it.dueDate }+                    .take(maxReviews.coerceAtLeast(0))+                reviewCards + newCards+            }+            StudyMode.AHEAD -> {+                val horizon = now + params.daysAhead.toLong() * dayMs+                active+                    .filter { it.state != CardState.NEW && it.dueDate <= horizon }+                    .sortedBy { it.dueDate }+                    .take(params.count.coerceAtLeast(0))+            }+            StudyMode.LAPSES -> active+                .filter { it.state == CardState.RELEARNING || it.lapses > 0 }+                .sortedBy { it.dueDate }+                .take(params.count.coerceAtLeast(0))+            StudyMode.NEW_ONLY -> active+                .filter { it.state == CardState.NEW }+                .sortedBy { it.position }+                .take(params.count.coerceAtLeast(0))+            StudyMode.CRAM -> active+                .sortedBy { it.position }+                .take(params.count.coerceAtLeast(0))+        }+        queue.addAll(selected)         totalCards = queue.size     } @@ -64,7 +93,7 @@ class ReviewSession(         undoStack.addLast(Undo(card, queue.toList(), completed))         queue.removeFirst() -        val updated = Scheduler.schedule(card, grade, now, desiredRetention)+        val updated = Scheduler.schedule(card, grade, now, desiredRetention, weights)         if (updated.state == CardState.LEARNING || updated.state == CardState.RELEARNING) {             queue.add(minOf(RE_QUEUE_GAP, queue.size), updated)         } else {@@ -73,6 +102,26 @@ class ReviewSession(         return updated     } +    /**+     * Removes the current card from the queue without scheduling it (used when a+     * card is suspended mid-session). Returns the removed card, or null if empty.+     */+    fun removeCurrent(): Card? {+        val card = queue.firstOrNull() ?: return null+        undoStack.addLast(Undo(card, queue.toList(), completed))+        queue.removeFirst()+        completed+++        return card+    }++    /**+     * Removes every queued copy of the card with [id] without scheduling (used when+     * a card is auto-suspended as a leech mid-session).+     */+    fun removeFromQueue(id: Long) {+        queue.removeAll { it.id == id }+    }+     /**      * Reverts the last [grade]. Returns the card whose pre-grade state must be      * restored in the database, or null if there is nothing to undo.@@ -89,7 +138,7 @@ class ReviewSession(     fun previewLabels(now: Long): Map<Grade, String> {         val card = current ?: return emptyMap()         return Grade.entries.associateWith {-            Scheduler.previewLabel(card, it, now, desiredRetention)+            Scheduler.previewLabel(card, it, now, desiredRetention, weights)         }     } 
flashcards/src/main/java/com/vayunmathur/flashcards/util/Scheduler.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/util/Scheduler.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/util/Scheduler.ktindex c72c81a141..ada640c873 100644--- a/flashcards/src/main/java/com/vayunmathur/flashcards/util/Scheduler.kt+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/util/Scheduler.kt@@ -118,8 +118,9 @@ object Scheduler {         grade: Grade,         now: Long,         desiredRetention: Double = 0.9,+        weights: DoubleArray = DEFAULT_W,     ): Card {-        val w = DEFAULT_W+        val w = if (weights.size == DEFAULT_W.size) weights else DEFAULT_W         val firstReview = card.reps == 0 || card.state == CardState.NEW         val elapsedDays =             if (card.lastReview > 0) (now - card.lastReview).toDouble() / DAY_MS else 0.0@@ -182,7 +183,25 @@ object Scheduler {         grade: Grade,         now: Long,         desiredRetention: Double = 0.9,-    ): String = formatDuration(schedule(card, grade, now, desiredRetention).dueDate - now)+        weights: DoubleArray = DEFAULT_W,+    ): String = formatDuration(schedule(card, grade, now, desiredRetention, weights).dueDate - now)++    /**+     * Parses a JSON array string of 19 doubles into FSRS weights. Returns+     * [DEFAULT_W] on a blank input, a parse failure, or a wrong length. Kept+     * dependency-free (no `org.json`) so it is usable from pure JVM tests.+     */+    fun parseWeights(json: String): DoubleArray {+        if (json.isBlank()) return DEFAULT_W+        val nums = json.trim().removePrefix("[").removeSuffix("]")+            .split(",")+            .mapNotNull { it.trim().toDoubleOrNull() }+        return if (nums.size == DEFAULT_W.size) nums.toDoubleArray() else DEFAULT_W+    }++    /** Serializes FSRS [weights] to a JSON array string for storage. */+    fun weightsToJson(weights: DoubleArray): String =+        weights.joinToString(prefix = "[", postfix = "]", separator = ",")      private fun formatDuration(ms: Long): String {         val minutes = ms / MINUTE_MS
flashcards/src/main/java/com/vayunmathur/flashcards/util/TemplateEngine.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/util/TemplateEngine.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/util/TemplateEngine.ktindex 8fb787ec83..ff321bc72d 100644--- a/flashcards/src/main/java/com/vayunmathur/flashcards/util/TemplateEngine.kt+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/util/TemplateEngine.kt@@ -18,11 +18,16 @@ object TemplateEngine {      private val clozeRegex = Regex("""\{\{c(\d+)::(.*?)(?:::(.*?))?\}\}""", RegexOption.DOT_MATCHES_ALL)     private val clozeFieldRegex = Regex("""\{\{cloze:([^}]+)\}\}""")+    private val typeRegex = Regex("""\{\{type:([^}]+)\}\}""")     private val sectionRegex = Regex(         """\{\{([#^])([^}]+)\}\}((?:(?!\{\{[#^/]).)*?)\{\{/([^}]+)\}\}""",         RegexOption.DOT_MATCHES_ALL,     ) +    /** The field name a `{{type:Field}}` marker in [qfmt] targets, or null if none. */+    fun typeField(qfmt: String): String? =+        typeRegex.find(qfmt)?.groupValues?.get(1)?.trim()+     /** Returns the rendered (frontMarkdown, backMarkdown) pair. */     fun render(         qfmt: String,@@ -46,6 +51,11 @@ object TemplateEngine {             val fieldName = match.groupValues[1].trim()             renderCloze(fields[fieldName] ?: "", clozeOrd, isBack = frontSide != null)         }+        // `{{type:Field}}`: blank on the front (the UI shows an input); the field+        // value on the back (the UI also shows a typed-vs-actual diff).+        text = typeRegex.replace(text) { match ->+            if (frontSide == null) "" else fields[match.groupValues[1].trim()] ?: ""+        }         if (frontSide != null) {             text = text.replace("{{FrontSide}}", frontSide)         }
flashcards/src/main/java/com/vayunmathur/flashcards/util/TtsSpeaker.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/util/TtsSpeaker.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/util/TtsSpeaker.ktnew file mode 100644index 0000000000..dee395ba07--- /dev/null+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/util/TtsSpeaker.kt@@ -0,0 +1,59 @@+package com.vayunmathur.flashcards.util++import android.content.Context+import android.speech.tts.TextToSpeech+import java.util.Locale++/**+ * A thin wrapper over [TextToSpeech] for reading card text aloud. Mirrors the+ * pattern used by `:translate`'s `TtsSpeaker`: the engine initialises+ * asynchronously, so requests made before it is ready are queued and replayed on+ * init. Uses the device's default locale. Call [shutdown] when the owner+ * (ViewModel) is cleared.+ */+class TtsSpeaker(context: Context) {++    private var ready = false+    private var pending: String? = null++    private val tts: TextToSpeech = TextToSpeech(context.applicationContext) { status ->+        ready = status == TextToSpeech.SUCCESS+        if (ready) {+            runCatching { tts.language = Locale.getDefault() }+            pending?.let { text ->+                pending = null+                speakNow(text)+            }+        }+    }++    /** Speaks [text], flushing anything currently playing. Blank input is a no-op. */+    fun speak(text: String) {+        val clean = text.trim()+        if (clean.isEmpty()) return+        if (!ready) {+            pending = clean+            return+        }+        speakNow(clean)+    }++    private fun speakNow(text: String) {+        tts.speak(text, TextToSpeech.QUEUE_FLUSH, null, UTTERANCE_ID)+    }++    fun stop() {+        pending = null+        runCatching { tts.stop() }+    }++    fun shutdown() {+        pending = null+        runCatching { tts.stop() }+        runCatching { tts.shutdown() }+    }++    private companion object {+        const val UTTERANCE_ID = "flashcards_tts"+    }+}
flashcards/src/main/res/values/strings.xml
diff --git a/flashcards/src/main/res/values/strings.xml b/flashcards/src/main/res/values/strings.xmlindex f0f04738ab..65ce7995c6 100644--- a/flashcards/src/main/res/values/strings.xml+++ b/flashcards/src/main/res/values/strings.xml@@ -125,4 +125,70 @@         <item quantity="one">%d card is due for review</item>         <item quantity="other">%d cards are due for review</item>     </plurals>++    <!-- Generic actions -->+    <string name="deleted">Deleted</string>+    <string name="undo">Undo</string>+    <string name="done">Done</string>++    <!-- Suspend / leech -->+    <string name="suspend">Suspend</string>+    <string name="unsuspend">Unsuspend</string>+    <string name="suspend_card">Suspend card</string>+    <string name="suspended_badge">Suspended</string>+    <string name="leech_suspended">Card suspended (leech)</string>++    <!-- Bulk actions (note list selection mode) -->+    <string name="selected_count">%1$d selected</string>+    <string name="move_to_deck">Move to deck</string>+    <string name="add_tag">Add tag</string>+    <string name="remove_tag">Remove tag</string>+    <string name="tag_name">Tag</string>+    <string name="reset_scheduling">Reset scheduling</string>+    <string name="reset_scheduling_message">Reset these cards back to new? Their review history will be cleared.</string>+    <string name="export_csv">Export CSV</string>++    <!-- Custom study -->+    <string name="custom_study">Custom study</string>+    <string name="custom_study_ahead">Study ahead</string>+    <string name="custom_study_lapses">Review lapses only</string>+    <string name="custom_study_new">New cards only</string>+    <string name="custom_study_cram">Cram (ignore schedule)</string>+    <string name="custom_study_count">Card count</string>+    <string name="custom_study_days">Days ahead</string>+    <string name="start">Start</string>++    <!-- Review extras -->+    <string name="speak">Speak</string>+    <string name="type_answer">Type the answer</string>+    <string name="check">Check</string>+    <string name="swipe_hint">Swipe to grade, or use the buttons</string>++    <!-- Settings additions -->+    <string name="setting_auto_play">Auto-play audio</string>+    <string name="setting_auto_play_hint">Read the front of each card aloud</string>++    <!-- Note editor toolbar -->+    <string name="insert_image">Insert image</string>+    <string name="insert_cloze">Cloze deletion</string>++    <!-- Stats additions -->+    <string name="stat_forecast">Due forecast</string>+    <string name="stat_retention_by_interval">Retention by interval</string>+    <string name="stat_heatmap">Review activity</string>++    <!-- Deck presets -->+    <string name="settings_presets">Deck presets</string>+    <string name="save_preset">Save preset</string>+    <string name="apply_preset">Apply preset</string>+    <string name="preset_name">Preset name</string>+    <string name="preset_saved">Preset saved</string>+    <string name="preset_applied">Preset applied</string>++    <!-- FSRS optimizer -->+    <string name="optimize_fsrs">Optimize FSRS parameters</string>+    <string name="optimize_fsrs_hint">Estimates better scheduling from your review history (needs at least %1$d reviews)</string>+    <string name="optimize_fsrs_too_few">Not enough reviews to optimize yet (%1$d of %2$d)</string>+    <string name="optimize_fsrs_done">Updated FSRS parameters from %1$d reviews</string>+    <string name="optimize_fsrs_running">Optimizing…</string> </resources>
flashcards/src/screenshotTest/kotlin/com/vayunmathur/flashcards/ui/MetadataPreviews.kt
diff --git a/flashcards/src/screenshotTest/kotlin/com/vayunmathur/flashcards/ui/MetadataPreviews.kt b/flashcards/src/screenshotTest/kotlin/com/vayunmathur/flashcards/ui/MetadataPreviews.ktindex 2d1ceca3b4..467013bb86 100644--- a/flashcards/src/screenshotTest/kotlin/com/vayunmathur/flashcards/ui/MetadataPreviews.kt+++ b/flashcards/src/screenshotTest/kotlin/com/vayunmathur/flashcards/ui/MetadataPreviews.kt@@ -132,6 +132,11 @@ class MetadataPreviews {         val today =

Diff truncated.