Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<Context>()
return DrawingCanvasViewModel(
Expand All @@ -97,6 +103,7 @@ class DrawingCanvasViewModelTest {
customBrushDao = FakeCustomBrushDao(),
CahierTextureBitmapStore(context),
ioDispatcher = testDispatcher,
applicationScope = applicationScope,
)
}

Expand Down Expand Up @@ -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))
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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())
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -219,7 +230,7 @@ constructor(
historyIndex--
_uiState.update { it.copy(strokes = history[historyIndex]) }
updateUndoRedoState()
viewModelScope.launch { saveStrokes() }
saveStrokes()
}
}

Expand All @@ -228,7 +239,7 @@ constructor(
historyIndex++
_uiState.update { it.copy(strokes = history[historyIndex]) }
updateUndoRedoState()
viewModelScope.launch { saveStrokes() }
saveStrokes()
}
}

Expand Down Expand Up @@ -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)
}
}
}
}

Expand All @@ -343,7 +367,7 @@ constructor(
val currentStrokes = history.getOrElse(historyIndex) { emptyList() }
val newStrokes = currentStrokes + finishedStrokes
updateStrokes(newStrokes)
viewModelScope.launch { saveStrokes() }
saveStrokes()
}

fun startErase() {
Expand All @@ -352,7 +376,7 @@ constructor(

fun endErase() {
previousPoint = null
viewModelScope.launch { saveStrokes() }
saveStrokes()
}

fun erase(x: Float, y: Float) {
Expand Down Expand Up @@ -449,7 +473,7 @@ constructor(
fun clearStrokes() {
if (_uiState.value.strokes.isNotEmpty()) {
updateStrokes(emptyList())
viewModelScope.launch { saveStrokes() }
saveStrokes()
}
}

Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ class FakeNotesRepository : NotesRepository {
var getNoteStrokesCallCount: Int = 0
private set

var updateNoteStrokesCallCount: Int = 0
private set

fun getNotes(): List<Note> = notesFlow.value.values.toList()

override fun getAllNotesStream(): Flow<List<Note>> {
Expand Down Expand Up @@ -82,6 +85,7 @@ class FakeNotesRepository : NotesRepository {
strokes: List<Stroke>,
clientBrushFamilyId: String?,
) {
updateNoteStrokesCallCount++
strokesFlow.update {
val current = LinkedHashMap(it)
current[noteId] = strokes
Expand Down