Skip to content

Commit

Permalink
NF: uses protobuf simplified constructors
Browse files Browse the repository at this point in the history
While looking at the `Card` code, I decided to go over all
`newBuilder`, and slightly improve the code everywhere.
  • Loading branch information
Arthur-Milchior committed Dec 12, 2024
1 parent d36795a commit f83df72
Show file tree
Hide file tree
Showing 6 changed files with 68 additions and 72 deletions.
12 changes: 6 additions & 6 deletions AnkiDroid/src/main/java/com/ichi2/anki/BackupManager.kt
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import android.text.format.DateFormat
import androidx.annotation.VisibleForTesting
import androidx.core.content.edit
import anki.config.Preferences.BackupLimits
import anki.config.PreferencesKt.backupLimits
import anki.config.copy
import com.ichi2.anki.preferences.sharedPrefs
import com.ichi2.compat.CompatHelper
Expand Down Expand Up @@ -181,12 +182,11 @@ open class BackupManager {
// Delete old backup files if needed
val prefs = AnkiDroidApp.instance.baseContext.sharedPrefs()
val backupLimits =
BackupLimits
.newBuilder()
.setDaily(prefs.getInt("daily_backups_to_keep", 8))
.setWeekly(prefs.getInt("weekly_backups_to_keep", 8))
.setMonthly(prefs.getInt("monthly_backups_to_keep", 8))
.build()
backupLimits {
daily = prefs.getInt("daily_backups_to_keep", 8)
weekly = prefs.getInt("weekly_backups_to_keep", 8)
monthly = prefs.getInt("monthly_backups_to_keep", 8)
}
deleteColBackups(colPath, backupLimits)
// set timestamp of file in order to avoid creating a new backup unless its changed
if (!backupFile.setLastModified(colFile.lastModified())) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ import androidx.core.view.isVisible
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import anki.decks.DeckTreeNode
import anki.decks.deckTreeNode
import com.ichi2.anki.CollectionManager.withCol
import com.ichi2.anki.DeckSpinnerSelection
import com.ichi2.anki.OnContextAndLongClickListener.Companion.setOnContextAndLongClickListener
Expand Down Expand Up @@ -439,11 +439,10 @@ open class DeckSelectionDialog : AnalyticsDialogFragment() {
val allDecksSet = deckNames.filter { it.deckId != 0L }.mapNotNull { decksRoot.find(it.deckId) }.toSet()
if (deckNames.any { it.deckId == ALL_DECKS_ID }) {
val newDeckNode =
DeckTreeNode
.newBuilder()
.setDeckId(ALL_DECKS_ID)
.setName("all")
.build()
deckTreeNode {
deckId = ALL_DECKS_ID
name = "all"
}
allDecksList.add(DeckNode(newDeckNode, getString(R.string.card_browser_all_decks), null))
}

Expand Down
55 changes: 25 additions & 30 deletions AnkiDroid/src/main/java/com/ichi2/libanki/Card.kt
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ package com.ichi2.libanki

import androidx.annotation.VisibleForTesting
import anki.cards.FsrsMemoryState
import anki.decks.deckId
import anki.notes.noteId
import com.ichi2.anki.Flag
import com.ichi2.anki.utils.ext.ifZero
import com.ichi2.libanki.Consts.CardQueue
Expand Down Expand Up @@ -147,31 +149,28 @@ open class Card : Cloneable {
}

@LibAnkiAlias("_to_backend_card")
fun toBackendCard(): anki.cards.Card {
val builder =
anki.cards.Card
.newBuilder()
.setId(id)
.setNoteId(nid)
.setDeckId(did)
.setTemplateIdx(ord)
.setCtype(type)
.setQueue(queue)
.setDue(due)
.setInterval(ivl)
.setEaseFactor(factor)
.setReps(reps)
.setLapses(lapses)
.setRemainingSteps(left)
.setOriginalDue(oDue)
.setOriginalDeckId(oDid)
.setFlags(flags)
.setCustomData(customData)
originalPosition?.let { builder.setOriginalPosition(it) }
memoryState?.let { builder.setMemoryState(it) }
desiredRetention?.let { builder.setDesiredRetention(it) }
return builder.build()
}
fun toBackendCard() =
anki.cards.card {
id = this@Card.id
noteId = nid
deckId = did
templateIdx = ord
ctype = type
queue = this@Card.queue
due = this@Card.due
interval = ivl
easeFactor = factor
reps = this@Card.reps
lapses = this@Card.lapses
remainingSteps = left
originalDue = oDue
originalDeckId = oDid
flags = this@Card.flags
customData = this@Card.customData
this@Card.originalPosition?.let { originalPosition = it }
this@Card.memoryState?.let { memoryState = it }
this@Card.desiredRetention?.let { desiredRetention = it }
}

@LibAnkiAlias("question")
fun question(
Expand Down Expand Up @@ -234,11 +233,7 @@ open class Card : Cloneable {
}

@LibAnkiAlias("current_deck_id")
fun currentDeckId(): anki.decks.DeckId =
anki.decks.DeckId
.newBuilder()
.setDid(oDid.ifZero { did })
.build()
fun currentDeckId() = deckId { did = oDid.ifZero { did } }

/**
* Time limit for answering in milliseconds.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,27 +15,29 @@
*/
package com.ichi2.libanki.backend.model

import anki.search.SortOrderKt.builtin
import anki.search.sortOrder
import com.ichi2.libanki.SortOrder

// Conversion functions from SortOrder to anki.search.SortOrder

fun SortOrder.toProtoBuf(): anki.search.SortOrder {
val builder = anki.search.SortOrder.newBuilder()
return when (this) {
is SortOrder.NoOrdering -> {
builder.setNone(anki.generic.Empty.getDefaultInstance())
}
is SortOrder.AfterSqlOrderBy ->
builder.setCustom(this.customOrdering)
is SortOrder.BuiltinSortKind ->
builder.setBuiltin(this.toProtoBuf())
else -> throw IllegalStateException(this.toString())
}.build()
}
fun SortOrder.toProtoBuf() =
sortOrder {
when (this@toProtoBuf) {
is SortOrder.NoOrdering -> {
none = anki.generic.Empty.getDefaultInstance()
}

is SortOrder.AfterSqlOrderBy ->
custom = customOrdering

fun SortOrder.BuiltinSortKind.toProtoBuf(): anki.search.SortOrder.Builtin =
anki.search.SortOrder.Builtin
.newBuilder()
.setColumn(value)
.setReverse(reverse)
.build()
is SortOrder.BuiltinSortKind ->
builtin =
builtin {
column = value
reverse = this@toProtoBuf.reverse
}

else -> throw IllegalStateException(this.toString())
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package com.ichi2.anki

import anki.config.Preferences.BackupLimits
import anki.config.PreferencesKt.backupLimits
import com.ichi2.anki.BackupManager.Companion.getLatestBackup
import com.ichi2.testutils.MockTime
import org.hamcrest.CoreMatchers.equalTo
Expand Down Expand Up @@ -132,12 +133,11 @@ class BackupManagerSimpleTest {
weekly: Int,
monthly: Int,
): BackupLimits =
BackupLimits
.newBuilder()
.setDaily(daily)
.setWeekly(weekly)
.setMonthly(monthly)
.build()
backupLimits {
this.daily = daily
this.weekly = weekly
this.monthly = monthly
}

@Test
fun keepsAllBackupsForToday() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
package com.ichi2.anki

import androidx.test.ext.junit.runners.AndroidJUnit4
import anki.backend.BackendError
import anki.backend.backendError
import com.ichi2.anki.exception.StorageAccessException
import com.ichi2.anki.servicelayer.ThrowableFilterService
import com.ichi2.anki.servicelayer.ThrowableFilterService.safeFromPII
Expand All @@ -35,13 +35,13 @@ import kotlin.test.assertTrue
class ThrowableFilterServiceTest : JvmTest() {
@Test
fun `Normal exceptions are flagged as PII-safe`() {
val exception = BackendDeckIsFilteredException(BackendError.newBuilder().build())
val exception = BackendDeckIsFilteredException(backendError {})
assertTrue(exception.safeFromPII(), "Exception reported as safe from PII")
}

@Test
fun `BackendSyncServerMessage exceptions are flagged as PII-unsafe`() {
val exception1 = BackendSyncServerMessageException(BackendError.newBuilder().build())
val exception1 = BackendSyncServerMessageException(backendError { })
assertFalse(exception1.safeFromPII(), "Exception reported as not safe from PII")

val exception2 = Exception("", Exception("", exception1))
Expand All @@ -54,9 +54,9 @@ class ThrowableFilterServiceTest : JvmTest() {
assertFalse(ThrowableFilterService.shouldDiscardThrowable(Exception("wanted")))

// exceptions of known unwanted types should not go through
val exception1 = BackendNetworkException(BackendError.newBuilder().build())
val exception1 = BackendNetworkException(backendError {})
assertTrue(ThrowableFilterService.shouldDiscardThrowable(exception1))
val exception2 = BackendSyncException(BackendError.newBuilder().build())
val exception2 = BackendSyncException(backendError {})
assertTrue(ThrowableFilterService.shouldDiscardThrowable(exception2))
val exception3 = StorageAccessException("test exception")
assertTrue(ThrowableFilterService.shouldDiscardThrowable(exception3))
Expand Down

0 comments on commit f83df72

Please sign in to comment.