diff --git a/app/src/androidTest/java/com/example/cahier/features/drawing/viewmodel/DrawingCanvasViewModelTest.kt b/app/src/androidTest/java/com/example/cahier/features/drawing/viewmodel/DrawingCanvasViewModelTest.kt index b5003cd8..06af3586 100644 --- a/app/src/androidTest/java/com/example/cahier/features/drawing/viewmodel/DrawingCanvasViewModelTest.kt +++ b/app/src/androidTest/java/com/example/cahier/features/drawing/viewmodel/DrawingCanvasViewModelTest.kt @@ -37,10 +37,13 @@ import com.example.cahier.developer.brushdesigner.data.FakeCustomBrushDao import dagger.hilt.android.testing.HiltAndroidRule import dagger.hilt.android.testing.HiltAndroidTest import javax.inject.Inject +import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.StandardTestDispatcher import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.advanceUntilIdle import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.runTest import kotlinx.coroutines.test.setMain @@ -85,7 +88,10 @@ class DrawingCanvasViewModelTest { viewModel = createViewModel(noteId) } - private fun createViewModel(noteId: Long): DrawingCanvasViewModel { + private fun createViewModel( + noteId: Long, + applicationScope: CoroutineScope = CoroutineScope(testDispatcher), + ): DrawingCanvasViewModel { val savedStateHandle = SavedStateHandle(mapOf(DrawingCanvasDestination.NOTE_ID_ARG to noteId)) val context = ApplicationProvider.getApplicationContext() return DrawingCanvasViewModel( @@ -97,6 +103,7 @@ class DrawingCanvasViewModelTest { customBrushDao = FakeCustomBrushDao(), CahierTextureBitmapStore(context), ioDispatcher = testDispatcher, + applicationScope = applicationScope, ) } @@ -254,4 +261,22 @@ class DrawingCanvasViewModelTest { assertEquals(savedBrush.brushFamily, restoredViewModel.currentBrush.value.family) } + + @Test + fun onStrokesFinished_savesLatestStrokesInBackground() = runTest { + val backgroundDispatcher = StandardTestDispatcher(testScheduler) + val savingViewModel = createViewModel(noteId, CoroutineScope(backgroundDispatcher)) + val brush = Brush(StockBrushes.marker(), 10f, 1f) + val stroke1 = Stroke(brush, ImmutableStrokeInputBatch.EMPTY) + val stroke2 = Stroke(brush, ImmutableStrokeInputBatch.EMPTY) + + savingViewModel.onStrokesFinished(listOf(stroke1)) + savingViewModel.onStrokesFinished(listOf(stroke2)) + assertEquals(0, notesRepository.updateNoteStrokesCallCount) + + advanceUntilIdle() + // The save queued for stroke1 is skipped because a newer save was requested. + assertEquals(1, notesRepository.updateNoteStrokesCallCount) + assertEquals(listOf(stroke1, stroke2), notesRepository.getNoteStrokes(noteId)) + } } diff --git a/app/src/main/java/com/example/cahier/features/drawing/viewmodel/DrawingCanvasViewModel.kt b/app/src/main/java/com/example/cahier/features/drawing/viewmodel/DrawingCanvasViewModel.kt index 71f1bf8f..bd8b8333 100644 --- a/app/src/main/java/com/example/cahier/features/drawing/viewmodel/DrawingCanvasViewModel.kt +++ b/app/src/main/java/com/example/cahier/features/drawing/viewmodel/DrawingCanvasViewModel.kt @@ -63,6 +63,7 @@ import com.example.cahier.core.data.CustomBrushEntity import com.example.cahier.core.data.CustomBrushes import com.example.cahier.core.data.Note import com.example.cahier.core.data.NotesRepository +import com.example.cahier.core.di.ApplicationScope import com.example.cahier.core.di.IoDispatcher import com.example.cahier.core.navigation.DrawingCanvasDestination import com.example.cahier.core.ui.CahierUiState @@ -72,9 +73,11 @@ import dagger.hilt.android.qualifiers.ApplicationContext import ink.proto.BrushFamily as ProtoBrushFamily import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream +import java.util.concurrent.atomic.AtomicLong import java.util.zip.GZIPInputStream import javax.inject.Inject import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.ensureActive import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow @@ -83,6 +86,8 @@ import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext @HiltViewModel @@ -97,6 +102,7 @@ constructor( private val customBrushDao: CustomBrushDao, val textureStore: CahierTextureBitmapStore, @IoDispatcher private val ioDispatcher: CoroutineDispatcher, + @ApplicationScope private val applicationScope: CoroutineScope, ) : ViewModel() { private val _uiState = MutableStateFlow(CahierUiState()) @@ -150,6 +156,11 @@ constructor( private var isBrushSelectedInSession = false + // Saves run one at a time under saveMutex. Each save gets a new ID from latestSaveRequestId and + // only writes if its ID is still the latest, so a stale save never overwrites a newer one. + private val saveMutex = Mutex() + private val latestSaveRequestId = AtomicLong(0L) + init { viewModelScope.launch { var isInitialLoad = true @@ -219,7 +230,7 @@ constructor( historyIndex-- _uiState.update { it.copy(strokes = history[historyIndex]) } updateUndoRedoState() - viewModelScope.launch { saveStrokes() } + saveStrokes() } } @@ -228,7 +239,7 @@ constructor( historyIndex++ _uiState.update { it.copy(strokes = history[historyIndex]) } updateUndoRedoState() - viewModelScope.launch { saveStrokes() } + saveStrokes() } } @@ -317,15 +328,28 @@ constructor( } } - suspend fun saveStrokes() { - if (historyIndex >= 0 && historyIndex < history.size) { - val strokesToSave = history[historyIndex] - val currentBrushFamily = strokesToSave.lastOrNull()?.brush?.family - val clientBrushFamilyId = - _customBrushes.value.find { it.brushFamily == currentBrushFamily }?.name - noteRepository.updateNoteStrokes(noteId, strokesToSave, clientBrushFamilyId) - } else if (history.isEmpty()) { - noteRepository.updateNoteStrokes(noteId, emptyList(), null) + /** + * Saves the current strokes on [applicationScope], off the main thread, so serializing every + * stroke doesn't delay drawing and the save still finishes if the screen closes. Saves run one at + * a time, and a save is skipped if a newer one was requested while it waited. + */ + private fun saveStrokes() { + val strokesToSave = + when { + historyIndex in history.indices -> history[historyIndex] + history.isEmpty() -> emptyList() + else -> return + } + val currentBrushFamily = strokesToSave.lastOrNull()?.brush?.family + val clientBrushFamilyId = + _customBrushes.value.find { it.brushFamily == currentBrushFamily }?.name + val request = latestSaveRequestId.incrementAndGet() + applicationScope.launch { + saveMutex.withLock { + if (request == latestSaveRequestId.get()) { + noteRepository.updateNoteStrokes(noteId, strokesToSave, clientBrushFamilyId) + } + } } } @@ -343,7 +367,7 @@ constructor( val currentStrokes = history.getOrElse(historyIndex) { emptyList() } val newStrokes = currentStrokes + finishedStrokes updateStrokes(newStrokes) - viewModelScope.launch { saveStrokes() } + saveStrokes() } fun startErase() { @@ -352,7 +376,7 @@ constructor( fun endErase() { previousPoint = null - viewModelScope.launch { saveStrokes() } + saveStrokes() } fun erase(x: Float, y: Float) { @@ -449,7 +473,7 @@ constructor( fun clearStrokes() { if (_uiState.value.strokes.isNotEmpty()) { updateStrokes(emptyList()) - viewModelScope.launch { saveStrokes() } + saveStrokes() } } @@ -548,10 +572,6 @@ constructor( } } - override fun onCleared() { - viewModelScope.launch { saveStrokes() } - } - companion object { private const val TAG = "DrawingCanvasViewModel" private const val HIGHLIGHTER_ALPHA = 0.3f diff --git a/app/src/testShared/java/com/example/cahier/core/data/FakeNotesRepository.kt b/app/src/testShared/java/com/example/cahier/core/data/FakeNotesRepository.kt index 80312c66..d2c340c4 100644 --- a/app/src/testShared/java/com/example/cahier/core/data/FakeNotesRepository.kt +++ b/app/src/testShared/java/com/example/cahier/core/data/FakeNotesRepository.kt @@ -33,6 +33,9 @@ class FakeNotesRepository : NotesRepository { var getNoteStrokesCallCount: Int = 0 private set + var updateNoteStrokesCallCount: Int = 0 + private set + fun getNotes(): List = notesFlow.value.values.toList() override fun getAllNotesStream(): Flow> { @@ -82,6 +85,7 @@ class FakeNotesRepository : NotesRepository { strokes: List, clientBrushFamilyId: String?, ) { + updateNoteStrokesCallCount++ strokesFlow.update { val current = LinkedHashMap(it) current[noteId] = strokes