Changing the note type, deleting the card's template or editing occlusions loses unsaved changes

Open
#23,185 0 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

Nobody has claimed this yet.

Assessment

Difficulty
3/5
Estimated time
1-2 days
Newbie friendliness
65/100
Issue type
Bug
Clarity
Mostly clear
Activity status
Active
Tech stack
android, kotlin
Domain
backend, mobile

Research direction

Start with the regression tests shown in the issue, NoteEditorExternalEditsTest.kt, and trace how the note editor handles external changes during note type conversion, card template deletion, and occlusion editing. Run the relevant note editor tests to reproduce the lost changes. Done means unsaved audio remains available or is saved after each of the three operations.

Written by the indexing model from the issue text.

Description

  • Found by David while reviewing #22885
Test
diff --git a/AnkiDroid/src/test/java/com/ichi2/anki/noteeditor/NoteEditorExternalEditsTest.kt b/AnkiDroid/src/test/java/com/ichi2/anki/noteeditor/NoteEditorExternalEditsTest.kt
new file mode 100644
--- /dev/null
+++ b/AnkiDroid/src/test/java/com/ichi2/anki/noteeditor/NoteEditorExternalEditsTest.kt
@@ -0,0 +1,152 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+
+package com.ichi2.anki.noteeditor
+
+import android.view.MotionEvent
+import android.widget.Spinner
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import com.ichi2.anki.NoteEditorActivity
+import com.ichi2.anki.NoteEditorFragment
+import com.ichi2.anki.R
+import com.ichi2.anki.RobolectricTest
+import com.ichi2.anki.common.destinations.NoteEditorDestination
+import com.ichi2.anki.dialogs.ChangeNoteTypeDialog
+import com.ichi2.anki.multimedia.MultimediaResult
+import com.ichi2.anki.multimediacard.fields.AudioRecordingField
+import org.hamcrest.MatcherAssert.assertThat
+import org.hamcrest.Matchers.containsString
+import org.hamcrest.Matchers.equalTo
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.Shadows.shadowOf
+import org.robolectric.android.controller.ActivityController
+
+@RunWith(AndroidJUnit4::class)
+class NoteEditorExternalEditsTest : RobolectricTest() {
+    override fun getCollectionStorageMode() = CollectionStorageMode.ON_DISK
+
+    @Test
+    fun `conversion preserves inserted audio`() {
+        val note = addBasicNote("Front", "Back")
+        ensureCollectionLoadIsSynchronous()
+        val controller =
+            startActivityControllerNormallyOpenCollectionWithIntent(
+                NoteEditorActivity::class.java,
+                NoteEditorDestination.EditNoteFromPreviewer(note.firstCard().id).toIntent(targetContext),
+            )
+        val editor = controller.noteEditor
+        editor.multimediaController.handleResult(MultimediaResult.Success(1, audioField("conversion-audio.3gp")))
+        advanceRobolectricLooper()
+        assertThat("the recording was inserted", editor.fieldText(1), containsString("[sound:"))
+
+        val touch = MotionEvent.obtain(0, 0, MotionEvent.ACTION_UP, 0f, 0f, 0)
+        try {
+            editor.noteTypeSpinner!!.dispatchTouchEvent(touch)
+        } finally {
+            touch.recycle()
+        }
+        advanceRobolectricLooper()
+        val dialog =
+            editor.parentFragmentManager.fragments
+                .filterIsInstance<ChangeNoteTypeDialog>()
+                .singleOrNull()
+        if (dialog != null) {
+            val destination = col.notetypes.byName("Basic (and reversed card)")!!.id
+            val spinner = dialog.requireView().findViewById<Spinner>(R.id.dest_note_type_spinner)
+            spinner.setSelection((0 until spinner.count).first { spinner.adapter.getItemId(it) == destination })
+            advanceRobolectricLooper()
+            val save = dialog.requireView().findViewById<android.view.View>(R.id.btn_save)
+            assertThat("conversion is available", save.isEnabled, equalTo(true))
+            save.performClick()
+            advanceRobolectricLooper()
+            assertThat("the conversion completed", col.getNote(note.id).noteTypeId, equalTo(destination))
+        }
+
+        if (controller.get().isFinishing) {
+            controller.pause().stop().destroy()
+            assertThat("closing saves the recording", col.getNote(note.id).fields[1], containsString("[sound:"))
+        } else {
+            assertThat("the recording remains available", editor.fieldText(1), containsString("[sound:"))
+        }
+    }
+
+    @Test
+    fun `template deletion preserves inserted audio`() {
+        val note = addNoteUsingNoteTypeName("Basic (and reversed card)", "Front", "Back")
+        val card = note.cards().first { it.ord == 0 }
+        ensureCollectionLoadIsSynchronous()
+        val controller =
+            startActivityControllerNormallyOpenCollectionWithIntent(
+                NoteEditorActivity::class.java,
+                NoteEditorDestination.EditNoteFromPreviewer(card.id).toIntent(targetContext),
+            )
+        val editor = controller.noteEditor
+        editor.multimediaController.handleResult(MultimediaResult.Success(1, audioField("template-audio.3gp")))
+        advanceRobolectricLooper()
+        assertThat("the recording was inserted", editor.fieldText(1), containsString("[sound:"))
+
+        editor.requireView().findViewById<android.view.View>(R.id.CardEditorCardsButton).performClick()
+        advanceRobolectricLooper()
+        val launched = shadowOf(controller.get()).nextStartedActivityForResult
+        if (launched != null) {
+            val notetype = col.notetypes.get(note.noteTypeId)!!
+            col.notetypes.removeTemplate(notetype, notetype.templates[card.ord])
+            col.notetypes.save(notetype)
+            assertThat("the other card survives", col.getNote(note.id).cardIds(col).size, equalTo(1))
+            shadowOf(controller.get()).receiveResult(launched.intent, android.app.Activity.RESULT_OK, android.content.Intent())
+            advanceRobolectricLooper()
+        }
+
+        if (controller.get().isFinishing) {
+            controller.pause().stop().destroy()
+            assertThat("closing saves the recording", col.getNote(note.id).fields[1], containsString("[sound:"))
+        } else {
+            assertThat("the recording remains available", editor.fieldText(1), containsString("[sound:"))
+        }
+    }
+
+    @Test
+    fun `occlusion edits preserve inserted audio`() {
+        val note =
+            col.newNote(col.notetypes.byName("Image Occlusion")!!).apply {
+                setField(0, "{{c1::x}}")
+                col.addNote(this, col.decks.selected())
+            }
+        ensureCollectionLoadIsSynchronous()
+        val controller =
+            startActivityControllerNormallyOpenCollectionWithIntent(
+                NoteEditorActivity::class.java,
+                NoteEditorDestination.EditNoteFromPreviewer(note.firstCard().id).toIntent(targetContext),
+            )
+        val editor = controller.noteEditor
+        editor.multimediaController.handleResult(MultimediaResult.Success(3, audioField("occlusion-audio.3gp")))
+        advanceRobolectricLooper()
+        assertThat("the recording was inserted", editor.fieldText(3), containsString("[sound:"))
+
+        editor.requireView().findViewById<android.view.View>(R.id.EditOcclusionsButton).performClick()
+        advanceRobolectricLooper()
+        val launched = shadowOf(controller.get()).nextStartedActivityForResult
+        if (launched != null) {
+            shadowOf(controller.get()).receiveResult(launched.intent, android.app.Activity.RESULT_OK, android.content.Intent())
+            advanceRobolectricLooper()
+        }
+
+        if (controller.get().isFinishing) {
+            controller.pause().stop().destroy()
+            assertThat("closing saves the recording", col.getNote(note.id).fields[3], containsString("[sound:"))
+        } else {
+            assertThat("the recording remains available", editor.fieldText(3), containsString("[sound:"))
+        }
+    }
+
+    private fun audioField(name: String) =
+        AudioRecordingField().apply {
+            mediaFile = tempFolder.newFile(name).apply { writeBytes(ByteArray(256)) }
+            hasTemporaryMedia = true
+        }
+
+    private val ActivityController<NoteEditorActivity>.noteEditor: NoteEditorFragment
+        get() = get().getNoteEditorFragment()
+
+    private fun NoteEditorFragment.fieldText(index: Int) = editFieldAt(index)!!.text.toString()
+}
Dominant language
Kotlin
Stars
12.3k
Forks
3.1k
Avg merge
1d 11h
Merged PRs (30d)
383

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from ankidroid/Anki-Android

All issues in ankidroid/Anki-Android

Similar issues

More Kotlin issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.