Skip to content
Open
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
2 changes: 2 additions & 0 deletions app/src/main/java/com/itsaky/androidide/di/TemplateModule.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.itsaky.androidide.di

import com.itsaky.androidide.repositories.TemplateCollectionRepository
import com.itsaky.androidide.repositories.TemplateRepository
import com.itsaky.androidide.repositories.TemplateRepositoryImpl
import com.itsaky.androidide.utils.Environment
Expand All @@ -25,6 +26,7 @@ val templateModule =
viewModel {
TemplateManagerViewModel(
templateRepository = get(),
collectionInstalls = get<TemplateCollectionRepository>().installs,
)
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.itsaky.androidide.repositories

import kotlinx.coroutines.flow.Flow
import java.io.File

/**
Expand All @@ -10,6 +11,13 @@ interface TemplateCollectionRepository {
val templateNames: List<String>,
)

/**
* Emits once after each successful [installCollection]. The install can run in another
* activity (ExternalFileInstallActivity) while the Templates tab's list is still on screen
* underneath, so the tab collects this to reload (ADFA-6967).
*/
val installs: Flow<Unit>

/**
* Parse and validate a candidate .cgt archive without installing it.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ import com.itsaky.androidide.templates.impl.zip.ZipTemplateReader
import com.itsaky.androidide.utils.Environment
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
Expand Down Expand Up @@ -63,6 +67,11 @@ class TemplateCollectionRepositoryImpl : TemplateCollectionRepository {
private fun installLock(baseName: String): Mutex = installLocks.computeIfAbsent(baseName.lowercase()) { Mutex() }
}

// No replay: a list loaded after an install already includes it. DROP_OLDEST keeps
// tryEmit() from ever failing; collectors only need to know that something changed.
private val _installs = MutableSharedFlow<Unit>(extraBufferCapacity = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST)
override val installs: SharedFlow<Unit> = _installs.asSharedFlow()

override suspend fun inspectCollection(candidateFile: File): Result<TemplateCollectionRepository.CollectionInfo> =
withContext(Dispatchers.IO) {
runCatching {
Expand Down Expand Up @@ -215,6 +224,7 @@ class TemplateCollectionRepositoryImpl : TemplateCollectionRepository {
if (!candidateFile.delete()) {
log.warn("Installed but failed to delete source temp file: {}", candidateFile.name)
}
_installs.tryEmit(Unit)
Unit
}.onFailure { exception ->
if (exception is CancellationException) throw exception
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,6 @@ import com.itsaky.androidide.ui.compose.templates.TemplateManagerScreen
import com.itsaky.androidide.ui.models.AddonFileKind
import com.itsaky.androidide.ui.models.DownloadPickerUiState
import com.itsaky.androidide.ui.models.PluginManagerUiEvent
import com.itsaky.androidide.ui.models.TemplateManagerUiEvent
import com.itsaky.androidide.utils.UrlManager
import com.itsaky.androidide.utils.flashError
import com.itsaky.androidide.utils.getFileName
Expand Down Expand Up @@ -254,7 +253,8 @@ fun ManagerScreen(
// A .cgp only reaches this ViewModel via the routing above, which sends plugins down the
// PickedUri path instead - so this is defensive, not a live path.
onForwardPlugin = { filePath -> pluginViewModel.onPendingInstallFile(filePath) },
onFinish = { templateViewModel.onEvent(TemplateManagerUiEvent.LoadTemplates) },
// The Templates tab reloads from TemplateCollectionRepository.installs, so nothing to do.
onFinish = {},
)

Scaffold(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ import com.itsaky.androidide.templates.manager.models.displayName
import com.itsaky.androidide.ui.models.TemplateManagerUiEffect
import com.itsaky.androidide.ui.models.TemplateManagerUiEvent
import com.itsaky.androidide.ui.models.TemplateManagerUiState
import kotlinx.coroutines.Job
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
Expand All @@ -23,6 +25,7 @@ import kotlinx.coroutines.launch
*/
class TemplateManagerViewModel(
private val templateRepository: TemplateRepository,
collectionInstalls: Flow<Unit>,
) : ViewModel() {
private companion object {
private const val TAG = "TemplateManagerViewModel"
Expand All @@ -34,8 +37,14 @@ class TemplateManagerViewModel(
private val _uiEffect = Channel<TemplateManagerUiEffect>(Channel.BUFFERED)
val uiEffect = _uiEffect.receiveAsFlow()

private var loadJob: Job? = null

init {
loadTemplates()
// A .cgt opened from outside the app installs in ExternalFileInstallActivity, which then
// finishes back to this screen without telling it (ADFA-6967). Reload on every install
// instead, whichever screen ran it.
viewModelScope.launch { collectionInstalls.collect { loadTemplates() } }
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

fun onEvent(event: TemplateManagerUiEvent) {
Expand All @@ -49,26 +58,33 @@ class TemplateManagerViewModel(
}
}

/**
* Scans finish in any order, so a reload cancels the scan it supersedes; otherwise an earlier
* scan finishing last would overwrite the newer list (e.g. hide a collection that just
* installed). The repository rethrows cancellation, so a cancelled scan never reaches the state.
*/
private fun loadTemplates() {
viewModelScope.launch {
_uiState.update { it.copy(isLoading = true) }

templateRepository
.listTemplateFiles()
.onSuccess { items ->
Log.d(TAG, "Loaded ${items.size} template files")
_uiState.update { it.copy(isLoading = false, items = items) }
}.onFailure { exception ->
Log.e(TAG, "Failed to load template files", exception)
_uiState.update { it.copy(isLoading = false) }
_uiEffect.send(
TemplateManagerUiEffect.ShowError(
R.string.msg_template_load_failed,
listOf(exception.message ?: ""),
),
)
}
}
loadJob?.cancel()
loadJob =
viewModelScope.launch {
_uiState.update { it.copy(isLoading = true) }

templateRepository
.listTemplateFiles()
.onSuccess { items ->
Log.d(TAG, "Loaded ${items.size} template files")
_uiState.update { it.copy(isLoading = false, items = items) }
}.onFailure { exception ->
Log.e(TAG, "Failed to load template files", exception)
_uiState.update { it.copy(isLoading = false) }
_uiEffect.send(
TemplateManagerUiEffect.ShowError(
R.string.msg_template_load_failed,
listOf(exception.message ?: ""),
),
)
}
}
}

private fun showInstallConfirmation(item: CgtFileItem) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ import com.google.common.truth.Truth.assertThat
import com.itsaky.androidide.plugins.templates.CgtTemplateBuilder
import com.itsaky.androidide.utils.Environment
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.advanceUntilIdle
import kotlinx.coroutines.test.runTest
import org.junit.After
import org.junit.Before
Expand Down Expand Up @@ -123,6 +128,40 @@ class TemplateCollectionRepositoryImplTest {
assertThat(cgt.exists()).isFalse()
}

/** Collects [TemplateCollectionRepository.installs] for the rest of the test. */
private fun TestScope.recordInstalls(): List<Unit> {
val emissions = mutableListOf<Unit>()
// Unconfined, so the collector is subscribed before this returns and records an
// emission as it happens, with no virtual-time timeout that could skip past it.
backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { repository.installs.toList(emissions) }
return emissions
}

@Test
fun `installCollection emits on installs after a successful install`() =
runTest {
val emissions = recordInstalls()
val cgt = buildCgt("Empty Activity")

assertThat(repository.installCollection(cgt, "my-templates", overwrite = false).isSuccess).isTrue()
advanceUntilIdle()

assertThat(emissions).hasSize(1)
}

@Test
fun `installCollection does not emit on installs when the install fails`() =
runTest {
val emissions = recordInstalls()
File(templatesDir, "my-templates.cgt").writeText("existing")
val cgt = buildCgt("Empty Activity")

assertThat(repository.installCollection(cgt, "my-templates", overwrite = false).isFailure).isTrue()
advanceUntilIdle()

assertThat(emissions).isEmpty()
}

@Test
fun `installCollection without overwrite fails when the destination already exists`() =
runTest {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@ import io.mockk.every
import io.mockk.mockk
import io.mockk.mockkStatic
import io.mockk.unmockkStatic
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.take
import kotlinx.coroutines.flow.toList
Expand All @@ -38,6 +40,7 @@ class TemplateManagerViewModelTest {
val mainDispatcherRule = MainDispatcherRule()

private val repository = mockk<TemplateRepository>()
private val collectionInstalls = MutableSharedFlow<Unit>(extraBufferCapacity = 1)

private val item =
CgtFileItem(
Expand Down Expand Up @@ -69,19 +72,61 @@ class TemplateManagerViewModelTest {
runTest {
coEvery { repository.listTemplateFiles() } returns Result.success(listOf(item))

val viewModel = TemplateManagerViewModel(repository)
val viewModel = TemplateManagerViewModel(repository, collectionInstalls)
advanceUntilIdle()

assertThat(viewModel.uiState.value.isLoading).isFalse()
assertThat(viewModel.uiState.value.items).containsExactly(item)
}

@Test
fun collectionInstall_reloadsTemplates() =
runTest {
// ADFA-6967: a .cgt opened from outside the app installs in another activity, and this
// list must pick it up without the user leaving the screen.
coEvery { repository.listTemplateFiles() } returnsMany
listOf(Result.success(emptyList()), Result.success(listOf(installedItem)))

val viewModel = TemplateManagerViewModel(repository, collectionInstalls)
advanceUntilIdle()
assertThat(viewModel.uiState.value.items).isEmpty()

collectionInstalls.emit(Unit)
advanceUntilIdle()

assertThat(viewModel.uiState.value.items).containsExactly(installedItem)
coVerify(exactly = 2) { repository.listTemplateFiles() }
}

@Test
fun collectionInstall_duringInitialScan_keepsTheNewerResult() =
runTest {
// The initial scan is still running when an install arrives, and finishes last. Its
// stale (empty) list must not replace the post-install one.
val initialScan = CompletableDeferred<Result<List<CgtFileItem>>>()
var calls = 0
coEvery { repository.listTemplateFiles() } coAnswers {
if (calls++ == 0) initialScan.await() else Result.success(listOf(installedItem))
}

val viewModel = TemplateManagerViewModel(repository, collectionInstalls)
advanceUntilIdle()

collectionInstalls.emit(Unit)
advanceUntilIdle()
initialScan.complete(Result.success(emptyList()))
advanceUntilIdle()

assertThat(viewModel.uiState.value.items).containsExactly(installedItem)
assertThat(viewModel.uiState.value.isLoading).isFalse()
}

@Test
fun installTemplateEvent_onlyAsksForConfirmation() =
runTest {
coEvery { repository.listTemplateFiles() } returns Result.success(emptyList())

val viewModel = TemplateManagerViewModel(repository)
val viewModel = TemplateManagerViewModel(repository, collectionInstalls)
advanceUntilIdle()

viewModel.onEvent(TemplateManagerUiEvent.InstallTemplate(item))
Expand All @@ -97,7 +142,7 @@ class TemplateManagerViewModelTest {
coEvery { repository.listTemplateFiles() } returns Result.success(emptyList())
coEvery { repository.installTemplate(item) } returns Result.success(Unit)

val viewModel = TemplateManagerViewModel(repository)
val viewModel = TemplateManagerViewModel(repository, collectionInstalls)
advanceUntilIdle()

viewModel.confirmInstallTemplate(item, deleteSourceAfterInstall = false)
Expand All @@ -113,7 +158,7 @@ class TemplateManagerViewModelTest {
coEvery { repository.installTemplate(item) } returns Result.success(Unit)
coEvery { repository.deleteDownloadFile(item) } returns Result.success(Unit)

val viewModel = TemplateManagerViewModel(repository)
val viewModel = TemplateManagerViewModel(repository, collectionInstalls)
advanceUntilIdle()

viewModel.confirmInstallTemplate(item, deleteSourceAfterInstall = true)
Expand All @@ -132,7 +177,7 @@ class TemplateManagerViewModelTest {
coEvery { repository.installTemplate(item) } returns Result.success(Unit)
coEvery { repository.deleteDownloadFile(item) } returns Result.failure(java.io.IOException("ro"))

val viewModel = TemplateManagerViewModel(repository)
val viewModel = TemplateManagerViewModel(repository, collectionInstalls)
advanceUntilIdle()

viewModel.confirmInstallTemplate(item, deleteSourceAfterInstall = true)
Expand All @@ -149,7 +194,7 @@ class TemplateManagerViewModelTest {
coEvery { repository.listTemplateFiles() } returns Result.success(emptyList())
coEvery { repository.installTemplate(item) } returns Result.failure(java.io.IOException("boom"))

val viewModel = TemplateManagerViewModel(repository)
val viewModel = TemplateManagerViewModel(repository, collectionInstalls)
advanceUntilIdle()

viewModel.confirmInstallTemplate(item, deleteSourceAfterInstall = true)
Expand All @@ -173,7 +218,7 @@ class TemplateManagerViewModelTest {
coEvery { repository.listTemplateFiles() } returns Result.success(emptyList())
coEvery { repository.installTemplate(item) } returns Result.success(Unit)

val viewModel = TemplateManagerViewModel(repository)
val viewModel = TemplateManagerViewModel(repository, collectionInstalls)
advanceUntilIdle()

viewModel.confirmInstallTemplate(item, deleteSourceAfterInstall = false)
Expand All @@ -191,7 +236,7 @@ class TemplateManagerViewModelTest {
coEvery { repository.listTemplateFiles() } returns Result.success(emptyList())
coEvery { repository.installTemplate(item) } returns Result.failure(java.io.IOException("boom"))

val viewModel = TemplateManagerViewModel(repository)
val viewModel = TemplateManagerViewModel(repository, collectionInstalls)
advanceUntilIdle()

viewModel.confirmInstallTemplate(item, deleteSourceAfterInstall = false)
Expand All @@ -210,7 +255,7 @@ class TemplateManagerViewModelTest {
// assertion below, rather than throwing inside the coroutine and hanging first().
coEvery { repository.uninstallTemplate(installedItem) } returns Result.success(Unit)

val viewModel = TemplateManagerViewModel(repository)
val viewModel = TemplateManagerViewModel(repository, collectionInstalls)
advanceUntilIdle()

viewModel.onEvent(TemplateManagerUiEvent.UninstallTemplate(installedItem))
Expand All @@ -226,7 +271,7 @@ class TemplateManagerViewModelTest {
coEvery { repository.listTemplateFiles() } returns Result.success(emptyList())
coEvery { repository.uninstallTemplate(installedItem) } returns Result.success(Unit)

val viewModel = TemplateManagerViewModel(repository)
val viewModel = TemplateManagerViewModel(repository, collectionInstalls)
advanceUntilIdle()

viewModel.confirmUninstallTemplate(installedItem)
Expand All @@ -244,7 +289,7 @@ class TemplateManagerViewModelTest {
coEvery { repository.listTemplateFiles() } returns Result.success(emptyList())
coEvery { repository.uninstallTemplate(installedItem) } returns Result.failure(java.io.IOException("boom"))

val viewModel = TemplateManagerViewModel(repository)
val viewModel = TemplateManagerViewModel(repository, collectionInstalls)
advanceUntilIdle()

viewModel.confirmUninstallTemplate(installedItem)
Expand Down
Loading