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 b87f34037d..a55eb1f502 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/AddonFiles.kt b/app/src/main/java/com/itsaky/androidide/repositories/AddonFiles.kt new file mode 100644 index 0000000000..3e86c1b478 --- /dev/null +++ b/app/src/main/java/com/itsaky/androidide/repositories/AddonFiles.kt @@ -0,0 +1,35 @@ +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: + * - 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, +): List = + dir + // Name checks first: they are free, and isFile is a stat per entry. + .listFiles { file -> + !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/DownloadFilesRepository.kt b/app/src/main/java/com/itsaky/androidide/repositories/DownloadFilesRepository.kt new file mode 100644 index 0000000000..b22dfbc161 --- /dev/null +++ b/app/src/main/java/com/itsaky/androidide/repositories/DownloadFilesRepository.kt @@ -0,0 +1,27 @@ +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. 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 new file mode 100644 index 0000000000..f0b6e54272 --- /dev/null +++ b/app/src/main/java/com/itsaky/androidide/repositories/DownloadFilesRepositoryImpl.kt @@ -0,0 +1,17 @@ +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) { + 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/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..e14c87ce06 --- /dev/null +++ b/app/src/main/java/com/itsaky/androidide/ui/compose/DownloadPickerDialog.kt @@ -0,0 +1,142 @@ +package com.itsaky.androidide.ui.compose + +import android.text.format.DateUtils +import android.text.format.Formatter +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 +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.platform.LocalView +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. + * + * 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( + state: DownloadPickerUiState.Open, + onPick: (DownloadedFile) -> Unit, + onBrowse: () -> Unit, + onDismiss: () -> Unit, + onShowHelp: (anchor: View) -> 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) }, onShowHelp = onShowHelp) + HorizontalDivider() + } + } + } + } + }, + confirmButton = { + 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)) } + }, + ) +} + +@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( + context, + file.lastModified, + DateUtils.FORMAT_SHOW_DATE or DateUtils.FORMAT_ABBREV_MONTH, + ) + Column( + modifier = + Modifier + .fillMaxWidth() + .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. + 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 6d314d3451..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 @@ -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 @@ -94,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 @@ -118,7 +121,7 @@ private fun rememberLongPressInteractionSource(onLongPress: () -> Unit): LongPre } /** See [rememberLongPressInteractionSource]. */ -private class LongPressAwareClick( +internal class LongPressAwareClick( val interactionSource: MutableInteractionSource, private val suppressNextClick: MutableState, ) { @@ -134,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 - * Add-ons Manager, and "add an add-on" 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. * @@ -156,17 +160,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,33 +208,49 @@ 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, + // 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) }, + ) + } 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) }, ) @@ -261,20 +310,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/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/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. 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/ui/models/PluginManagerUiState.kt b/app/src/main/java/com/itsaky/androidide/ui/models/PluginManagerUiState.kt index 595ead34d4..64f1f492aa 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 @@ -33,7 +35,7 @@ data class PluginManagerUiState( */ sealed class PluginInstallSource : Parcelable { @Parcelize - data class ContentUri( + data class PickedUri( val uri: Uri, ) : PluginInstallSource() @@ -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. */ @@ -102,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/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/main/java/com/itsaky/androidide/viewmodels/ExternalFileInstallViewModel.kt b/app/src/main/java/com/itsaky/androidide/viewmodels/ExternalFileInstallViewModel.kt index 53978fc2b4..f98567f33a 100644 --- a/app/src/main/java/com/itsaky/androidide/viewmodels/ExternalFileInstallViewModel.kt +++ b/app/src/main/java/com/itsaky/androidide/viewmodels/ExternalFileInstallViewModel.kt @@ -117,7 +117,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..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) } } @@ -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.PickedUri]; * the forwarded-file path emits [PluginManagerUiEffect.ShowInstallConfirmation] with a * [PluginInstallSource.LocalFile] directly and never comes through here. */ @@ -552,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/repositories/DownloadFilesRepositoryImplTest.kt b/app/src/test/java/com/itsaky/androidide/repositories/DownloadFilesRepositoryImplTest.kt new file mode 100644 index 0000000000..ac1bcf1204 --- /dev/null +++ b/app/src/test/java/com/itsaky/androidide/repositories/DownloadFilesRepositoryImplTest.kt @@ -0,0 +1,116 @@ +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") + } + + // 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 `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 { + 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 { + 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/repositories/TemplateRepositoryImplTest.kt b/app/src/test/java/com/itsaky/androidide/repositories/TemplateRepositoryImplTest.kt index fee8bddbd9..deada2f198 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,45 @@ 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_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_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 { 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/app/src/test/java/com/itsaky/androidide/viewmodels/ExternalFileInstallViewModelTest.kt b/app/src/test/java/com/itsaky/androidide/viewmodels/ExternalFileInstallViewModelTest.kt index c1bf33361c..c18f0371ec 100644 --- a/app/src/test/java/com/itsaky/androidide/viewmodels/ExternalFileInstallViewModelTest.kt +++ b/app/src/test/java/com/itsaky/androidide/viewmodels/ExternalFileInstallViewModelTest.kt @@ -17,9 +17,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 @@ -439,4 +442,52 @@ 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) + + // 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, perEffectMillis = 300)).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..12e548bb2b --- /dev/null +++ b/app/src/test/java/com/itsaky/androidide/viewmodels/PluginManagerViewModelSourceDeleteTest.kt @@ -0,0 +1,102 @@ +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.withTimeout +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.PickedUri(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.PickedUri(Uri.fromFile(source)), + deleteSourceAfterInstall = false, + ), + ) + + // Wait for the install to finish (failing if it never does), then check the source is untouched. + withContext(Dispatchers.Default) { + withTimeout(5_000) { viewModel.uiEffect.first { it is PluginManagerUiEffect.ShowRestartPrompt } } + } + assertThat(source.exists()).isTrue() + } +} diff --git a/resources/src/main/res/values/strings.xml b/resources/src/main/res/values/strings.xml index e5322481ea..676ef36758 100644 --- a/resources/src/main/res/values/strings.xml +++ b/resources/src/main/res/values/strings.xml @@ -1335,6 +1335,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