Skip to content

Commit

Permalink
chore: remove col from Note
Browse files Browse the repository at this point in the history
Revived from ankidroid@44b5f1b

* add NoteService.isMarked

Co-authored-by: Arthur Milchior <[email protected]>
  • Loading branch information
2 people authored and BrayanDSO committed Jan 29, 2024
1 parent c87cecd commit abb6a36
Show file tree
Hide file tree
Showing 21 changed files with 120 additions and 94 deletions.
4 changes: 2 additions & 2 deletions AnkiDroid/src/androidTest/java/com/ichi2/anki/PagesTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -88,14 +88,14 @@ fun PagesTest.getStatistics(context: Context): Intent {
}

fun PagesTest.getCardInfo(context: Context): Intent {
return addNoteUsingBasicModel().firstCard().let { card ->
return addNoteUsingBasicModel().firstCard(col).let { card ->
this.card = card
CardInfoDestination(card.id).toIntent(context)
}
}

fun PagesTest.getCongratsPage(context: Context): Intent {
return addNoteUsingBasicModel().firstCard().let { card ->
return addNoteUsingBasicModel().firstCard(col).let { card ->
this.card = card
CardInfoDestination(card.id).toIntent(context)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ class ReviewerTest : InstrumentedTest() {
customData.good.c += 1;
"""
val note = addNoteUsingBasicModel("foo", "bar")
val card = note.firstCard()
val card = note.firstCard(col)
val deck = col.decks.get(note.notetype.did)!!
card.moveToReviewQueue()
col.backend.updateCards(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,7 @@ class ContentProviderTest : InstrumentedTest() {
// Check that it looks as expected
assertNotNull("check note URI path", newNoteUri!!.lastPathSegment)
val addedNote = Note(col, newNoteUri.lastPathSegment!!.toLong())
addedNote.load()
addedNote.load(col)
assertEquals(
"Check that fields were set correctly",
addedNote.fields,
Expand All @@ -211,11 +211,11 @@ class ContentProviderTest : InstrumentedTest() {
val model: JSONObject? = col.notetypes.get(modelId)
assertNotNull("Check model", model)
val expectedNumCards = model!!.getJSONArray("tmpls").length()
assertEquals("Check that correct number of cards generated", expectedNumCards, addedNote.numberOfCards())
assertEquals("Check that correct number of cards generated", expectedNumCards, addedNote.numberOfCards(col))
// Now delete the note
cr.delete(newNoteUri, null, null)
try {
addedNote.load()
addedNote.load(col)
fail("Expected RuntimeException to be thrown when deleting note")
} catch (e: RuntimeException) {
// Expect RuntimeException to be thrown when loading deleted note
Expand Down Expand Up @@ -1300,7 +1300,7 @@ class ContentProviderTest : InstrumentedTest() {
fields: Array<String>,
tag: String
): Uri {
val newNote = Note(col, col.notetypes.get(mid)!!)
val newNote = Note(col.notetypes.get(mid)!!)
for (idx in fields.indices) {
newNote.setField(idx, fields[idx])
}
Expand All @@ -1310,7 +1310,7 @@ class ContentProviderTest : InstrumentedTest() {
col.addNote(newNote),
greaterThanOrEqualTo(1)
)
for (c in newNote.cards()) {
for (c in newNote.cards(col)) {
c.did = did
col.updateCard(c, skipUndoEntry = true)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2194,7 +2194,7 @@ abstract class AbstractFlashcardViewer :
}

protected open fun shouldDisplayMark(): Boolean {
return isMarked(currentCard!!.note(getColUnsafe))
return isMarked(getColUnsafe, currentCard!!.note(getColUnsafe))
}

val writeLock: Lock
Expand Down Expand Up @@ -2565,8 +2565,8 @@ abstract class AbstractFlashcardViewer :
if (currentCard!!.note(getColUnsafe).tags != selectedTags) {
val tagString = selectedTags.joinToString(" ")
val note = currentCard!!.note(getColUnsafe)
note.setTagsFromStr(tagString)
note.flush()
note.setTagsFromStr(getColUnsafe, tagString)
note.flush(getColUnsafe)
// Reload current card to reflect tag changes
reloadWebViewContent()
}
Expand Down
2 changes: 1 addition & 1 deletion AnkiDroid/src/main/java/com/ichi2/anki/AnkiDroidJsAPI.kt
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ open class AnkiDroidJsAPI(private val activity: AbstractFlashcardViewer) {
activity.launchCatchingTask { activity.resetCards(cardIds) }
convertToByteArray(apiContract, true)
}
"cardMark" -> convertToByteArray(apiContract, currentCard.note(getColUnsafe).hasTag("marked"))
"cardMark" -> convertToByteArray(apiContract, currentCard.note(getColUnsafe).hasTag(getColUnsafe, "marked"))
"cardFlag" -> convertToByteArray(apiContract, currentCard.userFlag())
"cardReps" -> convertToByteArray(apiContract, currentCard.reps)
"cardInterval" -> convertToByteArray(apiContract, currentCard.ivl)
Expand Down
10 changes: 5 additions & 5 deletions AnkiDroid/src/main/java/com/ichi2/anki/CardBrowser.kt
Original file line number Diff line number Diff line change
Expand Up @@ -1979,7 +1979,7 @@ open class CardBrowser :
6 -> R.attr.flagTurquoise
7 -> R.attr.flagPurple
else -> {
if (isMarked(card.note(col))) {
if (isMarked(col, card.note(col))) {
R.attr.markedColor
} else if (card.queue == Consts.QUEUE_TYPE_SUSPENDED) {
R.attr.suspendedColor
Expand All @@ -1994,11 +1994,11 @@ open class CardBrowser :
return when (key) {
CardBrowserColumn.FLAGS -> Integer.valueOf(card.userFlag()).toString()
CardBrowserColumn.SUSPENDED -> if (card.queue == Consts.QUEUE_TYPE_SUSPENDED) "True" else "False"
CardBrowserColumn.MARKED -> if (isMarked(card.note(col))) "marked" else null
CardBrowserColumn.SFLD -> card.note(col).sFld()
CardBrowserColumn.MARKED -> if (isMarked(col, card.note(col))) "marked" else null
CardBrowserColumn.SFLD -> card.note(col).sFld(col)
CardBrowserColumn.DECK -> col.decks.name(card.did)
CardBrowserColumn.TAGS -> card.note(col).stringTags()
CardBrowserColumn.CARD -> if (inCardMode) card.template(col).optString("name") else "${card.note(col).numberOfCards()}"
CardBrowserColumn.TAGS -> card.note(col).stringTags(col)
CardBrowserColumn.CARD -> if (inCardMode) card.template(col).optString("name") else "${card.note(col).numberOfCards(col)}"
CardBrowserColumn.DUE -> card.dueString(col)
CardBrowserColumn.EASE -> if (inCardMode) getEaseForCards() else getAvgEaseForNotes()
CardBrowserColumn.CHANGED -> LanguageUtil.getShortDateFormatFromS(if (inCardMode) card.mod else card.note(col).mod.toLong())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -597,7 +597,7 @@ open class CardTemplateEditor : AnkiActivity(), DeckSelectionListener {

// If we have a card for this position, send it, otherwise an empty card list signals to show a blank
if (noteId != -1L) {
val cids = col.getNote(noteId).cids()
val cids = col.getNote(noteId).cids(col)
if (ordinal < cids.size) {
i.putExtra("cardList", longArrayOf(cids[ordinal]))
}
Expand Down
12 changes: 7 additions & 5 deletions AnkiDroid/src/main/java/com/ichi2/anki/CardTemplatePreviewer.kt
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ open class CardTemplatePreviewer : AbstractFlashcardViewer() {
// loading from the note editor
val toPreview = setCurrentCardFromNoteEditorBundle(col)
if (toPreview != null) {
cardCount = toPreview.note(getColUnsafe).numberOfCardsEphemeral()
cardCount = toPreview.note(col).numberOfCardsEphemeral(col)
if (cardCount >= 2) {
previewLayout!!.showNavigationButtons()
}
Expand Down Expand Up @@ -304,7 +304,7 @@ open class CardTemplatePreviewer : AbstractFlashcardViewer() {
currentNote.delTag(tag)
}
if (tagsList != null) {
val tagsSet = currentNote.col.tags.canonify(tagsList)
val tagsSet = getColUnsafe.tags.canonify(tagsList)
currentNote.addTags(tagsSet)
}
}
Expand Down Expand Up @@ -425,6 +425,7 @@ open class CardTemplatePreviewer : AbstractFlashcardViewer() {
ord
}
val context = TemplateManager.TemplateRenderContext.fromCardLayout(
col,
note(col),
this,
model(col),
Expand All @@ -447,7 +448,7 @@ private class EphemeralCard(col: Collection, id: Long?) : Card(col, id) {
fun fromNote(n: Note, col: Collection, cardIndex: Int = 0): EphemeralCard {
val card = EphemeralCard(col, null)
card.did = 1
card.ord = n.cardIndexToOrd(cardIndex)
card.ord = n.cardIndexToOrd(col, cardIndex)
Timber.v("Generating ephemeral note, idx %d ord %d", cardIndex, card.ord)

val nt = n.notetype
Expand All @@ -460,6 +461,7 @@ private class EphemeralCard(col: Collection, id: Long?) : Card(col, id) {
template.put("ord", card.ord)

val output = TemplateManager.TemplateRenderContext.fromCardLayout(
col,
n,
card,
notetype = nt,
Expand All @@ -474,7 +476,7 @@ private class EphemeralCard(col: Collection, id: Long?) : Card(col, id) {
}

/** returns the number of cards from a note which has not had data saved in the database */
private fun Note.numberOfCardsEphemeral(): Int {
private fun Note.numberOfCardsEphemeral(col: Collection): Int {
// We can't use note.numberOfCards() as this uses the database value
return when {
this.notetype.isCloze -> col.clozeNumbersInNote(this).size
Expand All @@ -485,7 +487,7 @@ private fun Note.numberOfCardsEphemeral(): Int {
/**
* Given a card index, returns the 'ord' of the card
*/
private fun Note.cardIndexToOrd(index: Int): Int {
private fun Note.cardIndexToOrd(col: Collection, index: Int): Int {
// We can't use note.numberOfCards() as this uses the database value
return when {
this.notetype.isCloze -> col.clozeNumbersInNote(this)[index] - 1
Expand Down
24 changes: 12 additions & 12 deletions AnkiDroid/src/main/java/com/ichi2/anki/NoteEditor.kt
Original file line number Diff line number Diff line change
Expand Up @@ -228,8 +228,8 @@ class NoteEditor : AnkiActivity(), DeckSelectionListener, SubtitleListener, Tags
NoteEditorActivityResultCallback {
// Model can change regardless of exit type - update ourselves and CardBrowser
mReloadRequired = true
mEditorNote!!.reloadModel()
if (mCurrentEditedCard == null || !mEditorNote!!.cids()
mEditorNote!!.reloadModel(getColUnsafe)
if (mCurrentEditedCard == null || !mEditorNote!!.cids(getColUnsafe)
.contains(mCurrentEditedCard!!.id)
) {
if (!addNote) {
Expand Down Expand Up @@ -887,7 +887,7 @@ class NoteEditor : AnkiActivity(), DeckSelectionListener, SubtitleListener, Tags
// Save deck to model
mEditorNote!!.notetype.put("did", deckId)
// Save tags to model
mEditorNote!!.setTagsFromStr(tagsAsString(mSelectedTags!!))
mEditorNote!!.setTagsFromStr(getColUnsafe, tagsAsString(mSelectedTags!!))
val tags = JSONArray()
for (t in mSelectedTags!!) {
tags.put(t)
Expand All @@ -910,7 +910,7 @@ class NoteEditor : AnkiActivity(), DeckSelectionListener, SubtitleListener, Tags
val oldModel = if (mCurrentEditedCard == null) null else mCurrentEditedCard!!.model(getColUnsafe)
if (newModel != oldModel) {
mReloadRequired = true
if (mModelChangeCardMap!!.size < mEditorNote!!.numberOfCards() || mModelChangeCardMap!!.containsValue(
if (mModelChangeCardMap!!.size < mEditorNote!!.numberOfCards(getColUnsafe) || mModelChangeCardMap!!.containsValue(
null
)
) {
Expand Down Expand Up @@ -953,7 +953,7 @@ class NoteEditor : AnkiActivity(), DeckSelectionListener, SubtitleListener, Tags
}
// added tag?
for (t in mSelectedTags!!) {
modified = modified || !mEditorNote!!.hasTag(t)
modified = modified || !mEditorNote!!.hasTag(getColUnsafe, tag = t)
}
// removed tag?
modified = modified || mEditorNote!!.tags.size > mSelectedTags!!.size
Expand All @@ -963,7 +963,7 @@ class NoteEditor : AnkiActivity(), DeckSelectionListener, SubtitleListener, Tags
return
}

mEditorNote!!.setTagsFromStr(tagsAsString(mSelectedTags!!))
mEditorNote!!.setTagsFromStr(getColUnsafe, tagsAsString(mSelectedTags!!))
changed = true

if (caller != CALLER_PREVIEWER_EDIT) {
Expand All @@ -973,7 +973,7 @@ class NoteEditor : AnkiActivity(), DeckSelectionListener, SubtitleListener, Tags

withProgress {
undoableOp {
updateNote(mCurrentEditedCard!!.note(this))
updateNote(mCurrentEditedCard!!.note())
}
closeNoteEditor()
}
Expand All @@ -989,9 +989,9 @@ class NoteEditor : AnkiActivity(), DeckSelectionListener, SubtitleListener, Tags
val noteId = mEditorNote!!.id
undoableOp {
notetypes.change(oldNotetype, noteId, newNotetype, mModelChangeFieldMap!!, mModelChangeCardMap!!)
// refresh the note object to reflect the database changes
mEditorNote!!.load()
}
// refresh the note object to reflect the database changes
mEditorNote!!.load()
// close note editor
closeNoteEditor()
}
Expand Down Expand Up @@ -1683,7 +1683,7 @@ class NoteEditor : AnkiActivity(), DeckSelectionListener, SubtitleListener, Tags
// Update the field in the Note so we can run a dupe check on it.
updateField(field)
// 1 is empty, 2 is dupe, null is neither.
val dupeCode = mEditorNote!!.dupeOrEmpty()
val dupeCode = mEditorNote!!.dupeOrEmpty(getColUnsafe)
// Change bottom line color of text field
if (dupeCode == DupeOrEmpty.DUPE) {
field!!.setDupeStyle()
Expand Down Expand Up @@ -1748,7 +1748,7 @@ class NoteEditor : AnkiActivity(), DeckSelectionListener, SubtitleListener, Tags
private fun setNote(note: Note?, changeType: FieldChangeType) {
mEditorNote = if (note == null || addNote) {
val model = getColUnsafe.notetypes.current()
Note(getColUnsafe, model)
Note(model)
} else {
note
}
Expand Down Expand Up @@ -2126,7 +2126,7 @@ class NoteEditor : AnkiActivity(), DeckSelectionListener, SubtitleListener, Tags
val templatesLength = tmpls.length()
mModelChangeCardMap = HashUtil.hashMapInit(templatesLength)
for (i in 0 until templatesLength) {
if (i < mEditorNote!!.numberOfCards()) {
if (i < mEditorNote!!.numberOfCards(getColUnsafe)) {
mModelChangeCardMap!![i] = i
} else {
mModelChangeCardMap!![i] = null
Expand Down
2 changes: 1 addition & 1 deletion AnkiDroid/src/main/java/com/ichi2/anki/Reviewer.kt
Original file line number Diff line number Diff line change
Expand Up @@ -703,7 +703,7 @@ open class Reviewer :
actionButtons.setCustomButtonsStatus(menu)
val alpha = Themes.ALPHA_ICON_ENABLED_LIGHT
val markCardIcon = menu.findItem(R.id.action_mark_card)
if (currentCard != null && isMarked(currentCard!!.note(getColUnsafe))) {
if (currentCard != null && isMarked(getColUnsafe, currentCard!!.note(getColUnsafe))) {
markCardIcon.setTitle(R.string.menu_unmark_note).setIcon(R.drawable.ic_star_white)
} else {
markCardIcon.setTitle(R.string.menu_mark_note).setIcon(R.drawable.ic_star_border_white)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ import com.ichi2.libanki.Card
import com.ichi2.libanki.CardId
import com.ichi2.libanki.Consts
import com.ichi2.libanki.DeckId
import com.ichi2.libanki.hasTag
import com.ichi2.libanki.undoableOp
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import com.ichi2.anki.servicelayer.MARKED_TAG
import com.ichi2.anki.servicelayer.NoteService
import com.ichi2.libanki.Card
import com.ichi2.libanki.Sound.addPlayButtons
import com.ichi2.libanki.hasTag
import com.ichi2.libanki.note
import com.ichi2.themes.Themes
import com.ichi2.utils.toRGBHex
Expand Down Expand Up @@ -132,8 +133,8 @@ class PreviewerViewModel(private val selectedCardIds: LongArray, firstIndex: Int
}

private suspend fun updateMarkIcon() {
val note = withCol { currentCard.note() }
isMarked.emit(note.hasTag(MARKED_TAG))
val isMarkedValue = withCol { currentCard.note().hasTag(MARKED_TAG) }
isMarked.emit(isMarkedValue)
}

private suspend fun showQuestion() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,7 @@ class CardContentProvider : ContentProvider() {
val currentNote = getNoteFromUri(uri, col)
val columns = projection ?: FlashCardsContract.Card.DEFAULT_PROJECTION
val rv = MatrixCursor(columns, 1)
for (currentCard: Card in currentNote.cards()) {
for (currentCard: Card in currentNote.cards(col)) {
addCardToCursor(currentCard, rv, col, columns)
}
rv
Expand Down Expand Up @@ -427,7 +427,7 @@ class CardContentProvider : ContentProvider() {
// Update tags
Timber.d("CardContentProvider: tags update...")
if (tags != null) {
currentNote.setTagsFromStr(tags.toString())
currentNote.setTagsFromStr(col, tags.toString())
}
updated++
}
Expand All @@ -438,7 +438,7 @@ class CardContentProvider : ContentProvider() {
}
}
Timber.d("CardContentProvider: Saving note...")
currentNote.flush()
currentNote.flush(col)
}
NOTES_ID_CARDS -> throw UnsupportedOperationException("Not yet implemented")
NOTES_ID_CARDS_ORD -> {
Expand Down Expand Up @@ -718,7 +718,7 @@ class CardContentProvider : ContentProvider() {
}

// Create empty note
val newNote = Note(col, model!!) // for some reason we cannot pass modelId in here
val newNote = Note(model!!) // for some reason we cannot pass modelId in here
// Set fields
// Check that correct number of flds specified
if (fldsArray.size != newNote.fields.size) {
Expand All @@ -730,11 +730,11 @@ class CardContentProvider : ContentProvider() {
// Set tags
val tags = values.getAsString(FlashCardsContract.Note.TAGS)
if (tags != null) {
newNote.setTagsFromStr(tags)
newNote.setTagsFromStr(col, tags)
}
// Add to collection
col.addNote(newNote, deckId)
for (card: Card in newNote.cards()) {
for (card: Card in newNote.cards(col)) {
card.did = deckId
col.updateCard(card)
}
Expand Down Expand Up @@ -763,7 +763,7 @@ class CardContentProvider : ContentProvider() {
// val allowEmpty = AllowEmpty.fromBoolean(values.getAsBoolean(FlashCardsContract.Note.ALLOW_EMPTY))
// Create empty note
val model = requireNotNull(col.notetypes.get(modelId)) { "Invalid modelId: $modelId" }
val newNote = Note(col, model)
val newNote = Note(model)
// Set fields
val fldsArray = Utils.splitFields(flds)
// Check that correct number of flds specified
Expand All @@ -777,7 +777,7 @@ class CardContentProvider : ContentProvider() {
}
// Set tags
if (tags != null) {
newNote.setTagsFromStr(tags)
newNote.setTagsFromStr(col, tags)
}
// Add to collection
col.addNote(newNote)
Expand Down Expand Up @@ -1176,7 +1176,7 @@ class CardContentProvider : ContentProvider() {
private fun getCard(noteId: NoteId, ord: Int, col: Collection): Card {
val currentNote = col.getNote(noteId)
var currentCard: Card? = null
for (card in currentNote.cards()) {
for (card in currentNote.cards(col)) {
if (card.ord == ord) {
currentCard = card
}
Expand Down
Loading

0 comments on commit abb6a36

Please sign in to comment.