From 04885202293c6aea6bace7f21c7519bed2a41690 Mon Sep 17 00:00:00 2001 From: yaturner Date: Wed, 21 Oct 2026 09:44:50 -0700 Subject: [PATCH 01/10] ADFA-6729: Accept file:// picks in the Manager install paths Prepares for picking add-on files from an in-app Downloads list, which hands over file:// URIs rather than SAF's content:// ones. - PluginManagerViewModel: "delete after install" deletes a file:// source directly; DocumentsContract.deleteDocument cannot, so the file stayed and an error toast appeared. - ExternalFileInstallViewModel: add onPicked(), the same processing as onReceived() without LastValueGate. The gate exists for an intent redelivered across a rotation; a user pick never is, and picking the same file again after cancelling must open the dialog again. - Doc comments that said a picked plugin is always content:// updated. Both regression tests fail with their fix reverted. Co-Authored-By: Claude Opus 5.5 --- .../ui/models/PluginManagerUiState.kt | 13 ++- .../ExternalFileInstallViewModel.kt | 10 ++ .../viewmodels/PluginManagerViewModel.kt | 13 ++- .../ExternalFileInstallViewModelTest.kt | 48 +++++++++ .../PluginManagerViewModelSourceDeleteTest.kt | 101 ++++++++++++++++++ 5 files changed, 178 insertions(+), 7 deletions(-) create mode 100644 app/src/test/java/com/itsaky/androidide/viewmodels/PluginManagerViewModelSourceDeleteTest.kt diff --git a/app/src/main/java/com/itsaky/androidide/ui/models/PluginManagerUiState.kt b/app/src/main/java/com/itsaky/androidide/ui/models/PluginManagerUiState.kt index e7eae77bc8..384e4fee53 100644 --- a/app/src/main/java/com/itsaky/androidide/ui/models/PluginManagerUiState.kt +++ b/app/src/main/java/com/itsaky/androidide/ui/models/PluginManagerUiState.kt @@ -22,10 +22,12 @@ data class PluginManagerUiState( } /** - * Where a plugin archive to install comes from - either a `content://` [Uri] the user picked via - * SAF (any provider, including third-party ones), or a plain [File] this process already owns - * (the forwarded-`.cgp` case from [com.itsaky.androidide.activities.ExternalFileInstallActivity], - * which needs no [android.content.ContentResolver] round-trip since it's already a private file). + * Where a plugin archive to install comes from - either a [Uri] the user picked, or a plain [File] + * this process already owns. A picked [Uri] is `content://` from SAF (any provider, including + * third-party ones) or `file://` from the Manager screen's Downloads list; either way it is the + * user's own file, deleted only after a successful install they asked to clean up. The [File] is + * the forwarded-`.cgp` case from [com.itsaky.androidide.activities.ExternalFileInstallActivity], + * which needs no [android.content.ContentResolver] round-trip since it's already a private file. * * [Parcelable] so the Compose install-confirmation dialog can hold one in `rememberSaveable` and * survive rotation. [Uri] is Parcelable outright; [File] is [java.io.Serializable], which @@ -73,7 +75,8 @@ sealed class PluginManagerUiEvent { ) : PluginManagerUiEvent() /** - * The SAF picker returned a `.cgp` document. Always a `content://` [Uri] - the forwarded-file + * The user picked a `.cgp`: a `content://` [Uri] from the SAF picker, or a `file://` one from + * the Manager screen's Downloads list. The forwarded-file * entry point goes straight to [PluginManagerUiEffect.ShowInstallConfirmation] with a * [PluginInstallSource.LocalFile] instead, since it needs no picker round-trip. */ diff --git a/app/src/main/java/com/itsaky/androidide/viewmodels/ExternalFileInstallViewModel.kt b/app/src/main/java/com/itsaky/androidide/viewmodels/ExternalFileInstallViewModel.kt index f2bb0c6dc3..3bce7a22ec 100644 --- a/app/src/main/java/com/itsaky/androidide/viewmodels/ExternalFileInstallViewModel.kt +++ b/app/src/main/java/com/itsaky/androidide/viewmodels/ExternalFileInstallViewModel.kt @@ -116,7 +116,17 @@ class ExternalFileInstallViewModel( /** Call once, from `Activity.onCreate()`/`onNewIntent()`, with the VIEW intent's data [Uri]. */ fun onReceived(uri: Uri) { if (!receivedUriGate.consume(uri)) return + process(uri) + } + + /** + * Call with a file the user just picked in the Manager screen. Unlike [onReceived] this is not + * gated: a pick is never redelivered across a rotation, and picking the same file again (say, + * after cancelling its confirmation) must open the dialog again rather than do nothing. + */ + fun onPicked(uri: Uri) = process(uri) + private fun process(uri: Uri) { val generation = ++currentRequestGeneration viewModelScope.launch { diff --git a/app/src/main/java/com/itsaky/androidide/viewmodels/PluginManagerViewModel.kt b/app/src/main/java/com/itsaky/androidide/viewmodels/PluginManagerViewModel.kt index c4a27463f4..8d1e49d457 100644 --- a/app/src/main/java/com/itsaky/androidide/viewmodels/PluginManagerViewModel.kt +++ b/app/src/main/java/com/itsaky/androidide/viewmodels/PluginManagerViewModel.kt @@ -519,7 +519,15 @@ class PluginManagerViewModel( private suspend fun deleteSourceDocument(uri: Uri) { withContext(Dispatchers.IO) { try { - if (!DocumentsContract.deleteDocument(contentResolver, uri)) { + // A pick from the Manager screen's Downloads list is a file:// URI, which + // DocumentsContract cannot delete (ADFA-6729). + val deleted = + if (uri.scheme == ContentResolver.SCHEME_FILE) { + File(checkNotNull(uri.path) { "file URI without a path: $uri" }).delete() + } else { + DocumentsContract.deleteDocument(contentResolver, uri) + } + if (!deleted) { _uiEffect.send( PluginManagerUiEffect.ShowError(R.string.msg_source_delete_failed), ) @@ -539,7 +547,8 @@ class PluginManagerViewModel( * Validate the picked plugin file's name off the main thread (querying a `content://` URI's * display name is a `ContentResolver` IPC call) and route to install confirmation or an error. * - * A SAF pick is always a `content://` URI, so it becomes a [PluginInstallSource.ContentUri]; + * A user pick (`content://` from SAF, or `file://` from the Downloads list) becomes a + * [PluginInstallSource.ContentUri]; * the forwarded-file path emits [PluginManagerUiEffect.ShowInstallConfirmation] with a * [PluginInstallSource.LocalFile] directly and never comes through here. */ diff --git a/app/src/test/java/com/itsaky/androidide/viewmodels/ExternalFileInstallViewModelTest.kt b/app/src/test/java/com/itsaky/androidide/viewmodels/ExternalFileInstallViewModelTest.kt index fbf2784b15..f737130a66 100644 --- a/app/src/test/java/com/itsaky/androidide/viewmodels/ExternalFileInstallViewModelTest.kt +++ b/app/src/test/java/com/itsaky/androidide/viewmodels/ExternalFileInstallViewModelTest.kt @@ -16,9 +16,12 @@ import io.mockk.every import io.mockk.mockk import io.mockk.verify import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.first import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeoutOrNull import org.junit.Before import org.junit.Rule import org.junit.Test @@ -403,4 +406,49 @@ class ExternalFileInstallViewModelTest { private fun stubTemplatesFeatureAvailable(available: Boolean) { every { templateCollectionRepository.isTemplatesFeatureAvailable() } returns available } + + // The gate exists for an intent redelivered across a rotation: the same Uri twice is one + // request. Collected with a real-time timeout because processing hops to Dispatchers.IO. + @Test + fun `onReceived ignores a repeat of the same uri`() = + runTest { + val uri = sourceUriFor("notes.txt") + + // Sequential, like a real repeat: a request still in flight is superseded by a newer one. + viewModel.onReceived(uri) + assertThat(collectErrors(maxEffects = 2)).hasSize(1) + + viewModel.onReceived(uri) + assertThat(collectErrors(maxEffects = 2)).isEmpty() + } + + // A user pick is never a redelivery: picking the same file again must be handled again. + @Test + fun `onPicked handles a repeat of the same uri`() = + runTest { + val uri = sourceUriFor("notes.txt") + + viewModel.onPicked(uri) + assertThat(collectErrors(maxEffects = 2)).hasSize(1) + + viewModel.onPicked(uri) + assertThat(collectErrors(maxEffects = 2)).hasSize(1) + } + + /** + * The ShowError effects among up to [maxEffects] effects, stopping early once none arrives + * within [perEffectMillis] of real time. + */ + private suspend fun collectErrors( + maxEffects: Int, + perEffectMillis: Long = 2_000, + ): List = + withContext(Dispatchers.Default) { + buildList { + repeat(maxEffects) { + val next = withTimeoutOrNull(perEffectMillis) { viewModel.uiEffect.first() } ?: return@buildList + if (next is ExternalFileInstallUiEffect.ShowError) add(next) + } + } + } } diff --git a/app/src/test/java/com/itsaky/androidide/viewmodels/PluginManagerViewModelSourceDeleteTest.kt b/app/src/test/java/com/itsaky/androidide/viewmodels/PluginManagerViewModelSourceDeleteTest.kt new file mode 100644 index 0000000000..fcc5d732e4 --- /dev/null +++ b/app/src/test/java/com/itsaky/androidide/viewmodels/PluginManagerViewModelSourceDeleteTest.kt @@ -0,0 +1,101 @@ +package com.itsaky.androidide.viewmodels + +import android.content.Context +import android.net.Uri +import androidx.arch.core.executor.testing.InstantTaskExecutorRule +import androidx.test.core.app.ApplicationProvider +import com.google.common.truth.Truth.assertThat +import com.itsaky.androidide.repositories.PluginRepository +import com.itsaky.androidide.ui.models.PluginInstallSource +import com.itsaky.androidide.ui.models.PluginManagerUiEffect +import com.itsaky.androidide.ui.models.PluginManagerUiEvent +import com.itsaky.androidide.viewmodel.MainDispatcherRule +import io.mockk.coEvery +import io.mockk.every +import io.mockk.mockk +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeoutOrNull +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import java.io.File + +/** + * "Delete after install" for a plugin picked from the Manager screen's Downloads list, which + * arrives as a file:// Uri rather than SAF's content:// (ADFA-6729). + */ +@RunWith(RobolectricTestRunner::class) +@OptIn(ExperimentalCoroutinesApi::class) +class PluginManagerViewModelSourceDeleteTest { + @get:Rule + val instantExecutorRule = InstantTaskExecutorRule() + + @get:Rule + val mainDispatcherRule = MainDispatcherRule() + + @get:Rule + val tempFolder = TemporaryFolder() + + private val context: Context = ApplicationProvider.getApplicationContext() + + private val pluginRepository = + mockk(relaxed = true) { + every { isPluginManagerAvailable() } returns true + coEvery { getAllPlugins() } returns Result.success(emptyList()) + coEvery { installPluginFromFile(any()) } returns Result.success(Unit) + } + + private fun newViewModel() = + PluginManagerViewModel( + pluginRepository = pluginRepository, + contentResolver = context.contentResolver, + filesDir = tempFolder.newFolder("files"), + ) + + private fun downloadedPlugin(): File = File(tempFolder.newFolder("Download"), "my-plugin.cgp").apply { writeText("cgp") } + + @Test + fun `file uri source is deleted after a successful install when asked`() = + runTest { + val source = downloadedPlugin() + val viewModel = newViewModel() + + viewModel.onEvent( + PluginManagerUiEvent.ConfirmOverwrite( + PluginInstallSource.ContentUri(Uri.fromFile(source)), + deleteSourceAfterInstall = true, + ), + ) + + // The install hops to Dispatchers.IO, so wait in real time, not virtual time. + withContext(Dispatchers.Default) { withTimeoutOrNull(5_000) { while (source.exists()) delay(20) } } + assertThat(source.exists()).isFalse() + } + + @Test + fun `file uri source is kept when not asked to delete`() = + runTest { + val source = downloadedPlugin() + val viewModel = newViewModel() + + viewModel.onEvent( + PluginManagerUiEvent.ConfirmOverwrite( + PluginInstallSource.ContentUri(Uri.fromFile(source)), + deleteSourceAfterInstall = false, + ), + ) + + // Wait for the install to finish, then check the source is untouched. + withContext(Dispatchers.Default) { + withTimeoutOrNull(5_000) { viewModel.uiEffect.first { it is PluginManagerUiEffect.ShowRestartPrompt } } + } + assertThat(source.exists()).isTrue() + } +} From ccd778bf006b5449fe7e0e43f46857b57f7c3deb Mon Sep 17 00:00:00 2001 From: yaturner Date: Wed, 21 Oct 2026 09:45:00 -0700 Subject: [PATCH 02/10] ADFA-6729: List only .cgp/.cgt files when installing from Downloads The + button opened the system file picker, which lists every file in Download: SAF filters by MIME type, and .cgp/.cgt have no registered one, so no picker arguments can narrow it. + now opens an in-app list of the files at the top level of Download that match the open tab (.cgp on Plugins, .cgt on Templates), newest first, with size and date. "Browse other folders" opens the system picker as before, so add-ons kept elsewhere stay reachable. Both kinds of pick go through one routing function, so install behaves the same. Listing lives in DownloadFilesRepository behind DownloadPickerViewModel, per the screen's UDF layering. Co-Authored-By: Claude Opus 5.5 --- .../activities/PluginManagerActivity.kt | 6 + .../com/itsaky/androidide/di/PluginModule.kt | 12 ++ .../repositories/DownloadFilesRepository.kt | 26 ++++ .../DownloadFilesRepositoryImpl.kt | 19 +++ .../ui/compose/DownloadPickerDialog.kt | 119 ++++++++++++++++++ .../androidide/ui/compose/ManagerScreen.kt | 102 ++++++++++----- .../ui/models/DownloadPickerUiState.kt | 23 ++++ .../viewmodels/DownloadPickerViewModel.kt | 44 +++++++ .../DownloadFilesRepositoryImplTest.kt | 81 ++++++++++++ .../viewmodels/DownloadPickerViewModelTest.kt | 94 ++++++++++++++ resources/src/main/res/values/strings.xml | 7 ++ 11 files changed, 499 insertions(+), 34 deletions(-) create mode 100644 app/src/main/java/com/itsaky/androidide/repositories/DownloadFilesRepository.kt create mode 100644 app/src/main/java/com/itsaky/androidide/repositories/DownloadFilesRepositoryImpl.kt create mode 100644 app/src/main/java/com/itsaky/androidide/ui/compose/DownloadPickerDialog.kt create mode 100644 app/src/main/java/com/itsaky/androidide/ui/models/DownloadPickerUiState.kt create mode 100644 app/src/main/java/com/itsaky/androidide/viewmodels/DownloadPickerViewModel.kt create mode 100644 app/src/test/java/com/itsaky/androidide/repositories/DownloadFilesRepositoryImplTest.kt create mode 100644 app/src/test/java/com/itsaky/androidide/viewmodels/DownloadPickerViewModelTest.kt diff --git a/app/src/main/java/com/itsaky/androidide/activities/PluginManagerActivity.kt b/app/src/main/java/com/itsaky/androidide/activities/PluginManagerActivity.kt index 9dcc09bbbe..0fb143f92e 100644 --- a/app/src/main/java/com/itsaky/androidide/activities/PluginManagerActivity.kt +++ b/app/src/main/java/com/itsaky/androidide/activities/PluginManagerActivity.kt @@ -11,6 +11,7 @@ import com.itsaky.androidide.databinding.ActivityPluginManagerBinding import com.itsaky.androidide.ui.compose.ManagerScreen import com.itsaky.androidide.ui.compose.theme.ManagerTheme import com.itsaky.androidide.utils.flashError +import com.itsaky.androidide.viewmodels.DownloadPickerViewModel import com.itsaky.androidide.viewmodels.ExternalFileInstallViewModel import com.itsaky.androidide.viewmodels.PluginManagerViewModel import com.itsaky.androidide.viewmodels.TemplateManagerViewModel @@ -40,6 +41,9 @@ class PluginManagerActivity : EdgeToEdgeIDEActivity() { // uses, so a template picked here goes through the identical confirm/conflict/rename path. private val externalFileInstallViewModel: ExternalFileInstallViewModel by viewModel() + // Lists the matching .cgp/.cgt files in Downloads for the + button (ADFA-6729). + private val downloadPickerViewModel: DownloadPickerViewModel by viewModel() + override fun bindLayout(): View { _binding = ActivityPluginManagerBinding.inflate(layoutInflater) return binding.root @@ -57,6 +61,7 @@ class PluginManagerActivity : EdgeToEdgeIDEActivity() { val resolvedPluginViewModel = pluginViewModel val resolvedTemplateViewModel = templateViewModel val resolvedExternalFileInstallViewModel = externalFileInstallViewModel + val resolvedDownloadPickerViewModel = downloadPickerViewModel binding.composeView.setContent { ManagerTheme { @@ -65,6 +70,7 @@ class PluginManagerActivity : EdgeToEdgeIDEActivity() { pluginViewModel = resolvedPluginViewModel, templateViewModel = resolvedTemplateViewModel, externalFileInstallViewModel = resolvedExternalFileInstallViewModel, + downloadPickerViewModel = resolvedDownloadPickerViewModel, ) } } diff --git a/app/src/main/java/com/itsaky/androidide/di/PluginModule.kt b/app/src/main/java/com/itsaky/androidide/di/PluginModule.kt index abc42ee177..828e8ecb78 100644 --- a/app/src/main/java/com/itsaky/androidide/di/PluginModule.kt +++ b/app/src/main/java/com/itsaky/androidide/di/PluginModule.kt @@ -1,10 +1,14 @@ package com.itsaky.androidide.di import com.itsaky.androidide.app.IDEApplication +import com.itsaky.androidide.repositories.DownloadFilesRepository +import com.itsaky.androidide.repositories.DownloadFilesRepositoryImpl import com.itsaky.androidide.repositories.PluginRepository import com.itsaky.androidide.repositories.PluginRepositoryImpl import com.itsaky.androidide.repositories.TemplateCollectionRepository import com.itsaky.androidide.repositories.TemplateCollectionRepositoryImpl +import com.itsaky.androidide.utils.Environment +import com.itsaky.androidide.viewmodels.DownloadPickerViewModel import com.itsaky.androidide.viewmodels.ExternalFileInstallViewModel import com.itsaky.androidide.viewmodels.PluginManagerViewModel import org.koin.android.ext.koin.androidContext @@ -30,6 +34,10 @@ val pluginModule = TemplateCollectionRepositoryImpl() } + single { + DownloadFilesRepositoryImpl(downloadDir = Environment.DOWNLOAD_DIR) + } + // ViewModel viewModel { PluginManagerViewModel( @@ -39,6 +47,10 @@ val pluginModule = ) } + viewModel { + DownloadPickerViewModel(downloadFilesRepository = get()) + } + viewModel { ExternalFileInstallViewModel( pluginRepository = get(), diff --git a/app/src/main/java/com/itsaky/androidide/repositories/DownloadFilesRepository.kt b/app/src/main/java/com/itsaky/androidide/repositories/DownloadFilesRepository.kt new file mode 100644 index 0000000000..1d72f433df --- /dev/null +++ b/app/src/main/java/com/itsaky/androidide/repositories/DownloadFilesRepository.kt @@ -0,0 +1,26 @@ +package com.itsaky.androidide.repositories + +import java.io.File + +/** A file in the Downloads folder, as offered by the Manager screen's install picker. */ +data class DownloadedFile( + val file: File, + val sizeBytes: Long, + val lastModified: Long, +) { + val name: String get() = file.name +} + +/** + * Lists add-on files in the Downloads folder by extension. + * + * The system file picker cannot do this: SAF filters by MIME type, and neither `.cgp` nor `.cgt` + * has a registered one, so it lists every file (ADFA-6729). + */ +interface DownloadFilesRepository { + /** + * Files directly in the Downloads folder (not its subfolders) whose extension is [extension], + * ignoring case, newest first. Empty if the folder is missing or unreadable. + */ + suspend fun list(extension: String): List +} diff --git a/app/src/main/java/com/itsaky/androidide/repositories/DownloadFilesRepositoryImpl.kt b/app/src/main/java/com/itsaky/androidide/repositories/DownloadFilesRepositoryImpl.kt new file mode 100644 index 0000000000..ab1ad6e3ba --- /dev/null +++ b/app/src/main/java/com/itsaky/androidide/repositories/DownloadFilesRepositoryImpl.kt @@ -0,0 +1,19 @@ +package com.itsaky.androidide.repositories + +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import java.io.File + +class DownloadFilesRepositoryImpl( + private val downloadDir: File, +) : DownloadFilesRepository { + override suspend fun list(extension: String): List = + withContext(Dispatchers.IO) { + downloadDir + .listFiles { file -> file.isFile && file.extension.equals(extension, ignoreCase = true) } + .orEmpty() + .map { file -> DownloadedFile(file, file.length(), file.lastModified()) } + // Newest first: the file the user just downloaded is the one they are looking for. + .sortedByDescending { it.lastModified } + } +} diff --git a/app/src/main/java/com/itsaky/androidide/ui/compose/DownloadPickerDialog.kt b/app/src/main/java/com/itsaky/androidide/ui/compose/DownloadPickerDialog.kt new file mode 100644 index 0000000000..ce0aed1bb4 --- /dev/null +++ b/app/src/main/java/com/itsaky/androidide/ui/compose/DownloadPickerDialog.kt @@ -0,0 +1,119 @@ +package com.itsaky.androidide.ui.compose + +import android.text.format.DateUtils +import android.text.format.Formatter +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.unit.dp +import com.itsaky.androidide.R +import com.itsaky.androidide.repositories.DownloadedFile +import com.itsaky.androidide.ui.models.AddonFileKind +import com.itsaky.androidide.ui.models.DownloadPickerUiState + +/** + * The + button's picker: the open tab's add-on files in Downloads, plus a way out to the system + * picker for files kept anywhere else. + */ +@Composable +fun DownloadPickerDialog( + state: DownloadPickerUiState.Open, + onPick: (DownloadedFile) -> Unit, + onBrowse: () -> Unit, + onDismiss: () -> Unit, +) { + AlertDialog( + onDismissRequest = onDismiss, + title = { + Text( + stringResource( + when (state.kind) { + AddonFileKind.PLUGIN -> R.string.title_choose_plugin_file + AddonFileKind.TEMPLATE -> R.string.title_choose_template_file + }, + ), + ) + }, + text = { + val files = state.files + when { + files == null -> { + Box(modifier = Modifier.fillMaxWidth().padding(16.dp), contentAlignment = Alignment.Center) { + CircularProgressIndicator() + } + } + + files.isEmpty() -> { + Text( + stringResource(R.string.msg_no_download_files, ".${state.kind.extension}"), + style = MaterialTheme.typography.bodyMedium, + ) + } + + // Scrolls: Downloads can hold many add-ons, and rows grow with the font size. + else -> { + LazyColumn { + items(files, key = { it.file.absolutePath }) { file -> + DownloadFileRow(file = file, onClick = { onPick(file) }) + HorizontalDivider() + } + } + } + } + }, + confirmButton = { + TextButton(onClick = onBrowse) { Text(stringResource(R.string.action_browse_other_folders)) } + }, + dismissButton = { + TextButton(onClick = onDismiss) { Text(stringResource(android.R.string.cancel)) } + }, + ) +} + +@Composable +private fun DownloadFileRow( + file: DownloadedFile, + onClick: () -> Unit, +) { + val context = LocalContext.current + val size = Formatter.formatShortFileSize(context, file.sizeBytes) + val date = + DateUtils.formatDateTime( + context, + file.lastModified, + DateUtils.FORMAT_SHOW_DATE or DateUtils.FORMAT_ABBREV_MONTH, + ) + Column( + modifier = + Modifier + .fillMaxWidth() + .clickable( + role = Role.Button, + onClickLabel = stringResource(R.string.action_install), + onClick = onClick, + ).padding(vertical = 12.dp), + ) { + // Not ellipsized: names like "fun-and-games-libgdx-v2.cgt" differ only at the end. + Text(file.name, style = MaterialTheme.typography.titleSmall) + Text( + stringResource(R.string.label_download_file_details, size, date), + style = MaterialTheme.typography.bodySmall, + ) + } +} diff --git a/app/src/main/java/com/itsaky/androidide/ui/compose/ManagerScreen.kt b/app/src/main/java/com/itsaky/androidide/ui/compose/ManagerScreen.kt index 9b25e89e26..62c6b18396 100644 --- a/app/src/main/java/com/itsaky/androidide/ui/compose/ManagerScreen.kt +++ b/app/src/main/java/com/itsaky/androidide/ui/compose/ManagerScreen.kt @@ -53,11 +53,14 @@ import com.itsaky.androidide.idetooltips.TooltipManager import com.itsaky.androidide.idetooltips.TooltipTag import com.itsaky.androidide.ui.compose.plugins.PluginManagerContent 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 +import com.itsaky.androidide.viewmodels.DownloadPickerViewModel import com.itsaky.androidide.viewmodels.ExternalFileInstallViewModel import com.itsaky.androidide.viewmodels.PluginManagerViewModel import com.itsaky.androidide.viewmodels.TemplateManagerViewModel @@ -156,17 +159,46 @@ fun ManagerScreen( pluginViewModel: PluginManagerViewModel, templateViewModel: TemplateManagerViewModel, externalFileInstallViewModel: ExternalFileInstallViewModel, + downloadPickerViewModel: DownloadPickerViewModel, modifier: Modifier = Modifier, ) { val pagerState = rememberPagerState(pageCount = { 2 }) val coroutineScope = rememberCoroutineScope() val rootView = LocalView.current val pluginUiState by pluginViewModel.uiState.collectAsStateWithLifecycle() + val downloadPickerState by downloadPickerViewModel.uiState.collectAsStateWithLifecycle() fun showTooltip() { TooltipManager.showIdeCategoryTooltip(activity, rootView, TooltipTag.PLUGIN_MANAGER) } + // One route for both kinds of pick: a content:// Uri from the system picker, or a file:// Uri + // from the Downloads list. Neither is ever redelivered, so the template side uses the ungated + // onPicked() and picking the same file twice opens its confirmation twice. + fun routePick(uri: Uri) { + coroutineScope.launch { + // Resolving a content:// display name is a ContentResolver IPC call. + val name = withContext(Dispatchers.IO) { uri.getFileName(activity) } + when { + name.endsWith(".$TEMPLATE_ARCHIVE_EXTENSION", ignoreCase = true) -> { + pagerState.animateScrollToPage(TAB_TEMPLATES) + externalFileInstallViewModel.onPicked(uri) + } + + name.endsWith(".$PLUGIN_ARCHIVE_EXTENSION", ignoreCase = true) -> { + // Bring the Plugins page forward first: it owns the collector for the + // resulting confirmation effect, and the pager disposes it while hidden. + pagerState.animateScrollToPage(TAB_PLUGINS) + pluginViewModel.onEvent(PluginManagerUiEvent.FileSelected(uri)) + } + + else -> { + activity.flashError(activity.getString(R.string.msg_unsupported_extension_file)) + } + } + } + } + val filePickerLauncher = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri: Uri? -> uri ?: return@rememberLauncherForActivityResult @@ -175,28 +207,41 @@ fun ManagerScreen( } catch (e: SecurityException) { log.warn("Could not take persistable URI permission", e) } - coroutineScope.launch { - // Resolving a content:// display name is a ContentResolver IPC call. - val name = withContext(Dispatchers.IO) { uri.getFileName(activity) } - when { - name.endsWith(".$TEMPLATE_ARCHIVE_EXTENSION", ignoreCase = true) -> { - pagerState.animateScrollToPage(TAB_TEMPLATES) - externalFileInstallViewModel.onReceived(uri) - } - - name.endsWith(".$PLUGIN_ARCHIVE_EXTENSION", ignoreCase = true) -> { - // Bring the Plugins page forward first: it owns the collector for the - // resulting confirmation effect, and the pager disposes it while hidden. - pagerState.animateScrollToPage(TAB_PLUGINS) - pluginViewModel.onEvent(PluginManagerUiEvent.FileSelected(uri)) - } + routePick(uri) + } - else -> { - activity.flashError(activity.getString(R.string.msg_unsupported_extension_file)) - } - } - } + // The fallback for add-ons kept outside Downloads (another folder, an SD card, a cloud drive). + fun launchSystemPicker() { + try { + // SAF filters by MIME type, not extension, and neither .cgp nor .cgt has a + // registered one. Document providers report unrecognized extensions as + // "application/octet-stream", but both are zips, and some providers (and most + // cloud providers' own mappings) report "application/zip" instead - an + // octet-stream-only filter hides those with no way to reach them. "*/*" keeps + // every provider's mapping reachable; SAF still honors this ordering for the + // initial filter. routePick() validates the actual pick, since this is only an + // approximation - and why + opens the filtered Downloads list first (ADFA-6729). + filePickerLauncher.launch(arrayOf("application/octet-stream", "application/zip", "*/*")) + } catch (e: ActivityNotFoundException) { + log.warn("No document provider available for the extension file picker", e) + activity.flashError(activity.getString(R.string.msg_no_file_manager)) } + } + + (downloadPickerState as? DownloadPickerUiState.Open)?.let { state -> + DownloadPickerDialog( + state = state, + onPick = { file -> + downloadPickerViewModel.dismiss() + routePick(Uri.fromFile(file.file)) + }, + onBrowse = { + downloadPickerViewModel.dismiss() + launchSystemPicker() + }, + onDismiss = downloadPickerViewModel::dismiss, + ) + } ExternalFileInstallDialogs( viewModel = externalFileInstallViewModel, @@ -261,20 +306,9 @@ fun ManagerScreen( // on its own - swallow that one click here. if (longPressAwareClick.consumeIfSuppressed()) return@FloatingActionButton if (pluginUiState.isInstalling) return@FloatingActionButton - try { - // SAF filters by MIME type, not extension, and neither .cgp nor .cgt has a - // registered one. Document providers report unrecognized extensions as - // "application/octet-stream", but both are zips, and some providers (and most - // cloud providers' own mappings) report "application/zip" instead - an - // octet-stream-only filter hides those with no way to reach them. "*/*" keeps - // every provider's mapping reachable; SAF still honors this ordering for the - // initial filter. The routing above validates the actual pick, since this is - // only an approximation. - filePickerLauncher.launch(arrayOf("application/octet-stream", "application/zip", "*/*")) - } catch (e: ActivityNotFoundException) { - log.warn("No document provider available for the extension file picker", e) - activity.flashError(activity.getString(R.string.msg_no_file_manager)) - } + downloadPickerViewModel.open( + if (pagerState.currentPage == TAB_TEMPLATES) AddonFileKind.TEMPLATE else AddonFileKind.PLUGIN, + ) }, modifier = Modifier.alpha(if (pluginUiState.isInstalling) DISABLED_ALPHA else 1f), interactionSource = longPressAwareClick.interactionSource, diff --git a/app/src/main/java/com/itsaky/androidide/ui/models/DownloadPickerUiState.kt b/app/src/main/java/com/itsaky/androidide/ui/models/DownloadPickerUiState.kt new file mode 100644 index 0000000000..ab337a2f41 --- /dev/null +++ b/app/src/main/java/com/itsaky/androidide/ui/models/DownloadPickerUiState.kt @@ -0,0 +1,23 @@ +package com.itsaky.androidide.ui.models + +import com.itsaky.androidide.repositories.DownloadedFile +import org.adfa.constants.PLUGIN_ARCHIVE_EXTENSION +import org.adfa.constants.TEMPLATE_ARCHIVE_EXTENSION + +/** Which add-on file type the Manager screen's install picker offers. */ +enum class AddonFileKind( + val extension: String, +) { + PLUGIN(PLUGIN_ARCHIVE_EXTENSION), + TEMPLATE(TEMPLATE_ARCHIVE_EXTENSION), +} + +sealed interface DownloadPickerUiState { + data object Hidden : DownloadPickerUiState + + /** [files] is null while the Downloads folder is still being read. */ + data class Open( + val kind: AddonFileKind, + val files: List? = null, + ) : DownloadPickerUiState +} diff --git a/app/src/main/java/com/itsaky/androidide/viewmodels/DownloadPickerViewModel.kt b/app/src/main/java/com/itsaky/androidide/viewmodels/DownloadPickerViewModel.kt new file mode 100644 index 0000000000..5bdd4f326e --- /dev/null +++ b/app/src/main/java/com/itsaky/androidide/viewmodels/DownloadPickerViewModel.kt @@ -0,0 +1,44 @@ +package com.itsaky.androidide.viewmodels + +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import com.itsaky.androidide.repositories.DownloadFilesRepository +import com.itsaky.androidide.ui.models.AddonFileKind +import com.itsaky.androidide.ui.models.DownloadPickerUiState +import kotlinx.coroutines.Job +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch + +/** + * State for the Manager screen's install picker: the `.cgp` or `.cgt` files in Downloads, + * matching the open tab. Picking a file is routed by the screen, like a system-picker result. + */ +class DownloadPickerViewModel( + private val downloadFilesRepository: DownloadFilesRepository, +) : ViewModel() { + private val _uiState = MutableStateFlow(DownloadPickerUiState.Hidden) + val uiState: StateFlow = _uiState.asStateFlow() + + private var loadJob: Job? = null + + fun open(kind: AddonFileKind) { + loadJob?.cancel() + _uiState.value = DownloadPickerUiState.Open(kind) + loadJob = + viewModelScope.launch { + val files = downloadFilesRepository.list(kind.extension) + // A dismiss or a reopen for the other tab may have happened meanwhile. + _uiState.update { state -> + if (state is DownloadPickerUiState.Open && state.kind == kind) state.copy(files = files) else state + } + } + } + + fun dismiss() { + loadJob?.cancel() + _uiState.value = DownloadPickerUiState.Hidden + } +} diff --git a/app/src/test/java/com/itsaky/androidide/repositories/DownloadFilesRepositoryImplTest.kt b/app/src/test/java/com/itsaky/androidide/repositories/DownloadFilesRepositoryImplTest.kt new file mode 100644 index 0000000000..5b01bfdf4b --- /dev/null +++ b/app/src/test/java/com/itsaky/androidide/repositories/DownloadFilesRepositoryImplTest.kt @@ -0,0 +1,81 @@ +package com.itsaky.androidide.repositories + +import com.google.common.truth.Truth.assertThat +import kotlinx.coroutines.test.runTest +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import java.io.File + +class DownloadFilesRepositoryImplTest { + @get:Rule + val tempFolder = TemporaryFolder() + + private fun file( + name: String, + modified: Long, + dir: File = tempFolder.root, + ): File = + File(dir, name).apply { + writeText("x") + setLastModified(modified) + } + + @Test + fun `lists only files with the extension, ignoring case`() = + runTest { + file("a.cgp", 1_000_000) + file("B.CGP", 2_000_000) + file("c.cgt", 3_000_000) + file("d.apk", 4_000_000) + file("e.cgp.zip", 5_000_000) + + val names = DownloadFilesRepositoryImpl(tempFolder.root).list("cgp").map { it.name } + + assertThat(names).containsExactly("a.cgp", "B.CGP") + } + + @Test + fun `newest file comes first`() = + runTest { + file("old.cgt", 1_000_000) + file("new.cgt", 3_000_000) + file("mid.cgt", 2_000_000) + + val names = DownloadFilesRepositoryImpl(tempFolder.root).list("cgt").map { it.name } + + assertThat(names).containsExactly("new.cgt", "mid.cgt", "old.cgt").inOrder() + } + + @Test + fun `ignores subfolders and directories named like an add-on`() = + runTest { + file("top.cgp", 1_000_000) + file("nested.cgp", 2_000_000, dir = tempFolder.newFolder("templates")) + tempFolder.newFolder("folder.cgp") + + val names = DownloadFilesRepositoryImpl(tempFolder.root).list("cgp").map { it.name } + + assertThat(names).containsExactly("top.cgp") + } + + @Test + fun `reports size and date`() = + runTest { + val f = File(tempFolder.root, "p.cgp").apply { writeBytes(ByteArray(1234)) } + f.setLastModified(7_000_000) + + val listed = DownloadFilesRepositoryImpl(tempFolder.root).list("cgp").single() + + assertThat(listed.sizeBytes).isEqualTo(1234) + assertThat(listed.lastModified).isEqualTo(7_000_000) + } + + @Test + fun `missing folder gives an empty list`() = + runTest { + val missing = File(tempFolder.root, "no-such-dir") + + assertThat(DownloadFilesRepositoryImpl(missing).list("cgp")).isEmpty() + } +} diff --git a/app/src/test/java/com/itsaky/androidide/viewmodels/DownloadPickerViewModelTest.kt b/app/src/test/java/com/itsaky/androidide/viewmodels/DownloadPickerViewModelTest.kt new file mode 100644 index 0000000000..c8f2c26a8a --- /dev/null +++ b/app/src/test/java/com/itsaky/androidide/viewmodels/DownloadPickerViewModelTest.kt @@ -0,0 +1,94 @@ +package com.itsaky.androidide.viewmodels + +import com.google.common.truth.Truth.assertThat +import com.itsaky.androidide.repositories.DownloadFilesRepository +import com.itsaky.androidide.repositories.DownloadedFile +import com.itsaky.androidide.ui.models.AddonFileKind +import com.itsaky.androidide.ui.models.DownloadPickerUiState +import com.itsaky.androidide.viewmodel.MainDispatcherRule +import io.mockk.coEvery +import io.mockk.mockk +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.runTest +import org.junit.Rule +import org.junit.Test +import java.io.File + +@OptIn(ExperimentalCoroutinesApi::class) +class DownloadPickerViewModelTest { + @get:Rule + val mainDispatcherRule = MainDispatcherRule() + + private val plugin = DownloadedFile(File("/dl/a.cgp"), 10, 1) + private val template = DownloadedFile(File("/dl/b.cgt"), 20, 2) + + private val repository = + mockk { + coEvery { list("cgp") } returns listOf(plugin) + coEvery { list("cgt") } returns listOf(template) + } + + @Test + fun `starts hidden`() { + assertThat(DownloadPickerViewModel(repository).uiState.value).isEqualTo(DownloadPickerUiState.Hidden) + } + + @Test + fun `plugin tab lists cgp files and template tab lists cgt files`() = + runTest { + val viewModel = DownloadPickerViewModel(repository) + + viewModel.open(AddonFileKind.PLUGIN) + assertThat(viewModel.uiState.value) + .isEqualTo(DownloadPickerUiState.Open(AddonFileKind.PLUGIN, listOf(plugin))) + + viewModel.open(AddonFileKind.TEMPLATE) + assertThat(viewModel.uiState.value) + .isEqualTo(DownloadPickerUiState.Open(AddonFileKind.TEMPLATE, listOf(template))) + } + + @Test + fun `shows loading until the folder has been read`() = + runTest { + val pending = CompletableDeferred>() + coEvery { repository.list("cgp") } coAnswers { pending.await() } + val viewModel = DownloadPickerViewModel(repository) + + viewModel.open(AddonFileKind.PLUGIN) + assertThat(viewModel.uiState.value).isEqualTo(DownloadPickerUiState.Open(AddonFileKind.PLUGIN, files = null)) + + pending.complete(listOf(plugin)) + assertThat(viewModel.uiState.value) + .isEqualTo(DownloadPickerUiState.Open(AddonFileKind.PLUGIN, listOf(plugin))) + } + + @Test + fun `a listing that finishes after dismiss does not reopen the dialog`() = + runTest { + val pending = CompletableDeferred>() + coEvery { repository.list("cgp") } coAnswers { pending.await() } + val viewModel = DownloadPickerViewModel(repository) + + viewModel.open(AddonFileKind.PLUGIN) + viewModel.dismiss() + pending.complete(listOf(plugin)) + + assertThat(viewModel.uiState.value).isEqualTo(DownloadPickerUiState.Hidden) + } + + @Test + fun `a stale listing for the other tab is not shown`() = + runTest { + val slowPlugins = CompletableDeferred>() + coEvery { repository.list("cgp") } coAnswers { slowPlugins.await() } + val viewModel = DownloadPickerViewModel(repository) + + viewModel.open(AddonFileKind.PLUGIN) + viewModel.open(AddonFileKind.TEMPLATE) + slowPlugins.complete(listOf(plugin)) + + assertThat(viewModel.uiState.value) + .isEqualTo(DownloadPickerUiState.Open(AddonFileKind.TEMPLATE, listOf(template))) + } +} diff --git a/resources/src/main/res/values/strings.xml b/resources/src/main/res/values/strings.xml index a25299926e..c321f70b7a 100644 --- a/resources/src/main/res/values/strings.xml +++ b/resources/src/main/res/values/strings.xml @@ -1315,6 +1315,13 @@ Unsupported file type. Please select a .cgp file Unsupported file type. Please select a .cgp plugin or .cgt template file No file manager found + + Choose a plugin + Choose templates + No %1$s files in Download. + Browse other folders + + %1$s ยท %2$s Failed to initialize Plugin Manager: %1$s Delete installation file after install Discover plugins From 3388e0f4a835ce04657f7907cdd6d98f30be2577 Mon Sep 17 00:00:00 2001 From: yaturner Date: Mon, 2 Nov 2026 09:00:21 -0800 Subject: [PATCH 03/10] ADFA-6729: Fail the kept-source test if the install never finishes withTimeoutOrNull let the test pass after 5s without seeing ShowRestartPrompt, so it asserted on a source that no install had touched. withTimeout fails it instead. uiEffect is a buffered Channel, so the effect cannot be missed before first() subscribes. Co-Authored-By: Claude Opus 5.5 --- .../viewmodels/PluginManagerViewModelSourceDeleteTest.kt | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/app/src/test/java/com/itsaky/androidide/viewmodels/PluginManagerViewModelSourceDeleteTest.kt b/app/src/test/java/com/itsaky/androidide/viewmodels/PluginManagerViewModelSourceDeleteTest.kt index fcc5d732e4..593e931bad 100644 --- a/app/src/test/java/com/itsaky/androidide/viewmodels/PluginManagerViewModelSourceDeleteTest.kt +++ b/app/src/test/java/com/itsaky/androidide/viewmodels/PluginManagerViewModelSourceDeleteTest.kt @@ -19,6 +19,7 @@ import kotlinx.coroutines.delay import kotlinx.coroutines.flow.first import kotlinx.coroutines.test.runTest import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeout import kotlinx.coroutines.withTimeoutOrNull import org.junit.Rule import org.junit.Test @@ -92,9 +93,9 @@ class PluginManagerViewModelSourceDeleteTest { ), ) - // Wait for the install to finish, then check the source is untouched. + // Wait for the install to finish (failing if it never does), then check the source is untouched. withContext(Dispatchers.Default) { - withTimeoutOrNull(5_000) { viewModel.uiEffect.first { it is PluginManagerUiEffect.ShowRestartPrompt } } + withTimeout(5_000) { viewModel.uiEffect.first { it is PluginManagerUiEffect.ShowRestartPrompt } } } assertThat(source.exists()).isTrue() } From 5112ea09ec69e26fc7d80c6c63c991e913984b3e Mon Sep 17 00:00:00 2001 From: yaturner Date: Mon, 2 Nov 2026 09:48:55 -0800 Subject: [PATCH 04/10] ADFA-6729: Rename PluginInstallSource.ContentUri to PickedUri Mechanical rename, no behaviour change. The type now also carries file:// URIs from the Download list, so ContentUri suggested a content:// guarantee it no longer has. A later DocumentsContract or persistable-permission call on it would break Download picks. Co-Authored-By: Claude Opus 5.5 --- .../androidide/ui/compose/ManagerScreen.kt | 2 +- .../ui/compose/plugins/PluginManagerContent.kt | 2 +- .../ui/models/PluginManagerUiState.kt | 4 ++-- .../androidide/utils/InstallTempFiles.kt | 2 +- .../viewmodels/PluginManagerViewModel.kt | 18 +++++++++--------- .../PluginManagerViewModelSourceDeleteTest.kt | 4 ++-- 6 files changed, 16 insertions(+), 16 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/ui/compose/ManagerScreen.kt b/app/src/main/java/com/itsaky/androidide/ui/compose/ManagerScreen.kt index 62c6b18396..305a206b28 100644 --- a/app/src/main/java/com/itsaky/androidide/ui/compose/ManagerScreen.kt +++ b/app/src/main/java/com/itsaky/androidide/ui/compose/ManagerScreen.kt @@ -246,7 +246,7 @@ fun ManagerScreen( ExternalFileInstallDialogs( viewModel = externalFileInstallViewModel, // A .cgp only reaches this ViewModel via the routing above, which sends plugins down the - // ContentUri path instead - so this is defensive, not a live path. + // PickedUri path instead - so this is defensive, not a live path. onForwardPlugin = { filePath -> pluginViewModel.onPendingInstallFile(filePath) }, onFinish = { templateViewModel.onEvent(TemplateManagerUiEvent.LoadTemplates) }, ) diff --git a/app/src/main/java/com/itsaky/androidide/ui/compose/plugins/PluginManagerContent.kt b/app/src/main/java/com/itsaky/androidide/ui/compose/plugins/PluginManagerContent.kt index 9c5c9793a4..ca3fc657b4 100644 --- a/app/src/main/java/com/itsaky/androidide/ui/compose/plugins/PluginManagerContent.kt +++ b/app/src/main/java/com/itsaky/androidide/ui/compose/plugins/PluginManagerContent.kt @@ -224,7 +224,7 @@ fun PluginManagerContent( }, onDismiss = { // Declining a forwarded install must dispose of the temp copy - // ExternalFileInstallActivity made for us; a user-picked ContentUri is left + // ExternalFileInstallActivity made for us; a user-picked PickedUri is left // untouched. CancelPendingInstall encapsulates that distinction. viewModel.onEvent(PluginManagerUiEvent.CancelPendingInstall(dialog.source)) dialogState = PluginManagerDialogState.None diff --git a/app/src/main/java/com/itsaky/androidide/ui/models/PluginManagerUiState.kt b/app/src/main/java/com/itsaky/androidide/ui/models/PluginManagerUiState.kt index 384e4fee53..286e919c89 100644 --- a/app/src/main/java/com/itsaky/androidide/ui/models/PluginManagerUiState.kt +++ b/app/src/main/java/com/itsaky/androidide/ui/models/PluginManagerUiState.kt @@ -35,7 +35,7 @@ data class PluginManagerUiState( */ sealed class PluginInstallSource : Parcelable { @Parcelize - data class ContentUri( + data class PickedUri( val uri: Uri, ) : PluginInstallSource() @@ -105,7 +105,7 @@ sealed class PluginManagerUiEffect { /** * Carries a [PluginInstallSource], not a bare [Uri], so both entry points share one dialog: - * the SAF pick (a [PluginInstallSource.ContentUri]) and a `.cgp` forwarded from + * the SAF pick (a [PluginInstallSource.PickedUri]) and a `.cgp` forwarded from * [com.itsaky.androidide.activities.ExternalFileInstallActivity] (a * [PluginInstallSource.LocalFile]). */ diff --git a/app/src/main/java/com/itsaky/androidide/utils/InstallTempFiles.kt b/app/src/main/java/com/itsaky/androidide/utils/InstallTempFiles.kt index 7c5b779269..6ed5f80f55 100644 --- a/app/src/main/java/com/itsaky/androidide/utils/InstallTempFiles.kt +++ b/app/src/main/java/com/itsaky/androidide/utils/InstallTempFiles.kt @@ -9,7 +9,7 @@ import java.util.concurrent.atomic.AtomicLong /** * Shared `filesDir/temp` staging area for the .cgp/.cgt install flows (ExternalFileInstallViewModel, - * and PluginManagerViewModel's ContentUri branch) - centralizes temp-file naming so both ViewModels + * and PluginManagerViewModel's PickedUri branch) - centralizes temp-file naming so both ViewModels * don't duplicate it, and sweeps orphans left behind by a hand-off that never completed (e.g. * process death between ExternalFileInstallViewModel sending ForwardToPluginManager and * PluginManagerActivity reading the pending-install-file extra). diff --git a/app/src/main/java/com/itsaky/androidide/viewmodels/PluginManagerViewModel.kt b/app/src/main/java/com/itsaky/androidide/viewmodels/PluginManagerViewModel.kt index 8d1e49d457..625477ca56 100644 --- a/app/src/main/java/com/itsaky/androidide/viewmodels/PluginManagerViewModel.kt +++ b/app/src/main/java/com/itsaky/androidide/viewmodels/PluginManagerViewModel.kt @@ -153,7 +153,7 @@ class PluginManagerViewModel( is PluginManagerUiEvent.CancelPendingInstall -> { // Only a forwarded LocalFile (our own disposable temp copy) is cleaned up here - - // nothing was installed, so a user-picked ContentUri source is never touched on + // nothing was installed, so a user-picked PickedUri source is never touched on // decline (deletion there only ever happens after a *successful* install, // matching the "delete after install" checkbox's label - there's no flag to // consult here since a decline never installs anything). @@ -336,13 +336,13 @@ class PluginManagerViewModel( _currentOperation.value = PluginOperation.Installing _uiState.update { it.copy(isInstalling = true) } - // ownedTempFile (the ContentUri case's own temp copy) is what the `finally` block + // ownedTempFile (the PickedUri case's own temp copy) is what the `finally` block // below cleans up unconditionally. Note pluginRepository.installPluginFromFile() // itself unconditionally deletes whatever `pluginFile` it's given once that's copied // into the plugins directory - that's pre-existing behavior this function doesn't // control (it also affects InstallFileAction.kt's direct callers). What // deleteSourceAfterInstall/deleteInstallSource governs below is the *original* - // source's lifecycle instead: a user-picked ContentUri is only ever deleted after a + // source's lifecycle instead: a user-picked PickedUri is only ever deleted after a // successful install (see the onSuccess/onFailure split below), while a forwarded // LocalFile temp copy is always cleaned up regardless of outcome. var ownedTempFile: File? = null @@ -361,7 +361,7 @@ class PluginManagerViewModel( source.file } - is PluginInstallSource.ContentUri -> { + is PluginInstallSource.PickedUri -> { withContext(Dispatchers.IO) { val fileName = UriFileImporter.getDisplayName(contentResolver, source.uri) val extension = @@ -412,7 +412,7 @@ class PluginManagerViewModel( ), ) // A failed install deletes nothing but our own disposable temp copy - a - // user-picked ContentUri is preserved so they can retry, matching + // user-picked PickedUri is preserved so they can retry, matching // deleteSourceAfterInstall's "delete after install [succeeds]" meaning. deleteIfLocalFile(source) } @@ -491,7 +491,7 @@ class PluginManagerViewModel( return true } - /** A user-picked ContentUri is only ever deleted after a successful install (matching the + /** A user-picked PickedUri is only ever deleted after a successful install (matching the * "delete after install" checkbox's label) - a forwarded LocalFile temp copy is disposable * regardless of outcome, so it's the only source type any non-success path cleans up here. */ private suspend fun deleteIfLocalFile(source: PluginInstallSource) { @@ -510,7 +510,7 @@ class PluginManagerViewModel( } } - is PluginInstallSource.ContentUri -> { + is PluginInstallSource.PickedUri -> { deleteSourceDocument(source.uri) } } @@ -548,7 +548,7 @@ class PluginManagerViewModel( * display name is a `ContentResolver` IPC call) and route to install confirmation or an error. * * A user pick (`content://` from SAF, or `file://` from the Downloads list) becomes a - * [PluginInstallSource.ContentUri]; + * [PluginInstallSource.PickedUri]; * the forwarded-file path emits [PluginManagerUiEffect.ShowInstallConfirmation] with a * [PluginInstallSource.LocalFile] directly and never comes through here. */ @@ -561,7 +561,7 @@ class PluginManagerViewModel( if (isSupported) { _uiEffect.send( - PluginManagerUiEffect.ShowInstallConfirmation(PluginInstallSource.ContentUri(uri)), + PluginManagerUiEffect.ShowInstallConfirmation(PluginInstallSource.PickedUri(uri)), ) } else { _uiEffect.send(PluginManagerUiEffect.ShowError(R.string.msg_unsupported_plugin_file)) diff --git a/app/src/test/java/com/itsaky/androidide/viewmodels/PluginManagerViewModelSourceDeleteTest.kt b/app/src/test/java/com/itsaky/androidide/viewmodels/PluginManagerViewModelSourceDeleteTest.kt index 593e931bad..12e548bb2b 100644 --- a/app/src/test/java/com/itsaky/androidide/viewmodels/PluginManagerViewModelSourceDeleteTest.kt +++ b/app/src/test/java/com/itsaky/androidide/viewmodels/PluginManagerViewModelSourceDeleteTest.kt @@ -70,7 +70,7 @@ class PluginManagerViewModelSourceDeleteTest { viewModel.onEvent( PluginManagerUiEvent.ConfirmOverwrite( - PluginInstallSource.ContentUri(Uri.fromFile(source)), + PluginInstallSource.PickedUri(Uri.fromFile(source)), deleteSourceAfterInstall = true, ), ) @@ -88,7 +88,7 @@ class PluginManagerViewModelSourceDeleteTest { viewModel.onEvent( PluginManagerUiEvent.ConfirmOverwrite( - PluginInstallSource.ContentUri(Uri.fromFile(source)), + PluginInstallSource.PickedUri(Uri.fromFile(source)), deleteSourceAfterInstall = false, ), ) From 1727ce43addc418e02a40f16999bbf661949a4e5 Mon Sep 17 00:00:00 2001 From: yaturner Date: Mon, 2 Nov 2026 09:50:53 -0800 Subject: [PATCH 05/10] ADFA-6729: Skip pending, trashed and core.cgt files in add-on listings On Android 11+ MediaProvider keeps a download in progress or a trashed file in its folder as .pending-- or .trashed--. Those keep the add-on extension, so the + picker and the Templates tab offered partial archives and files the user had deleted. The picker also listed a core.cgt dropped into Download, which then failed to install on its reserved name; the Templates tab already hid it. Both now list through one helper, addonFilesIn(), which skips hidden names and core.cgt and checks names before the per-entry stat. The Templates tab's item-level core.cgt filter moves into it unchanged. Co-Authored-By: Claude Opus 5.5 --- .../androidide/repositories/AddonFiles.kt | 31 +++++++++++++++++++ .../repositories/DownloadFilesRepository.kt | 3 +- .../DownloadFilesRepositoryImpl.kt | 4 +-- .../repositories/TemplateRepositoryImpl.kt | 17 ++++------ .../DownloadFilesRepositoryImplTest.kt | 24 ++++++++++++++ .../TemplateRepositoryImplTest.kt | 14 +++++++++ 6 files changed, 78 insertions(+), 15 deletions(-) create mode 100644 app/src/main/java/com/itsaky/androidide/repositories/AddonFiles.kt diff --git a/app/src/main/java/com/itsaky/androidide/repositories/AddonFiles.kt b/app/src/main/java/com/itsaky/androidide/repositories/AddonFiles.kt new file mode 100644 index 0000000000..260afe5226 --- /dev/null +++ b/app/src/main/java/com/itsaky/androidide/repositories/AddonFiles.kt @@ -0,0 +1,31 @@ +package com.itsaky.androidide.repositories + +import org.adfa.constants.TEMPLATE_CORE_ARCHIVE +import java.io.File + +/** + * Add-on archives directly in [dir] (not its subfolders) whose extension is [extension], ignoring + * case. Shared by the Templates tab and the Manager screen's + picker so the two list the same + * files. Empty if [dir] is missing or unreadable. + * + * Leaves out: + * - Hidden names. On Android 11+ MediaProvider keeps a download still in progress, or a file in + * the trash, in its folder as `.pending--` or `.trashed--`, which + * keep the add-on extension. Offering one would install a partial archive, or a file the user + * deleted. + * - The bundled core.cgt (ADFA-5645). It ships with the IDE, and installing a copy fails on its + * reserved name. + */ +internal fun addonFilesIn( + dir: File, + extension: String, +): List = + dir + // Name checks first: they are free, and isFile is a stat per entry. + .listFiles { file -> + !file.name.startsWith(".") && + file.extension.equals(extension, ignoreCase = true) && + !file.name.equals(TEMPLATE_CORE_ARCHIVE, ignoreCase = true) && + file.isFile + }.orEmpty() + .toList() diff --git a/app/src/main/java/com/itsaky/androidide/repositories/DownloadFilesRepository.kt b/app/src/main/java/com/itsaky/androidide/repositories/DownloadFilesRepository.kt index 1d72f433df..b22dfbc161 100644 --- a/app/src/main/java/com/itsaky/androidide/repositories/DownloadFilesRepository.kt +++ b/app/src/main/java/com/itsaky/androidide/repositories/DownloadFilesRepository.kt @@ -20,7 +20,8 @@ data class DownloadedFile( interface DownloadFilesRepository { /** * Files directly in the Downloads folder (not its subfolders) whose extension is [extension], - * ignoring case, newest first. Empty if the folder is missing or unreadable. + * ignoring case, newest first. Hidden files and the bundled core.cgt are left out; see + * [addonFilesIn]. Empty if the folder is missing or unreadable. */ suspend fun list(extension: String): List } diff --git a/app/src/main/java/com/itsaky/androidide/repositories/DownloadFilesRepositoryImpl.kt b/app/src/main/java/com/itsaky/androidide/repositories/DownloadFilesRepositoryImpl.kt index ab1ad6e3ba..f0b6e54272 100644 --- a/app/src/main/java/com/itsaky/androidide/repositories/DownloadFilesRepositoryImpl.kt +++ b/app/src/main/java/com/itsaky/androidide/repositories/DownloadFilesRepositoryImpl.kt @@ -9,9 +9,7 @@ class DownloadFilesRepositoryImpl( ) : DownloadFilesRepository { override suspend fun list(extension: String): List = withContext(Dispatchers.IO) { - downloadDir - .listFiles { file -> file.isFile && file.extension.equals(extension, ignoreCase = true) } - .orEmpty() + addonFilesIn(downloadDir, extension) .map { file -> DownloadedFile(file, file.length(), file.lastModified()) } // Newest first: the file the user just downloaded is the one they are looking for. .sortedByDescending { it.lastModified } diff --git a/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepositoryImpl.kt b/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepositoryImpl.kt index 01f39e310c..69df2f50a3 100644 --- a/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepositoryImpl.kt +++ b/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepositoryImpl.kt @@ -57,9 +57,10 @@ class TemplateRepositoryImpl( * (`TemplateCollectionRepository.findExistingCollision`), so any row still listed as * "not installed" is one the user can actually install. * - * The bundled `core.cgt` is excluded outright (ADFA-5645): it ships with the IDE, isn't - * something the user installed or can uninstall, and has nothing to do with this screen's - * install/uninstall/delete flows. + * The bundled `core.cgt` is excluded outright (ADFA-5645), from both folders, by + * [addonFilesIn]: it ships with the IDE, isn't something the user installed or can uninstall, + * and has nothing to do with this screen's install/uninstall/delete flows. That holds even + * when templatesDir doesn't have it yet (bootstrap incomplete) and only a Downloads copy exists. */ private fun scanTemplates(): List { val installed = cgtFilesIn(templatesDir).mapNotNull { file -> parseCgtFile(file, installed = true) } @@ -68,19 +69,13 @@ class TemplateRepositoryImpl( cgtFilesIn(downloadDir) .filterNot { file -> file.name.lowercase() in installedNames } .mapNotNull { file -> parseCgtFile(file, installed = false) } - // Filtered out of the combined list, not just `installed`: core.cgt must be excluded even - // if templatesDir doesn't have it yet (bootstrap incomplete) and only a Downloads copy exists. - return (installed + downloaded).filterNot { item -> isCoreArchive(item.name) } + return installed + downloaded } /** Case-insensitive, like the twin dedup above and `findExistingCollision`'s reserved name. */ private fun isCoreArchive(fileName: String): Boolean = fileName.equals(TEMPLATE_CORE_ARCHIVE, ignoreCase = true) - private fun cgtFilesIn(dir: File): List = - dir - .listFiles { file -> file.isFile && file.extension.equals(CGT_EXTENSION, ignoreCase = true) } - ?.sortedBy { it.name } - ?: emptyList() + private fun cgtFilesIn(dir: File): List = addonFilesIn(dir, CGT_EXTENSION).sortedBy { it.name } /** Parses a .cgt (which may bundle multiple templates) into a card item, or null if it contains no template.json. */ private fun parseCgtFile( diff --git a/app/src/test/java/com/itsaky/androidide/repositories/DownloadFilesRepositoryImplTest.kt b/app/src/test/java/com/itsaky/androidide/repositories/DownloadFilesRepositoryImplTest.kt index 5b01bfdf4b..c8e6e58cfe 100644 --- a/app/src/test/java/com/itsaky/androidide/repositories/DownloadFilesRepositoryImplTest.kt +++ b/app/src/test/java/com/itsaky/androidide/repositories/DownloadFilesRepositoryImplTest.kt @@ -59,6 +59,30 @@ class DownloadFilesRepositoryImplTest { assertThat(names).containsExactly("top.cgp") } + // MediaProvider's names for a download still in progress and a trashed file (Android 11+). + @Test + fun `leaves out pending and trashed files`() = + runTest { + file(".pending-1733000000-partial.cgp", 1_000_000) + file(".trashed-1733000000-deleted.cgp", 2_000_000) + file("real.cgp", 3_000_000) + + val names = DownloadFilesRepositoryImpl(tempFolder.root).list("cgp").map { it.name } + + assertThat(names).containsExactly("real.cgp") + } + + @Test + fun `leaves out the bundled core archive`() = + runTest { + file("Core.CGT", 1_000_000) + file("mine.cgt", 2_000_000) + + val names = DownloadFilesRepositoryImpl(tempFolder.root).list("cgt").map { it.name } + + assertThat(names).containsExactly("mine.cgt") + } + @Test fun `reports size and date`() = runTest { diff --git a/app/src/test/java/com/itsaky/androidide/repositories/TemplateRepositoryImplTest.kt b/app/src/test/java/com/itsaky/androidide/repositories/TemplateRepositoryImplTest.kt index fee8bddbd9..a2e55132ae 100644 --- a/app/src/test/java/com/itsaky/androidide/repositories/TemplateRepositoryImplTest.kt +++ b/app/src/test/java/com/itsaky/androidide/repositories/TemplateRepositoryImplTest.kt @@ -252,6 +252,20 @@ class TemplateRepositoryImplTest { assertThat(downloadDir.list()).isEmpty() } + @Test + fun listTemplateFiles_skipsPendingAndTrashedDownloads() = + runTest { + // MediaProvider's names for a download still in progress and a trashed file + // (Android 11+). Both keep the .cgt extension and must not be offered for install. + writeCgt(downloadDir, ".pending-1733000000-partial.cgt") + writeCgt(downloadDir, ".trashed-1733000000-deleted.cgt") + writeCgt(downloadDir, "real.cgt") + + val items = repository.listTemplateFiles().getOrThrow() + + assertThat(items.map { it.name }).containsExactly("real.cgt") + } + @Test fun listTemplateFiles_excludesACoreArchiveFoundOnlyInDownloads() = runTest { From da64774681f6841ae2b457e016f1ef2ee88e3a45 Mon Sep 17 00:00:00 2001 From: yaturner Date: Mon, 2 Nov 2026 09:51:29 -0800 Subject: [PATCH 06/10] ADFA-6729: Update the Manager screen KDocs for the Download picker ManagerScreen's KDoc still said + accepts either archive type on any tab, and TemplateManagerScreen's said the Templates tab has no FAB/file-picker install flow. + now lists only the open tab's files in Download, with the system picker as the fallback for either type. Comments only. Co-Authored-By: Claude Opus 5.5 --- .../itsaky/androidide/ui/compose/ManagerScreen.kt | 13 +++++++------ .../ui/compose/templates/TemplateManagerScreen.kt | 5 +++-- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/ui/compose/ManagerScreen.kt b/app/src/main/java/com/itsaky/androidide/ui/compose/ManagerScreen.kt index 305a206b28..5f4d6ac180 100644 --- a/app/src/main/java/com/itsaky/androidide/ui/compose/ManagerScreen.kt +++ b/app/src/main/java/com/itsaky/androidide/ui/compose/ManagerScreen.kt @@ -137,13 +137,14 @@ private class LongPressAwareClick( * Root screen for `PluginManagerActivity` (ADFA-4928): a single manager with two tabs, Plugins * and Templates, defaulting to Plugins. Owns the one shared Scaffold/TopAppBar. * - * The add FAB is shown on both tabs and accepts either archive type - this screen is the - * Addons Manager, and "add an addon" means the same thing whichever tab you happen to be - * looking at. The picked file is routed by extension and the matching tab is brought forward, so - * the result is visible where it landed. The discover-plugins action stays Plugins-only: it opens - * a plugin catalog, which has no meaning on the Templates tab. + * The add FAB is shown on both tabs and opens [DownloadPickerDialog], which lists only the open + * tab's archives in Download: `.cgp` on Plugins, `.cgt` on Templates (ADFA-6729). Its Browse other + * folders button falls back to the system picker, which accepts either archive type from any + * folder. Either way the picked file is routed by extension and the matching tab is brought + * forward, so the result is visible where it landed. The discover-plugins action stays + * Plugins-only: it opens a plugin catalog, which has no meaning on the Templates tab. * - * The picker launcher lives here rather than in [PluginManagerContent] because `HorizontalPager` + * The system picker's launcher lives here rather than in [PluginManagerContent] because `HorizontalPager` * disposes the off-screen page: a launcher owned by the Plugins page would not exist while the * Templates tab is showing, and the FAB is reachable from both. * diff --git a/app/src/main/java/com/itsaky/androidide/ui/compose/templates/TemplateManagerScreen.kt b/app/src/main/java/com/itsaky/androidide/ui/compose/templates/TemplateManagerScreen.kt index 4e6da44a51..c5ae026a4c 100644 --- a/app/src/main/java/com/itsaky/androidide/ui/compose/templates/TemplateManagerScreen.kt +++ b/app/src/main/java/com/itsaky/androidide/ui/compose/templates/TemplateManagerScreen.kt @@ -87,8 +87,9 @@ private data class SelectedTemplateKey( /** * Templates tab content (ADR 0009). Passively scans `Environment.TEMPLATES_DIR` + the Downloads - * folder for `.cgt` files - unlike the Plugins tab, there's no FAB/file-picker install flow here, - * matching the reference `TemplateManagerPlugin`'s design. + * folder for `.cgt` files, matching the reference `TemplateManagerPlugin`'s design. The shared + * manager screen's + button also installs a `.cgt` from this tab; that flow lives in + * [com.itsaky.androidide.ui.compose.ManagerScreen], not here. * * Content-only (no Scaffold/TopAppBar): meant to be composed as one tab's body inside the shared * manager screen alongside the Plugins tab. From 7330b50ec1baec2ae358648182eb6e89d0ea068d Mon Sep 17 00:00:00 2001 From: yaturner Date: Mon, 2 Nov 2026 09:53:45 -0800 Subject: [PATCH 07/10] ADFA-6729: Shorten the wait in the gated-repeat test The gated onReceived() call launches nothing, so its collectErrors() waited out the full 2 s timeout on every run. 300 ms is enough: a processed uri reports in about 40 ms, and with the gate removed the test still fails. The other calls keep maxEffects = 2, since each processed uri sends ShowError then Finish and collection returns as soon as both arrive. Co-Authored-By: Claude Opus 5.5 --- .../viewmodels/ExternalFileInstallViewModelTest.kt | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/app/src/test/java/com/itsaky/androidide/viewmodels/ExternalFileInstallViewModelTest.kt b/app/src/test/java/com/itsaky/androidide/viewmodels/ExternalFileInstallViewModelTest.kt index f737130a66..cf09285e24 100644 --- a/app/src/test/java/com/itsaky/androidide/viewmodels/ExternalFileInstallViewModelTest.kt +++ b/app/src/test/java/com/itsaky/androidide/viewmodels/ExternalFileInstallViewModelTest.kt @@ -418,8 +418,11 @@ class ExternalFileInstallViewModelTest { viewModel.onReceived(uri) assertThat(collectErrors(maxEffects = 2)).hasSize(1) + // Each processed uri sends ShowError then Finish, so maxEffects = 2 returns as soon as both + // arrive. The gated call launches nothing, so it would wait out the full timeout; keep + // that wait short. viewModel.onReceived(uri) - assertThat(collectErrors(maxEffects = 2)).isEmpty() + assertThat(collectErrors(maxEffects = 2, perEffectMillis = 300)).isEmpty() } // A user pick is never a redelivery: picking the same file again must be handled again. From c51bda9c9e45fd0d9c67febae7db3a0220801ae0 Mon Sep 17 00:00:00 2001 From: yaturner Date: Mon, 2 Nov 2026 09:57:55 -0800 Subject: [PATCH 08/10] ADFA-6729: Show help on long-press in the Download picker A long-press on a file row or on Browse other folders shows the Add-ons Manager's screen-level tooltip (plugin.manager), anchored on the dialog's view so it appears above the dialog. Rows use combinedClickable with a long-click label, like the toolbar's download action. Browse is a TextButton, so it reuses the screen's rememberLongPressInteractionSource (now internal) to detect the hold and drop the click that ends it. A picker-specific tag needs its text added through OfflineDocumentationTools: the database now uses the 3.0 tooltip schema and dictionary-compressed pages, so a hand-written docs/docdb script would be wrong. A new tag without text would show the "no tooltip" fallback, so this reuses the live screen tooltip until then. Co-Authored-By: Claude Opus 5.5 --- .../ui/compose/DownloadPickerDialog.kt | 31 ++++++++++++++++--- .../androidide/ui/compose/ManagerScreen.kt | 7 +++-- 2 files changed, 32 insertions(+), 6 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/ui/compose/DownloadPickerDialog.kt b/app/src/main/java/com/itsaky/androidide/ui/compose/DownloadPickerDialog.kt index ce0aed1bb4..e14c87ce06 100644 --- a/app/src/main/java/com/itsaky/androidide/ui/compose/DownloadPickerDialog.kt +++ b/app/src/main/java/com/itsaky/androidide/ui/compose/DownloadPickerDialog.kt @@ -2,7 +2,9 @@ package com.itsaky.androidide.ui.compose import android.text.format.DateUtils import android.text.format.Formatter -import androidx.compose.foundation.clickable +import android.view.View +import androidx.compose.foundation.ExperimentalFoundationApi +import androidx.compose.foundation.combinedClickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth @@ -19,6 +21,7 @@ import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalView import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.Role import androidx.compose.ui.unit.dp @@ -30,6 +33,9 @@ import com.itsaky.androidide.ui.models.DownloadPickerUiState /** * The + button's picker: the open tab's add-on files in Downloads, plus a way out to the system * picker for files kept anywhere else. + * + * Long-press on a file row or on Browse other folders calls [onShowHelp] with the dialog's own + * view, to anchor the help popup above the dialog. */ @Composable fun DownloadPickerDialog( @@ -37,6 +43,7 @@ fun DownloadPickerDialog( onPick: (DownloadedFile) -> Unit, onBrowse: () -> Unit, onDismiss: () -> Unit, + onShowHelp: (anchor: View) -> Unit, ) { AlertDialog( onDismissRequest = onDismiss, @@ -70,7 +77,7 @@ fun DownloadPickerDialog( else -> { LazyColumn { items(files, key = { it.file.absolutePath }) { file -> - DownloadFileRow(file = file, onClick = { onPick(file) }) + DownloadFileRow(file = file, onClick = { onPick(file) }, onShowHelp = onShowHelp) HorizontalDivider() } } @@ -78,7 +85,18 @@ fun DownloadPickerDialog( } }, confirmButton = { - TextButton(onClick = onBrowse) { Text(stringResource(R.string.action_browse_other_folders)) } + val view = LocalView.current + val longPressAwareClick = rememberLongPressInteractionSource { onShowHelp(view) } + TextButton( + onClick = { + // TextButton's clickable() fires on the lift that ends the long press; drop that one. + if (longPressAwareClick.consumeIfSuppressed()) return@TextButton + onBrowse() + }, + interactionSource = longPressAwareClick.interactionSource, + ) { + Text(stringResource(R.string.action_browse_other_folders)) + } }, dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(android.R.string.cancel)) } @@ -86,12 +104,15 @@ fun DownloadPickerDialog( ) } +@OptIn(ExperimentalFoundationApi::class) @Composable private fun DownloadFileRow( file: DownloadedFile, onClick: () -> Unit, + onShowHelp: (anchor: View) -> Unit, ) { val context = LocalContext.current + val view = LocalView.current val size = Formatter.formatShortFileSize(context, file.sizeBytes) val date = DateUtils.formatDateTime( @@ -103,10 +124,12 @@ private fun DownloadFileRow( modifier = Modifier .fillMaxWidth() - .clickable( + .combinedClickable( role = Role.Button, onClickLabel = stringResource(R.string.action_install), + onLongClickLabel = stringResource(R.string.cd_show_tooltip), onClick = onClick, + onLongClick = { onShowHelp(view) }, ).padding(vertical = 12.dp), ) { // Not ellipsized: names like "fun-and-games-libgdx-v2.cgt" differ only at the end. diff --git a/app/src/main/java/com/itsaky/androidide/ui/compose/ManagerScreen.kt b/app/src/main/java/com/itsaky/androidide/ui/compose/ManagerScreen.kt index 5f4d6ac180..94483bf5e0 100644 --- a/app/src/main/java/com/itsaky/androidide/ui/compose/ManagerScreen.kt +++ b/app/src/main/java/com/itsaky/androidide/ui/compose/ManagerScreen.kt @@ -97,7 +97,7 @@ private const val TAB_TEMPLATES = 1 * one click. */ @Composable -private fun rememberLongPressInteractionSource(onLongPress: () -> Unit): LongPressAwareClick { +internal fun rememberLongPressInteractionSource(onLongPress: () -> Unit): LongPressAwareClick { val interactionSource = remember { MutableInteractionSource() } val isPressed by interactionSource.collectIsPressedAsState() val longPressTimeoutMillis = LocalViewConfiguration.current.longPressTimeoutMillis @@ -121,7 +121,7 @@ private fun rememberLongPressInteractionSource(onLongPress: () -> Unit): LongPre } /** See [rememberLongPressInteractionSource]. */ -private class LongPressAwareClick( +internal class LongPressAwareClick( val interactionSource: MutableInteractionSource, private val suppressNextClick: MutableState, ) { @@ -241,6 +241,9 @@ fun ManagerScreen( launchSystemPicker() }, onDismiss = downloadPickerViewModel::dismiss, + // The screen-level tooltip until the picker has its own (ADFA-6729 review); anchored on the + // dialog's view so the popup shows above the dialog. + onShowHelp = { anchor -> TooltipManager.showIdeCategoryTooltip(activity, anchor, TooltipTag.PLUGIN_MANAGER) }, ) } From b87cd7705608ee1acc073115298d486eb267db66 Mon Sep 17 00:00:00 2001 From: yaturner Date: Mon, 2 Nov 2026 11:34:29 -0800 Subject: [PATCH 09/10] ADFA-6729: Keep installed template collections with hidden names 1727ce43a skipped hidden names in every folder, but the installer accepts a collection named ".name" and stores it as ".name.cgt" in the templates folder. That collection vanished from the Templates tab and could not be uninstalled there. Only Download needs the filter, since MediaProvider's .pending-/.trashed- files live there, so the installed listing now passes includeHidden = true. Co-Authored-By: Claude Opus 5.5 --- .../com/itsaky/androidide/repositories/AddonFiles.kt | 12 +++++++----- .../repositories/TemplateRepositoryImpl.kt | 8 ++++++-- .../repositories/TemplateRepositoryImplTest.kt | 12 ++++++++++++ 3 files changed, 25 insertions(+), 7 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/repositories/AddonFiles.kt b/app/src/main/java/com/itsaky/androidide/repositories/AddonFiles.kt index 260afe5226..b70c057ea1 100644 --- a/app/src/main/java/com/itsaky/androidide/repositories/AddonFiles.kt +++ b/app/src/main/java/com/itsaky/androidide/repositories/AddonFiles.kt @@ -9,21 +9,23 @@ import java.io.File * files. Empty if [dir] is missing or unreadable. * * Leaves out: - * - Hidden names. On Android 11+ MediaProvider keeps a download still in progress, or a file in - * the trash, in its folder as `.pending--` or `.trashed--`, which - * keep the add-on extension. Offering one would install a partial archive, or a file the user - * deleted. + * - Hidden names, unless [includeHidden]. On Android 11+ MediaProvider keeps a download still in + * progress, or a file in the trash, in its folder as `.pending--` or + * `.trashed--`, which keep the add-on extension. Offering one would install a + * partial archive, or a file the user deleted. Pass true for a folder MediaProvider does not + * manage: a collection installed as `.name` is stored as `.name.cgt` and must stay listed. * - The bundled core.cgt (ADFA-5645). It ships with the IDE, and installing a copy fails on its * reserved name. */ internal fun addonFilesIn( dir: File, extension: String, + includeHidden: Boolean = false, ): List = dir // Name checks first: they are free, and isFile is a stat per entry. .listFiles { file -> - !file.name.startsWith(".") && + (includeHidden || !file.name.startsWith(".")) && file.extension.equals(extension, ignoreCase = true) && !file.name.equals(TEMPLATE_CORE_ARCHIVE, ignoreCase = true) && file.isFile diff --git a/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepositoryImpl.kt b/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepositoryImpl.kt index 69df2f50a3..ac102d6d1a 100644 --- a/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepositoryImpl.kt +++ b/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepositoryImpl.kt @@ -63,7 +63,8 @@ class TemplateRepositoryImpl( * when templatesDir doesn't have it yet (bootstrap incomplete) and only a Downloads copy exists. */ private fun scanTemplates(): List { - val installed = cgtFilesIn(templatesDir).mapNotNull { file -> parseCgtFile(file, installed = true) } + // Hidden names count here: the installer accepts a collection named ".name". + val installed = cgtFilesIn(templatesDir, includeHidden = true).mapNotNull { file -> parseCgtFile(file, installed = true) } val installedNames = installed.mapTo(mutableSetOf()) { item -> item.name.lowercase() } val downloaded = cgtFilesIn(downloadDir) @@ -75,7 +76,10 @@ class TemplateRepositoryImpl( /** Case-insensitive, like the twin dedup above and `findExistingCollision`'s reserved name. */ private fun isCoreArchive(fileName: String): Boolean = fileName.equals(TEMPLATE_CORE_ARCHIVE, ignoreCase = true) - private fun cgtFilesIn(dir: File): List = addonFilesIn(dir, CGT_EXTENSION).sortedBy { it.name } + private fun cgtFilesIn( + dir: File, + includeHidden: Boolean = false, + ): List = addonFilesIn(dir, CGT_EXTENSION, includeHidden).sortedBy { it.name } /** Parses a .cgt (which may bundle multiple templates) into a card item, or null if it contains no template.json. */ private fun parseCgtFile( diff --git a/app/src/test/java/com/itsaky/androidide/repositories/TemplateRepositoryImplTest.kt b/app/src/test/java/com/itsaky/androidide/repositories/TemplateRepositoryImplTest.kt index a2e55132ae..4de2eb9907 100644 --- a/app/src/test/java/com/itsaky/androidide/repositories/TemplateRepositoryImplTest.kt +++ b/app/src/test/java/com/itsaky/androidide/repositories/TemplateRepositoryImplTest.kt @@ -266,6 +266,18 @@ class TemplateRepositoryImplTest { assertThat(items.map { it.name }).containsExactly("real.cgt") } + @Test + fun listTemplateFiles_keepsAnInstalledCollectionWithAHiddenName() = + runTest { + // The installer accepts a collection named ".hidden" and stores it as ".hidden.cgt"; + // it must stay listed so it can be uninstalled. + writeCgt(templatesDir, ".hidden.cgt") + + val items = repository.listTemplateFiles().getOrThrow() + + assertThat(items.map { it.name }).containsExactly(".hidden.cgt") + } + @Test fun listTemplateFiles_excludesACoreArchiveFoundOnlyInDownloads() = runTest { From ef570b4b72aa0f57736658f0c9419afb2f4659c3 Mon Sep 17 00:00:00 2001 From: yaturner Date: Tue, 3 Nov 2026 06:17:50 -0800 Subject: [PATCH 10/10] ADFA-6729: Skip only MediaProvider placeholders, not every hidden name Listings skipped every name starting with "." in Download, and b87cd7705 exempted only the templates folder. But uninstalling a collection named ".hidden" moves ".hidden.cgt" to Download under the same name, where it then vanished from the Templates tab and could not be reinstalled or deleted. addonFilesIn() now skips only MediaProvider's own placeholder names, .pending-- and .trashed-- (AOSP FileUtils.PATTERN_EXPIRES_FILE), in every folder, and the includeHidden parameter is gone. A collection the user names in that same form is not listed; that name is MediaProvider's. Co-Authored-By: Claude Opus 5.5 --- .../itsaky/androidide/repositories/AddonFiles.kt | 16 +++++++++------- .../repositories/TemplateRepositoryImpl.kt | 8 ++------ .../DownloadFilesRepositoryImplTest.kt | 11 +++++++++++ .../repositories/TemplateRepositoryImplTest.kt | 13 +++++++++++++ 4 files changed, 35 insertions(+), 13 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/repositories/AddonFiles.kt b/app/src/main/java/com/itsaky/androidide/repositories/AddonFiles.kt index b70c057ea1..3e86c1b478 100644 --- a/app/src/main/java/com/itsaky/androidide/repositories/AddonFiles.kt +++ b/app/src/main/java/com/itsaky/androidide/repositories/AddonFiles.kt @@ -9,25 +9,27 @@ import java.io.File * files. Empty if [dir] is missing or unreadable. * * Leaves out: - * - Hidden names, unless [includeHidden]. On Android 11+ MediaProvider keeps a download still in - * progress, or a file in the trash, in its folder as `.pending--` or - * `.trashed--`, which keep the add-on extension. Offering one would install a - * partial archive, or a file the user deleted. Pass true for a folder MediaProvider does not - * manage: a collection installed as `.name` is stored as `.name.cgt` and must stay listed. + * - MediaProvider's placeholders. On Android 11+ it keeps a download still in progress, or a file + * in the trash, in its folder as `.pending--` or `.trashed--`, which + * keep the add-on extension. Offering one would install a partial archive, or a file the user + * deleted. Only that exact form is skipped, not every hidden name: the installer accepts a + * collection named `.name`, stored as `.name.cgt`, and uninstalling moves it to Downloads. * - The bundled core.cgt (ADFA-5645). It ships with the IDE, and installing a copy fails on its * reserved name. */ internal fun addonFilesIn( dir: File, extension: String, - includeHidden: Boolean = false, ): List = dir // Name checks first: they are free, and isFile is a stat per entry. .listFiles { file -> - (includeHidden || !file.name.startsWith(".")) && + !MEDIA_STORE_PLACEHOLDER.matches(file.name) && file.extension.equals(extension, ignoreCase = true) && !file.name.equals(TEMPLATE_CORE_ARCHIVE, ignoreCase = true) && file.isFile }.orEmpty() .toList() + +// AOSP MediaProvider's FileUtils.PATTERN_EXPIRES_FILE, which names these files ".%s-%d-%s". +private val MEDIA_STORE_PLACEHOLDER = Regex("""^\.(pending|trashed)-\d+-.+$""", RegexOption.IGNORE_CASE) diff --git a/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepositoryImpl.kt b/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepositoryImpl.kt index ac102d6d1a..69df2f50a3 100644 --- a/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepositoryImpl.kt +++ b/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepositoryImpl.kt @@ -63,8 +63,7 @@ class TemplateRepositoryImpl( * when templatesDir doesn't have it yet (bootstrap incomplete) and only a Downloads copy exists. */ private fun scanTemplates(): List { - // Hidden names count here: the installer accepts a collection named ".name". - val installed = cgtFilesIn(templatesDir, includeHidden = true).mapNotNull { file -> parseCgtFile(file, installed = true) } + val installed = cgtFilesIn(templatesDir).mapNotNull { file -> parseCgtFile(file, installed = true) } val installedNames = installed.mapTo(mutableSetOf()) { item -> item.name.lowercase() } val downloaded = cgtFilesIn(downloadDir) @@ -76,10 +75,7 @@ class TemplateRepositoryImpl( /** Case-insensitive, like the twin dedup above and `findExistingCollision`'s reserved name. */ private fun isCoreArchive(fileName: String): Boolean = fileName.equals(TEMPLATE_CORE_ARCHIVE, ignoreCase = true) - private fun cgtFilesIn( - dir: File, - includeHidden: Boolean = false, - ): List = addonFilesIn(dir, CGT_EXTENSION, includeHidden).sortedBy { it.name } + private fun cgtFilesIn(dir: File): List = addonFilesIn(dir, CGT_EXTENSION).sortedBy { it.name } /** Parses a .cgt (which may bundle multiple templates) into a card item, or null if it contains no template.json. */ private fun parseCgtFile( diff --git a/app/src/test/java/com/itsaky/androidide/repositories/DownloadFilesRepositoryImplTest.kt b/app/src/test/java/com/itsaky/androidide/repositories/DownloadFilesRepositoryImplTest.kt index c8e6e58cfe..ac1bcf1204 100644 --- a/app/src/test/java/com/itsaky/androidide/repositories/DownloadFilesRepositoryImplTest.kt +++ b/app/src/test/java/com/itsaky/androidide/repositories/DownloadFilesRepositoryImplTest.kt @@ -72,6 +72,17 @@ class DownloadFilesRepositoryImplTest { assertThat(names).containsExactly("real.cgp") } + @Test + fun `lists hidden names that are not placeholders`() = + runTest { + file(".hidden.cgp", 1_000_000) + file(".PENDING-1733000000-partial.cgp", 2_000_000) + + val names = DownloadFilesRepositoryImpl(tempFolder.root).list("cgp").map { it.name } + + assertThat(names).containsExactly(".hidden.cgp") + } + @Test fun `leaves out the bundled core archive`() = runTest { diff --git a/app/src/test/java/com/itsaky/androidide/repositories/TemplateRepositoryImplTest.kt b/app/src/test/java/com/itsaky/androidide/repositories/TemplateRepositoryImplTest.kt index 4de2eb9907..deada2f198 100644 --- a/app/src/test/java/com/itsaky/androidide/repositories/TemplateRepositoryImplTest.kt +++ b/app/src/test/java/com/itsaky/androidide/repositories/TemplateRepositoryImplTest.kt @@ -278,6 +278,19 @@ class TemplateRepositoryImplTest { assertThat(items.map { it.name }).containsExactly(".hidden.cgt") } + @Test + fun listTemplateFiles_keepsAHiddenCollectionInDownloads() = + runTest { + // Where uninstall leaves ".hidden.cgt": in Downloads under the same name. The user must + // still be able to reinstall or delete it. (A successful uninstall reloads the global + // template provider, which unit tests cannot, so this sets up its result directly.) + writeCgt(downloadDir, ".hidden.cgt") + + val items = repository.listTemplateFiles().getOrThrow() + + assertThat(items.map { it.name to it.installed }).containsExactly(".hidden.cgt" to false) + } + @Test fun listTemplateFiles_excludesACoreArchiveFoundOnlyInDownloads() = runTest {