diff --git a/.gitignore b/.gitignore index 1673ebc78e..553a7825fd 100755 --- a/.gitignore +++ b/.gitignore @@ -173,6 +173,10 @@ lsp/kotlin/src/main/resources/stdlib-index.json # Large asset files (bootstrap, SDK archives, databases, dependencies) assets/core.cgt +assets/plugins/*.cgp +assets/plugins/*.CGP +assets/templates/*.cgt +assets/templates/*.CGT assets/bootstrap-*.zip assets/android-sdk-*.zip assets/release/**/data/**/*.zip.br diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 751cb7fd4d..840d5d3621 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -107,6 +107,7 @@ These structural facts shape every module. Day-to-day build *commands* live in ` - **ABI product flavors.** Every Android module *except* `:plugin-api` and `:subprojects:sqlite-js` gets two flavors on the `abi` dimension — `v7` (`armeabi-v7a`) and `v8` (`arm64-v8a`) — defined centrally. There is no flavorless variant; tasks are `assembleV8Debug`, `assembleV7Release`, etc. - **SDK levels** (`build-logic/.../build/config/BuildConfig.kt`): `COMPILE_SDK=36`, `MIN_SDK=28`, `TARGET_SDK=28`. **`TARGET_SDK` is deliberately pinned at 28:** higher targets enforce W^X (write-xor-execute), which blocks executing code from app-writable files. That is fatal for an on-device IDE that compiles and runs code (Gradle, `javac`, Termux binaries), so it is a hard requirement, not tech debt. `MIN_SDK_FOR_APPS_BUILT_WITH_COGO=16` is the floor for the apps a *user* builds with CoGo — distinct from CoGo's own `MIN_SDK`. - **Native asset bundling.** The on-device LLM (`llama-impl`) ships as a per-flavor native AAR, wired through the root `build.gradle.kts` (`bundleLlamaV8Assets` / `assembleV8Assets`, …); prebuilt per-flavor assets live under `assets/release/v7/` and `assets/release/v8/`. +- **Bundled add-ons** (ADFA-7238). A build is *fat* when `assets/plugins/*.cgp` and `assets/templates/*.cgt` exist in the repo root: release builds put them in the APK assets as `plugins/` and `templates/` (`StageBundledAddons` in `app/build.gradle.kts`), and `createAssetsZip()` adds the same entries to the debug `assets-.zip`. Both also write the bundle index `bundled-addons.tsv` (one line per add-on: entry name, size, SHA-256; empty in a thin build), so the app lists and fingerprints the bundle without opening an add-on, which a release APK stores compressed, and a rebuilt add-on of the same size changes the fingerprint. A bundle without a valid index, such as an older debug zip, is listed from its folders by name and size. A missing or empty folder is the thin build. First-run setup (`AssetsInstallationHelper`) lists the bundle (`assets/addons/BundledAddons`), installs each file in the same parallel phase through `BundledAddonInstaller` (scratch file, then rename; a plugin lands in `filesDir/plugins` as `-.cgp`, a template in `Environment.TEMPLATES_DIR`; a copy whose SHA-256 differs from the index is rejected and reported like a plugin with no readable manifest), and writes `filesDir/bundled_addons.properties` last (`BundledAddonsRecord`: bundle fingerprint, bundled plugin IDs and template files, plugin load failures not yet reported to the user). `InstallationViewModel` then reloads the plugins once, and `MainActivity` shows one error bar for the recorded failures. - **sqlite-js for apps built with CoGo** (ADFA-7082). `subprojects:sqlite-js` builds the AAR that the JavaScript-in-SQLite project template depends on: the sqlite-js release vendored (see its README), for arm64-v8a and armeabi-v7a, minSdk 26, without core-library desugaring. Nothing in CoGo depends on it. Its default entry point runs no code stored in a database; loading stored functions is a separate entry point, only for databases the app made, since loading runs their code. `test-sqlite-js.yml` runs its host tests on pull requests. The manual `release-sqlite-js.yml` publishes it to the moving `sqlite-js-latest` release, from which dev-assets fetches it into the template, as it fetches `plugin-api-latest` for the plugin template. - **Native lib compression** (ADFA-2306, ADFA-4729). The app manifest hard-codes `android:extractNativeLibs="true"` (required: the installer must materialize libs in `nativeLibraryDir`, e.g. `libshizuku.so` is an executable the adb shell runs from there). That attribute overrides the `jniLibs.useLegacyPackaging` DSL, so AGP packages `lib//*.so` deflate-compressed in **every** APK — ~5.9 MB smaller (`libtree-sitter-kotlin.so` alone is 4.18 MB → 339 kB). The trap is the `recompressApk` post-step (release always, debug in CI only): its no-compress lists in `app/build.gradle.kts` must NOT contain `"so"`, or it silently re-stores the libs and undoes the saving — which is what ADFA-2306 fixed for release and ADFA-4729 for CI debug. Locally built debug APKs (including the e2e farm's) never run that step and were always fine. - **Quick Build shares the Gradle distribution's toolchain** (ADFA-4931). `:app`'s `quickBuildDaemonZip` leaves the Kotlin compiler and eight other jars out of the daemon zip, because the on-device Gradle distribution already carries them; `QuickBuildArtifactStager` links them in at provision time. That makes the daemon's Kotlin version the distribution's, so `:quickbuild:daemon` takes its Kotlin artifacts at `org.adfa.constants.GRADLE_DISTRIBUTION_KOTLIN_VERSION`, and `:app:quickBuildDistJarCheck` fails the build when the distribution it packages lacks a linked jar. See [ADR 0016](docs/adr/0016-quick-build-compiles-outside-gradle.md). diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 55c5fdec0f..61aa3a1fa4 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -26,6 +26,8 @@ import java.net.URI import java.net.URL import java.nio.file.Files import java.nio.file.StandardCopyOption +import java.security.DigestInputStream +import java.security.DigestOutputStream import java.security.MessageDigest import java.util.Properties import java.util.zip.CRC32 @@ -691,10 +693,113 @@ val quickBuildDaemonZip = } } +// A fat build bundles add-ons: the *.cgp files of assets/plugins and the *.cgt files of +// assets/templates, put in the APK assets as plugins/ and templates/. A folder that is +// missing or empty bundles nothing, and the build is the thin one. Plugin files keep their names: +// the installer names each after the plugin ID in its manifest, which Gradle does not read. +// Beside them goes the bundle index, bundled-addons.tsv (BundledAddons.INDEX_FILE): one line per +// add-on, "/\t\t", empty in a thin build. The app lists and fingerprints +// the bundle from it, so it opens no add-on at start-up and notices a rebuild of the same size. +// The one copy of the add-on file rule and the index format, for the release staging task and the +// debug zip alike. The app's side is BundledAddons (INDEX_FILE, isAddonFile, parseIndex): an index +// it rejects silently loses every copy's SHA-256 check, so these must not drift. +object BundledAddonFiles { + const val INDEX_FILE = "bundled-addons.tsv" + + /** Each bundled folder with the extension of its add-ons, plugins first. */ + val DIRS = listOf("plugins" to "cgp", "templates" to "cgt") + + /** A file named [name] is a bundled add-on: not hidden, [extension] in any case, not core.cgt. */ + fun isAddonName( + name: String, + extension: String, + ): Boolean = + !name.startsWith(".") && + name.endsWith(".$extension", ignoreCase = true) && + // core.cgt has its own asset entry; same rule as BundledAddons.isAddonFile. + !name.equals("core.cgt", ignoreCase = true) + + /** The index line of the add-on [name] in [dir]: "/\t\t\n". */ + fun indexLine( + dir: String, + name: String, + size: Long, + sha256: ByteArray, + ): String = "$dir/$name\t$size\t${sha256.joinToString("") { "%02x".format(it) }}\n" +} + +abstract class StageBundledAddons : DefaultTask() { + @get:InputFiles + @get:PathSensitive(PathSensitivity.NAME_ONLY) + abstract val pluginFiles: ConfigurableFileCollection + + @get:InputFiles + @get:PathSensitive(PathSensitivity.NAME_ONLY) + abstract val templateFiles: ConfigurableFileCollection + + @get:OutputDirectory + abstract val outputDirectory: DirectoryProperty + + @TaskAction + fun stage() { + val out = outputDirectory.get().asFile + out.deleteRecursively() + out.mkdirs() + val index = StringBuilder() + pluginFiles.files + .filter { !it.name.startsWith(".") } + .sortedBy { it.name } + .forEach { index.append(stage(it, "plugins", out)) } + templateFiles.files + .filter { !it.name.startsWith(".") } + .sortedBy { it.name } + .forEach { index.append(stage(it, "templates", out)) } + File(out, BundledAddonFiles.INDEX_FILE).writeText(index.toString()) + } + + /** Copies [file] into [dir] of [out], hashing it on the way, and returns its index line. */ + private fun stage( + file: File, + dir: String, + out: File, + ): String { + val dest = File(out, "$dir/${file.name}") + dest.parentFile.mkdirs() + val digest = MessageDigest.getInstance("SHA-256") + file.inputStream().use { input -> + DigestOutputStream(dest.outputStream(), digest).use { output -> input.copyTo(output) } + } + return BundledAddonFiles.indexLine(dir, file.name, dest.length(), digest.digest()) + } +} + +/** A bundled add-on file: directly in its folder, not hidden, with [extension] in any case. */ +fun isBundledAddon( + element: FileTreeElement, + extension: String, +): Boolean = + !element.isDirectory && + element.relativePath.segments.size == 1 && + BundledAddonFiles.isAddonName(element.name, extension) + androidComponents.onVariants { variant -> val variantName = variant.name.replaceFirstChar(Char::uppercaseChar) val flavorName = variant.flavorName!! + if (hasBundledAssets(variant)) { + val stageBundledAddons = + tasks.register("stage${variantName}BundledAddons") { + // Top-level files only, extension in any case, as the debug zip takes them. + pluginFiles.from(fileTree(rootProject.file("assets/plugins")) { include { isBundledAddon(it, "cgp") } }) + templateFiles.from(fileTree(rootProject.file("assets/templates")) { include { isBundledAddon(it, "cgt") } }) + } + // AGP sets the task's outputDirectory: build/generated/assets/. + variant.sources.assets?.addGeneratedSourceDirectory( + stageBundledAddons, + StageBundledAddons::outputDirectory, + ) + } + val copyRuntimeAar = tasks.register("copy${variantName}QuickBuildRuntimeAar") { val runtimeProject = rootProject.project(":quickbuild:runtime") @@ -1038,6 +1143,28 @@ fun createAssetsZip(arch: String) { filePath.inputStream().use { input -> input.copyTo(zipOut) } zipOut.closeEntry() } + + // Add-ons of a fat build, as plugins/ and templates/; none in a thin one. Then the + // bundle index, as StageBundledAddons writes it for a release build. + val index = StringBuilder() + BundledAddonFiles.DIRS.forEach { (dirName, extension) -> + sourceDir + .resolve(dirName) + .listFiles { file -> file.isFile && BundledAddonFiles.isAddonName(file.name, extension) } + .orEmpty() + .sortedBy { it.name } + .forEach { file -> + project.logger.lifecycle("Zipping bundled add-on $dirName/${file.name} from ${file.absolutePath}") + val digest = MessageDigest.getInstance("SHA-256") + zipOut.putNextEntry(ZipEntry("$dirName/${file.name}")) + file.inputStream().use { input -> DigestInputStream(input, digest).copyTo(zipOut) } + zipOut.closeEntry() + index.append(BundledAddonFiles.indexLine(dirName, file.name, file.length(), digest.digest())) + } + } + zipOut.putNextEntry(ZipEntry(BundledAddonFiles.INDEX_FILE)) + zipOut.write(index.toString().toByteArray(Charsets.UTF_8)) + zipOut.closeEntry() } project.logger.lifecycle("Created ${zipFile.name} at ${zipFile.parentFile.absolutePath}") } diff --git a/app/src/main/java/com/itsaky/androidide/activities/MainActivity.kt b/app/src/main/java/com/itsaky/androidide/activities/MainActivity.kt index 9c7067929e..72ad9d62f4 100755 --- a/app/src/main/java/com/itsaky/androidide/activities/MainActivity.kt +++ b/app/src/main/java/com/itsaky/androidide/activities/MainActivity.kt @@ -47,6 +47,8 @@ import com.itsaky.androidide.analytics.IAnalyticsManager import com.itsaky.androidide.analytics.depth import com.itsaky.androidide.analytics.selector import com.itsaky.androidide.app.EdgeToEdgeIDEActivity +import com.itsaky.androidide.assets.addons.BundledAddonsRecord +import com.itsaky.androidide.assets.addons.reportFailures import com.itsaky.androidide.databinding.ActivityMainBinding import com.itsaky.androidide.deeplink.ConsumedRequests import com.itsaky.androidide.fragments.MainFragment @@ -79,6 +81,7 @@ import com.itsaky.androidide.utils.UrlManager import com.itsaky.androidide.utils.applyBottomWindowInsetsPadding import com.itsaky.androidide.utils.findValidProjects import com.itsaky.androidide.utils.flashError +import com.itsaky.androidide.utils.flashErrorTracked import com.itsaky.androidide.utils.flashInfo import com.itsaky.androidide.utils.hasVisibleDialog import com.itsaky.androidide.utils.recordProjectOpenedBookkeeping @@ -109,6 +112,7 @@ class MainActivity : EdgeToEdgeIDEActivity() { private val analyticsManager: IAnalyticsManager by inject() private val recentProjectRepository: RecentProjectRepository by inject() private var feedbackButtonManager: FeedbackButtonManager? = null + private var reportingBundledFailures = false // Where the current touch on the toolbar began; null outside a touch (e.g. a TalkBack // long-press), which counts as the app name. @@ -336,6 +340,34 @@ class MainActivity : EdgeToEdgeIDEActivity() { super.onResume() MainScreenActions.register(this) feedbackButtonManager?.loadFabPosition() + reportBundledPluginFailures() + } + + /** + * Tells the user once which plugins bundled with the build did not start. The failures are + * marked reported only when the user dismisses the bar ([reportFailures]); a screen that goes + * away first, as a font scale change recreates it, shows them again next time. The report runs + * until the dismissal, and [reportingBundledFailures] keeps a resume during the report from + * starting a second one. + */ + private fun reportBundledPluginFailures() { + if (reportingBundledFailures) return + reportingBundledFailures = true + lifecycleScope.launch { + try { + val record = BundledAddonsRecord.inFilesDir(filesDir) + record.reportFailures { failures -> + flashErrorTracked( + getString( + string.msg_bundled_plugins_failed, + failures.joinToString("\n") { "${it.pluginId}: ${it.message}" }, + ), + ) + } + } finally { + reportingBundledFailures = false + } + } } override fun onPause() { diff --git a/app/src/main/java/com/itsaky/androidide/assets/AssetsInstallationHelper.kt b/app/src/main/java/com/itsaky/androidide/assets/AssetsInstallationHelper.kt index 47962fe751..ffb0ac1d03 100644 --- a/app/src/main/java/com/itsaky/androidide/assets/AssetsInstallationHelper.kt +++ b/app/src/main/java/com/itsaky/androidide/assets/AssetsInstallationHelper.kt @@ -5,6 +5,12 @@ import android.os.StatFs import androidx.annotation.WorkerThread import com.aayushatharva.brotli4j.Brotli4jLoader import com.itsaky.androidide.app.configuration.IDEBuildConfigProvider +import com.itsaky.androidide.assets.addons.BundledAddonKind +import com.itsaky.androidide.assets.addons.BundledAddons +import com.itsaky.androidide.assets.addons.BundledAddonsRecord +import com.itsaky.androidide.assets.addons.BundledAddonsState +import com.itsaky.androidide.assets.addons.BundledEntry +import com.itsaky.androidide.assets.addons.BundledPluginFailure import com.itsaky.androidide.resources.R import com.itsaky.androidide.utils.ContainedPathResolver import com.itsaky.androidide.utils.ContainedPathResolver.Resolution @@ -15,6 +21,7 @@ import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.async import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.delay +import kotlinx.coroutines.ensureActive import kotlinx.coroutines.isActive import kotlinx.coroutines.joinAll import kotlinx.coroutines.launch @@ -69,6 +76,22 @@ object AssetsInstallationHelper { private val ASSETS_INSTALLER = AssetsInstaller.CURRENT_INSTALLER const val BOOTSTRAP_ENTRY_NAME = "bootstrap.zip" + /** The entries every build installs. Add-ons a build bundles come on top, see [entriesToInstall]. */ + internal val expectedEntries = + listOf( + GRADLE_DISTRIBUTION_ARCHIVE_NAME, + ANDROID_SDK_ZIP, + DOCUMENTATION_DB, + LOCAL_MAVEN_REPO_ARCHIVE_ZIP_NAME, + BOOTSTRAP_ENTRY_NAME, + GRADLE_API_NAME_JAR_ZIP, + PLUGIN_ARTIFACTS_ZIP, + TEMPLATE_CORE_ARCHIVE, + ) + + /** [expectedEntries], then each of [bundled]; a thin build, with none, installs [expectedEntries] alone. */ + internal fun entriesToInstall(bundled: List): List = expectedEntries + bundled.map { it.entryName } + suspend fun install( context: Context, onProgress: AssetsInstallerProgressConsumer = {}, @@ -124,18 +147,6 @@ object AssetsInstallationHelper { val buildConfig = IDEBuildConfigProvider.getInstance() val cpuArch = buildConfig.cpuArch - val expectedEntries = - arrayOf( - GRADLE_DISTRIBUTION_ARCHIVE_NAME, - ANDROID_SDK_ZIP, - DOCUMENTATION_DB, - LOCAL_MAVEN_REPO_ARCHIVE_ZIP_NAME, - BOOTSTRAP_ENTRY_NAME, - GRADLE_API_NAME_JAR_ZIP, - PLUGIN_ARTIFACTS_ZIP, - TEMPLATE_CORE_ARCHIVE, - ) - val stagingDir = Files.createTempDirectory(UUID.randomUUID().toString()) logger.debug("Staging directory ({}): {}", cpuArch, stagingDir) @@ -160,17 +171,19 @@ object AssetsInstallationHelper { logAndRethrow("I/O error during preInstall", e) } + val bundledAddons = ASSETS_INSTALLER.listBundledAddons(context) + val entries = entriesToInstall(bundledAddons) + val entrySizes: Map = - expectedEntries.associateWith { entry -> - ASSETS_INSTALLER.expectedSize(entry) - } + expectedEntries.associateWith { entry -> ASSETS_INSTALLER.expectedSize(entry) } + + bundledAddons.associate { it.entryName to it.size } val totalSize = entrySizes.values.sum() val entryStatusMap = ConcurrentHashMap() val installerJobs = - expectedEntries.map { entry -> + entries.map { entry -> async { entryStatusMap[entry] = STATUS_INSTALLING @@ -233,6 +246,29 @@ object AssetsInstallationHelper { // then cancel progress updater progressUpdater.cancel() + + // A failed copy has already cancelled this scope, so joinAll() throws; this keeps the record + // unwritable after any failure even if that changes. + ensureActive() + + // Last, and only here, so a record means every file of the bundle is in place. + val installed = ASSETS_INSTALLER.installedAddons() + BundledAddonsRecord.inFilesDir(context.filesDir).write( + BundledAddonsState( + fingerprint = BundledAddons.fingerprint(bundledAddons), + pluginIds = installed.mapNotNull { it.pluginId }.sorted(), + templateFiles = + installed + .filter { it.kind == BundledAddonKind.TEMPLATE } + .mapNotNull { it.file?.name } + .sorted(), + // Add-ons rejected while copying; the main screen reports them with load failures. + failures = + installed + .mapNotNull { addon -> addon.failure?.let { BundledPluginFailure(addon.sourceName ?: "?", it) } } + .sortedBy { it.pluginId }, + ), + ) } finally { // Always run postInstall so zip/FS resources are closed (e.g. SplitAssetsInstaller.zipFile), // and always clean up the staging dir -- on any exit path, including a preInstall diff --git a/app/src/main/java/com/itsaky/androidide/assets/AssetsInstaller.kt b/app/src/main/java/com/itsaky/androidide/assets/AssetsInstaller.kt index 422cb543cd..d33376d9ac 100644 --- a/app/src/main/java/com/itsaky/androidide/assets/AssetsInstaller.kt +++ b/app/src/main/java/com/itsaky/androidide/assets/AssetsInstaller.kt @@ -4,6 +4,8 @@ import android.content.Context import androidx.annotation.WorkerThread import com.itsaky.androidide.BuildConfig import com.itsaky.androidide.app.configuration.CpuArch +import com.itsaky.androidide.assets.addons.BundledEntry +import com.itsaky.androidide.assets.addons.InstalledAddon import java.nio.file.Path /** @@ -74,4 +76,14 @@ sealed interface AssetsInstaller { * @return The expected size in bytes, or 0 if unknown. */ fun expectedSize(entryName: String): Long + + /** + * Lists the add-on files (plugins and templates) this build bundles; none for a thin build. + * Call it once per installation, after [preInstall]: it also forgets the add-ons a previous + * installation reported through [installedAddons]. + */ + fun listBundledAddons(context: Context): List + + /** The add-ons [doInstall] has put in place since [listBundledAddons]. */ + fun installedAddons(): List } diff --git a/app/src/main/java/com/itsaky/androidide/assets/BaseAssetsInstaller.kt b/app/src/main/java/com/itsaky/androidide/assets/BaseAssetsInstaller.kt index b0ded95a38..55f8bdaf56 100644 --- a/app/src/main/java/com/itsaky/androidide/assets/BaseAssetsInstaller.kt +++ b/app/src/main/java/com/itsaky/androidide/assets/BaseAssetsInstaller.kt @@ -1,17 +1,60 @@ package com.itsaky.androidide.assets import android.content.Context +import com.itsaky.androidide.assets.addons.BundleSource +import com.itsaky.androidide.assets.addons.BundledAddonInstaller +import com.itsaky.androidide.assets.addons.BundledAddons +import com.itsaky.androidide.assets.addons.BundledEntry +import com.itsaky.androidide.assets.addons.InstalledAddon +import com.itsaky.androidide.plugins.manager.loaders.PluginLoader import com.itsaky.androidide.utils.Environment import com.termux.shared.termux.TermuxConstants import org.slf4j.LoggerFactory import java.io.File +import java.io.InputStream import java.nio.file.Path +import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.TimeUnit import kotlin.concurrent.thread import kotlin.system.measureTimeMillis abstract class BaseAssetsInstaller : AssetsInstaller { private val logger = LoggerFactory.getLogger(BaseAssetsInstaller::class.java) + private val installedByEntry = ConcurrentHashMap() + + // Content hashes from the bundle index, by entry name, for the copies to check. + private val sha256ByEntry = ConcurrentHashMap() + + /** Where this installer's bundled add-ons are read from. */ + protected abstract fun bundleSource(context: Context): BundleSource + + override fun listBundledAddons(context: Context): List { + installedByEntry.clear() + sha256ByEntry.clear() + return BundledAddons.list(bundleSource(context)).onEach { entry -> + entry.sha256?.let { sha256ByEntry[entry.entryName] = it } + } + } + + override fun installedAddons(): List = installedByEntry.values.toList() + + /** Installs the bundled add-on [entryName] (`plugins/` or `templates/`) read from [input]. */ + protected fun installBundledAddon( + context: Context, + entryName: String, + input: InputStream, + ) { + val (kind, fileName) = + BundledAddons.parse(entryName) ?: throw IllegalStateException("Unknown entry: $entryName") + val installer = + BundledAddonInstaller( + // The folder PluginManager loads from. + pluginsDir = File(context.filesDir, "plugins"), + templatesDir = Environment.TEMPLATES_DIR, + readPluginId = { PluginLoader(context, it).getPluginMetadata()?.id }, + ) + installedByEntry[entryName] = installer.install(kind, fileName, input, sha256ByEntry[entryName]) + } override suspend fun postInstall( context: Context, diff --git a/app/src/main/java/com/itsaky/androidide/assets/BundledAssetsInstaller.kt b/app/src/main/java/com/itsaky/androidide/assets/BundledAssetsInstaller.kt index a01d15a636..eef570e4b9 100644 --- a/app/src/main/java/com/itsaky/androidide/assets/BundledAssetsInstaller.kt +++ b/app/src/main/java/com/itsaky/androidide/assets/BundledAssetsInstaller.kt @@ -4,6 +4,9 @@ import android.content.Context import androidx.annotation.WorkerThread import com.aayushatharva.brotli4j.decoder.BrotliInputStream import com.itsaky.androidide.app.configuration.CpuArch +import com.itsaky.androidide.assets.addons.AssetManagerBundleSource +import com.itsaky.androidide.assets.addons.BundleSource +import com.itsaky.androidide.assets.addons.BundledAddons import com.itsaky.androidide.managers.ToolsManager import com.itsaky.androidide.resources.R import com.itsaky.androidide.utils.Environment @@ -169,11 +172,16 @@ data object BundledAssetsInstaller : BaseAssetsInstaller() { } else -> { - throw IllegalStateException("Unknown entry: $entryName") + if (!BundledAddons.isAddonEntry(entryName)) { + throw IllegalStateException("Unknown entry: $entryName") + } + assets.open(entryName).use { installBundledAddon(context, entryName, it) } } } } + override fun bundleSource(context: Context): BundleSource = AssetManagerBundleSource(context.assets) + override fun expectedSize(entryName: String): Long = when (entryName) { GRADLE_DISTRIBUTION_ARCHIVE_NAME -> 63399283L diff --git a/app/src/main/java/com/itsaky/androidide/assets/SplitAssetsInstaller.kt b/app/src/main/java/com/itsaky/androidide/assets/SplitAssetsInstaller.kt index dcafab5900..8c49061ba6 100644 --- a/app/src/main/java/com/itsaky/androidide/assets/SplitAssetsInstaller.kt +++ b/app/src/main/java/com/itsaky/androidide/assets/SplitAssetsInstaller.kt @@ -3,6 +3,9 @@ package com.itsaky.androidide.assets import android.content.Context import androidx.annotation.WorkerThread import com.itsaky.androidide.app.configuration.CpuArch +import com.itsaky.androidide.assets.addons.BundleSource +import com.itsaky.androidide.assets.addons.BundledAddons +import com.itsaky.androidide.assets.addons.ZipBundleSource import com.itsaky.androidide.resources.R import com.itsaky.androidide.utils.Environment import com.itsaky.androidide.utils.TerminalInstaller @@ -174,7 +177,10 @@ data object SplitAssetsInstaller : BaseAssetsInstaller() { } else -> { - throw IllegalStateException("Unknown entry: $entryName") + if (!BundledAddons.isAddonEntry(entryName)) { + throw IllegalStateException("Unknown entry: $entryName") + } + installBundledAddon(context, entryName, zipInput) } } } @@ -182,6 +188,8 @@ data object SplitAssetsInstaller : BaseAssetsInstaller() { logger.info("Extraction of '{}' completed in {}ms", entry.name, time) } + override fun bundleSource(context: Context): BundleSource = ZipBundleSource(zipFile) + override suspend fun postInstall( context: Context, stagingDir: Path, diff --git a/app/src/main/java/com/itsaky/androidide/assets/addons/AtomicFiles.kt b/app/src/main/java/com/itsaky/androidide/assets/addons/AtomicFiles.kt new file mode 100644 index 0000000000..8b654f5aae --- /dev/null +++ b/app/src/main/java/com/itsaky/androidide/assets/addons/AtomicFiles.kt @@ -0,0 +1,48 @@ +package com.itsaky.androidide.assets.addons + +import java.io.File +import java.io.IOException +import java.nio.file.AtomicMoveNotSupportedException +import java.nio.file.Files +import java.nio.file.StandardCopyOption +import java.util.UUID + +internal object AtomicFiles { + /** Moves [temp] to [dest], replacing it, in one step where the filesystem can. */ + fun moveInto( + temp: File, + dest: File, + ) { + try { + Files.move(temp.toPath(), dest.toPath(), StandardCopyOption.ATOMIC_MOVE) + } catch (e: AtomicMoveNotSupportedException) { + Files.move(temp.toPath(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING) + } + } + + /** + * Fills a scratch file next to the destination with [write], then lets [finalName] pick the + * destination's name from it and moves it there. The scratch name ends in `.partial`, which no + * loader of plugins or templates reads, and the scratch file is deleted on any failure, so an + * interrupted copy never leaves a truncated file under a final name. + */ + fun writeInto( + destDir: File, + write: (File) -> Unit, + finalName: (File) -> String, + ): File { + if (!destDir.isDirectory && !destDir.mkdirs() && !destDir.isDirectory) { + throw IOException("Could not create ${destDir.absolutePath}") + } + val temp = File(destDir, ".${UUID.randomUUID()}.partial") + try { + write(temp) + val dest = File(destDir, finalName(temp)) + moveInto(temp, dest) + return dest + } finally { + // Gone already after a successful move; only a failure leaves it. + temp.delete() + } + } +} diff --git a/app/src/main/java/com/itsaky/androidide/assets/addons/BundleSources.kt b/app/src/main/java/com/itsaky/androidide/assets/addons/BundleSources.kt new file mode 100644 index 0000000000..12ef9c6d5e --- /dev/null +++ b/app/src/main/java/com/itsaky/androidide/assets/addons/BundleSources.kt @@ -0,0 +1,80 @@ +package com.itsaky.androidide.assets.addons + +import android.content.res.AssetManager +import java.io.FileNotFoundException +import java.io.IOException +import java.io.InputStream +import java.util.zip.ZipFile + +/** The bundle of a release build: `plugins/` and `templates/` in the APK assets. */ +class AssetManagerBundleSource( + private val assets: AssetManager, +) : BundleSource { + override fun names(dir: String): List = assets.list(dir)?.toList().orEmpty() + + override fun size( + dir: String, + name: String, + ): Long = + try { + assets.openFd("$dir/$name").use { it.length } + } catch (e: IOException) { + // openFd refuses an asset the APK stores compressed; count the bytes instead. Only a bundle + // without an index asks for sizes, and every release build writes one. + assets.open("$dir/$name").use { input -> input.countBytes() } + } + + override fun open( + dir: String, + name: String, + ): InputStream = assets.open("$dir/$name") + + override fun index(): String? = + try { + assets.open(BundledAddons.INDEX_FILE).bufferedReader().use { it.readText() } + } catch (e: FileNotFoundException) { + null + } +} + +/** The bundle of a debug build: `plugins/` and `templates/` entries of the split assets zip. */ +class ZipBundleSource( + private val zip: ZipFile, +) : BundleSource { + override fun names(dir: String): List = + zip + .entries() + .asSequence() + .filter { !it.isDirectory && it.name.startsWith("$dir/") } + .map { it.name.removePrefix("$dir/") } + .filter { it.isNotEmpty() && '/' !in it } + .toList() + + override fun size( + dir: String, + name: String, + ): Long = entry(dir, name).size + + override fun open( + dir: String, + name: String, + ): InputStream = zip.getInputStream(entry(dir, name)) + + override fun index(): String? = + zip.getEntry(BundledAddons.INDEX_FILE)?.let { entry -> zip.getInputStream(entry).bufferedReader().use { it.readText() } } + + private fun entry( + dir: String, + name: String, + ) = zip.getEntry("$dir/$name") ?: throw FileNotFoundException("Entry '$dir/$name' not found in assets zip file") +} + +private fun InputStream.countBytes(): Long { + val buffer = ByteArray(DEFAULT_BUFFER_SIZE) + var total = 0L + while (true) { + val read = read(buffer) + if (read < 0) return total + total += read + } +} diff --git a/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonInstaller.kt b/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonInstaller.kt new file mode 100644 index 0000000000..77a69bc353 --- /dev/null +++ b/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonInstaller.kt @@ -0,0 +1,126 @@ +package com.itsaky.androidide.assets.addons + +import com.itsaky.androidide.plugins.manager.core.PluginBuildFiles +import com.itsaky.androidide.plugins.manager.core.checkPluginId +import org.adfa.constants.PLUGIN_ARCHIVE_EXTENSION +import java.io.File +import java.io.IOException +import java.io.InputStream +import java.security.DigestInputStream +import java.security.MessageDigest + +/** + * A bundled add-on after installation. [pluginId] is set for a plugin that reached its folder. A + * plugin whose manifest names no valid ID, or an add-on whose content differs from the bundle + * index, has no [file] and carries a [failure] instead, with the bundled file name in + * [sourceName]: it is reported to the user, and must not fail the setup. + */ +data class InstalledAddon( + val kind: BundledAddonKind, + val file: File?, + val pluginId: String?, + val failure: String? = null, + val sourceName: String? = null, +) + +/** + * Copies bundled add-on files into place. A plugin lands in [pluginsDir] as + * `-.cgp`, the name an install from the Add-ons Manager gives it, and a template in + * [templatesDir] under its bundled name. + * + * The plugin ID is only in the plugin's manifest, so the name is chosen on the device, from the + * copied file ([readPluginId]), and not at build time. The bundle then needs no manifest reader in + * Gradle, and the naming rule stays in [PluginBuildFiles.fileStem]. + */ +class BundledAddonInstaller( + private val pluginsDir: File, + private val templatesDir: File, + private val readPluginId: (File) -> String?, +) { + /** + * Copies [input] into place. With [sha256] (hex, from the bundle index), a copy whose content + * differs is rejected like an unreadable plugin: reported, not thrown, and nothing replaced. + */ + fun install( + kind: BundledAddonKind, + fileName: String, + input: InputStream, + sha256: String? = null, + ): InstalledAddon { + val digest = sha256?.let { MessageDigest.getInstance("SHA-256") } + val source = digest?.let { DigestInputStream(input, it) } ?: input + val checkContent = { + if (digest != null && digest.digest().toHex() != sha256) { + throw RejectedAddonException("its content does not match the bundle index") + } + } + return when (kind) { + BundledAddonKind.PLUGIN -> { + installPlugin(fileName, source, checkContent) + } + + BundledAddonKind.TEMPLATE -> { + try { + val file = + AtomicFiles.writeInto(templatesDir, { source.copyToFile(it) }, { + checkContent() + fileName + }) + InstalledAddon(kind, file, null) + } catch (e: RejectedAddonException) { + InstalledAddon(kind, null, null, failure = e.message, sourceName = fileName) + } + } + } + } + + private fun installPlugin( + fileName: String, + input: InputStream, + checkContent: () -> Unit, + ): InstalledAddon { + var pluginId: String? = null + val file = + try { + AtomicFiles.writeInto( + pluginsDir, + { input.copyToFile(it) }, + { copy -> + checkContent() + val id = + try { + readPluginId(copy) + } catch (e: Exception) { + null + } ?: throw RejectedAddonException("it has no readable manifest") + checkPluginId(id).onFailure { throw RejectedAddonException(it.message ?: "invalid plugin ID") } + val name = "${PluginBuildFiles.fileStem(id, copy)}.$PLUGIN_ARCHIVE_EXTENSION" + // 255 bytes is the longest file name the file system takes. + if (name.toByteArray(Charsets.UTF_8).size > MAX_FILE_NAME_BYTES) { + throw RejectedAddonException("its plugin ID is too long") + } + pluginId = id + name + }, + ) + } catch (e: RejectedAddonException) { + // writeInto has deleted the scratch copy. A write error (disk full) still propagates. + return InstalledAddon(BundledAddonKind.PLUGIN, null, null, failure = e.message, sourceName = fileName) + } + return InstalledAddon(BundledAddonKind.PLUGIN, file, pluginId) + } + + private companion object { + const val MAX_FILE_NAME_BYTES = 255 + } + + private class RejectedAddonException( + message: String, + ) : IOException(message) + + private fun ByteArray.toHex(): String = joinToString("") { "%02x".format(it) } + + private fun InputStream.copyToFile(dest: File) { + dest.outputStream().use { out -> copyTo(out) } + } +} diff --git a/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddons.kt b/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddons.kt new file mode 100644 index 0000000000..a224d8d70a --- /dev/null +++ b/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddons.kt @@ -0,0 +1,139 @@ +package com.itsaky.androidide.assets.addons + +import org.adfa.constants.PLUGIN_ARCHIVE_EXTENSION +import org.adfa.constants.TEMPLATE_ARCHIVE_EXTENSION +import org.adfa.constants.TEMPLATE_CORE_ARCHIVE +import org.slf4j.LoggerFactory +import java.io.InputStream +import java.security.MessageDigest + +/** The add-on kinds a build can bundle, each in a folder of its own in the APK assets or the debug zip. */ +enum class BundledAddonKind( + val dir: String, + val extension: String, +) { + PLUGIN("plugins", PLUGIN_ARCHIVE_EXTENSION), + TEMPLATE("templates", TEMPLATE_ARCHIVE_EXTENSION), +} + +/** + * One bundled add-on file: [fileName] inside the [kind] folder, [size] bytes. [sha256] (hex) comes + * from the bundle index; it is null for a bundle without one, listed by name and size. + */ +data class BundledEntry( + val kind: BundledAddonKind, + val fileName: String, + val size: Long, + val sha256: String? = null, +) { + /** The name the installers and the progress list know it by: `plugins/`. */ + val entryName: String get() = "${kind.dir}/$fileName" +} + +/** Where the bundle is read from: APK assets in a release build, the split assets zip in a debug one. */ +interface BundleSource { + /** File names directly inside [dir], or none when the folder is absent. */ + fun names(dir: String): List + + fun size( + dir: String, + name: String, + ): Long + + fun open( + dir: String, + name: String, + ): InputStream + + /** The text of the bundle index ([BundledAddons.INDEX_FILE]), or null when the bundle has none. */ + fun index(): String? = null +} + +object BundledAddons { + private val logger = LoggerFactory.getLogger(BundledAddons::class.java) + + /** + * The bundle index, written by the build beside `plugins/` and `templates/`: one line per add-on, + * `\t\t`. A thin build writes it empty. With it, listing the bundle + * opens no add-on, and the fingerprint notices a rebuilt add-on of the same size. + */ + const val INDEX_FILE = "bundled-addons.tsv" + + /** True for an entry name that [BundledEntry.entryName] could have produced. */ + fun isAddonEntry(entryName: String): Boolean = parse(entryName) != null + + /** The kind and file name of [entryName], or null when it names no add-on file. */ + fun parse(entryName: String): Pair? { + val kind = BundledAddonKind.values().firstOrNull { entryName.startsWith("${it.dir}/") } ?: return null + val fileName = entryName.removePrefix("${kind.dir}/") + return if (isAddonFile(kind, fileName)) kind to fileName else null + } + + /** + * Every add-on file [source] holds, plugins first, each kind in name order. A thin build has + * none. The bundle index is used when there is a valid one. Otherwise, as for a debug zip made + * before the index, the folders are listed and each file's size read: other files in the folders, + * and any path below them, are not add-ons. + */ + fun list(source: BundleSource): List { + val index = source.index() + index?.let(::parseIndex)?.let { return it } + // A present but rejected index loses every copy's SHA-256 check, so say so. + if (index != null) logger.warn("Bundle index {} is not valid; listing the folders without content checks", INDEX_FILE) + return listFolders(source) + } + + /** + * The entries of an index, in [list]'s order, or null when any line is malformed, names no add-on + * file, or repeats an entry: such an index was not written by the build, so the folders decide. + */ + fun parseIndex(text: String): List? { + val entries = + text.lines().filter { it.isNotBlank() }.map { line -> + val fields = line.split('\t') + if (fields.size != 3) return null + val (kind, fileName) = parse(fields[0]) ?: return null + val size = fields[1].toLongOrNull()?.takeIf { it >= 0 } ?: return null + val sha256 = fields[2].takeIf { SHA256_HEX.matches(it) } ?: return null + BundledEntry(kind, fileName, size, sha256) + } + if (entries.distinctBy { it.entryName }.size != entries.size) return null + return entries.sortedWith(compareBy({ it.kind.ordinal }, { it.fileName })) + } + + private val SHA256_HEX = Regex("[0-9a-f]{64}") + + private fun listFolders(source: BundleSource): List = + BundledAddonKind.values().flatMap { kind -> + source + .names(kind.dir) + .filter { isAddonFile(kind, it) } + .sorted() + .map { BundledEntry(kind, it, source.size(kind.dir, it)) } + } + + /** + * Identifies a bundle by its entries, in any order: sha-256, hex. It reads no add-on, so it is + * cheap at every start. Entries from an index carry their content hash, so a rebuilt add-on of the + * same name and size is noticed; a bundle without an index is identified by names and sizes only. + * The empty bundle has a fingerprint too, so a thin build can be told from a missing record. + */ + fun fingerprint(entries: List): String { + val digest = MessageDigest.getInstance("SHA-256") + entries + .map { entry -> listOfNotNull(entry.entryName, entry.size.toString(), entry.sha256).joinToString("\t", postfix = "\n") } + .sorted() + .forEach { digest.update(it.toByteArray(Charsets.UTF_8)) } + return digest.digest().joinToString("") { "%02x".format(it) } + } + + private fun isAddonFile( + kind: BundledAddonKind, + fileName: String, + ): Boolean = + '/' !in fileName && + !fileName.startsWith(".") && + fileName.endsWith(".${kind.extension}", ignoreCase = true) && + // core.cgt is installed by its own entry into the same folder. + !(kind == BundledAddonKind.TEMPLATE && fileName.equals(TEMPLATE_CORE_ARCHIVE, ignoreCase = true)) +} diff --git a/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonsRecord.kt b/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonsRecord.kt new file mode 100644 index 0000000000..877c2f7354 --- /dev/null +++ b/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonsRecord.kt @@ -0,0 +1,147 @@ +package com.itsaky.androidide.assets.addons + +import java.io.File +import java.io.IOException +import java.util.Properties +import java.util.UUID +import java.util.concurrent.ConcurrentHashMap + +/** A bundled plugin that did not load, and whether the user has been told. */ +data class BundledPluginFailure( + val pluginId: String, + val message: String, + val reported: Boolean = false, +) + +/** What the first installation took from the build's bundle. */ +data class BundledAddonsState( + /** [BundledAddons.fingerprint] of the bundle that was installed. */ + val fingerprint: String, + val pluginIds: List = emptyList(), + val templateFiles: List = emptyList(), + val failures: List = emptyList(), +) + +/** + * The record of an installed bundle: which plugins and templates came from the build, and which + * bundled plugins failed to load. Kept in a properties file, as `plugin_crash_counts.properties` is. + * + * [write] runs only after every bundle file is in place, so a record exists only for a complete + * install, and replaces the file in one step. A missing or unreadable file reads as no record. + * The installation writes it for a thin build too, with an empty bundle. + */ +class BundledAddonsRecord( + private val file: File, +) { + @Synchronized + fun read(): BundledAddonsState? { + if (!file.isFile) return null + return try { + val props = Properties() + file.inputStream().use { props.load(it) } + val fingerprint = props.getProperty(FINGERPRINT) ?: return null + BundledAddonsState( + fingerprint = fingerprint, + pluginIds = props.indexed(PLUGIN), + templateFiles = props.indexed(TEMPLATE), + failures = props.failures(), + ) + } catch (e: IOException) { + null + } catch (e: IllegalArgumentException) { + // Properties.load on a malformed escape. + null + } + } + + /** Replaces the record with [state]; failures it carries are kept as given. */ + @Synchronized + fun write(state: BundledAddonsState) { + val props = Properties() + props.setProperty(FINGERPRINT, state.fingerprint) + state.pluginIds.forEachIndexed { n, id -> props.setProperty("$PLUGIN.$n", id) } + state.templateFiles.forEachIndexed { n, name -> props.setProperty("$TEMPLATE.$n", name) } + state.failures.forEachIndexed { n, failure -> + props.setProperty("$FAILURE.$n.id", failure.pluginId) + props.setProperty("$FAILURE.$n.message", failure.message) + props.setProperty("$FAILURE.$n.reported", failure.reported.toString()) + } + + file.parentFile?.mkdirs() + val temp = File(file.parentFile, ".${file.name}.${UUID.randomUUID()}.tmp") + try { + temp.outputStream().use { props.store(it, null) } + AtomicFiles.moveInto(temp, file) + } finally { + temp.delete() + } + } + + /** + * Stores [failures] (plugin ID to message) as unreported. A failure already recorded under + * another key (a plugin rejected while copying) is kept; one under the same key is replaced. + * Does nothing when there is no record: failures belong to an installed bundle. + */ + @Synchronized + fun recordFailures(failures: Map) { + val state = read() ?: return + val kept = state.failures.filterNot { it.pluginId in failures } + write(state.copy(failures = kept + failures.map { (id, message) -> BundledPluginFailure(id, message) })) + } + + /** The failures the user has not been told about, in the order recorded. */ + @Synchronized + fun unreportedFailures(): List = read()?.failures.orEmpty().filterNot { it.reported } + + /** + * Marks [told] as told, and returns those that were not before. A failure recorded since [told] + * was read, or recorded again with another message, stays unreported. + */ + @Synchronized + fun markReported(told: Collection): List { + val state = read() ?: return emptyList() + val keys = told.mapTo(HashSet()) { it.pluginId to it.message } + val pending = state.failures.filter { !it.reported && (it.pluginId to it.message) in keys } + if (pending.isNotEmpty()) { + write(state.copy(failures = state.failures.map { if (it in pending) it.copy(reported = true) else it })) + } + return pending + } + + private fun Properties.indexed(prefix: String): List { + val values = ArrayList() + while (true) { + values += getProperty("$prefix.${values.size}") ?: return values + } + } + + private fun Properties.failures(): List { + val failures = ArrayList() + while (true) { + val n = failures.size + val id = getProperty("$FAILURE.$n.id") ?: return failures + failures += + BundledPluginFailure( + pluginId = id, + message = getProperty("$FAILURE.$n.message").orEmpty(), + reported = getProperty("$FAILURE.$n.reported") == "true", + ) + } + } + + companion object { + const val FILE_NAME = "bundled_addons.properties" + + private const val FINGERPRINT = "fingerprint" + private const val PLUGIN = "plugin" + private const val TEMPLATE = "template" + private const val FAILURE = "failure" + + // One instance per file, so @Synchronized serializes every caller: the setup and the main screen + // both read, change and rewrite the file. + private val instances = ConcurrentHashMap() + + fun inFilesDir(filesDir: File): BundledAddonsRecord = + instances.computeIfAbsent(File(filesDir, FILE_NAME).canonicalPath) { BundledAddonsRecord(File(it)) } + } +} diff --git a/app/src/main/java/com/itsaky/androidide/assets/addons/BundledFailureReport.kt b/app/src/main/java/com/itsaky/androidide/assets/addons/BundledFailureReport.kt new file mode 100644 index 0000000000..6dbb6573a7 --- /dev/null +++ b/app/src/main/java/com/itsaky/androidide/assets/addons/BundledFailureReport.kt @@ -0,0 +1,29 @@ +package com.itsaky.androidide.assets.addons + +import com.itsaky.androidide.utils.TrackedFlashbar +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.withContext +import kotlin.coroutines.CoroutineContext + +/** + * Shows the failures the user has not been told about with [show], and marks them reported only once + * the user dismisses the bar. Until then this suspends, so a caller that runs one report at a time + * shows no second bar while one is up. + * + * If the caller's scope ends first - the screen went away, say recreated by a font scale change - the + * failures stay unreported and the next report shows them again. Destroying an activity fires no + * dismiss callback, so only the user ends the wait. A failure recorded while the bar is up is not + * marked: it was not on the bar. + */ +suspend fun BundledAddonsRecord.reportFailures( + io: CoroutineContext = Dispatchers.IO, + show: (List) -> TrackedFlashbar?, +) { + val failures = withContext(io) { runCatching { unreportedFailures() }.getOrDefault(emptyList()) } + if (failures.isEmpty()) return + val bar = show(failures) ?: return + bar.awaitDismissed() + // The user dismissed the bar: record that even if the screen goes away now. + withContext(NonCancellable + io) { runCatching { markReported(failures) } } +} diff --git a/app/src/main/java/com/itsaky/androidide/assets/addons/BundledPluginStartup.kt b/app/src/main/java/com/itsaky/androidide/assets/addons/BundledPluginStartup.kt new file mode 100644 index 0000000000..e272c0bde5 --- /dev/null +++ b/app/src/main/java/com/itsaky/androidide/assets/addons/BundledPluginStartup.kt @@ -0,0 +1,39 @@ +package com.itsaky.androidide.assets.addons + +import kotlin.coroutines.cancellation.CancellationException + +/** + * Starts the plugins a first installation copied from the bundle, and records those that did not + * load, for the main screen to report once ([BundledAddonsRecord.markReported]). + * + * A failure here never fails the setup: [start] returns normally whatever the plugins do. + */ +class BundledPluginStartup( + private val record: BundledAddonsRecord, + private val reloadPlugins: suspend () -> Unit, + private val loadError: (pluginId: String) -> String?, +) { + suspend fun start() { + val pluginIds = record.read()?.pluginIds.orEmpty() + // A thin build copied no plugin, so there is nothing to start. + if (pluginIds.isEmpty()) return + + val reloadFailure = + try { + reloadPlugins() + null + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + e.message ?: e.toString() + } + + val failures = + pluginIds + .mapNotNull { id -> (reloadFailure ?: loadError(id))?.let { id to it } } + .toMap() + if (failures.isNotEmpty()) { + record.recordFailures(failures) + } + } +} diff --git a/app/src/main/java/com/itsaky/androidide/viewmodel/InstallationViewModel.kt b/app/src/main/java/com/itsaky/androidide/viewmodel/InstallationViewModel.kt index 6c07509ed3..ac1570880a 100644 --- a/app/src/main/java/com/itsaky/androidide/viewmodel/InstallationViewModel.kt +++ b/app/src/main/java/com/itsaky/androidide/viewmodel/InstallationViewModel.kt @@ -7,8 +7,11 @@ import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.itsaky.androidide.app.configuration.IJdkDistributionProvider import com.itsaky.androidide.assets.AssetsInstallationHelper +import com.itsaky.androidide.assets.addons.BundledAddonsRecord +import com.itsaky.androidide.assets.addons.BundledPluginStartup import com.itsaky.androidide.events.InstallationEvent import com.itsaky.androidide.models.StorageInfo +import com.itsaky.androidide.plugins.manager.core.PluginManager import com.itsaky.androidide.resources.R import com.itsaky.androidide.utils.Environment import com.itsaky.androidide.utils.bytesToGigabytes @@ -37,6 +40,7 @@ import kotlin.coroutines.cancellation.CancellationException // All-default constructor, so the default ViewModel factory still finds a no-arg one. class InstallationViewModel( private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO, + private val startBundledPlugins: suspend (Context) -> Unit = { startBundledPluginsWithManager(it) }, ) : ViewModel() { private val log = LoggerFactory.getLogger(InstallationViewModel::class.java) @@ -95,6 +99,15 @@ class InstallationViewModel( val distributionProvider = IJdkDistributionProvider.getInstance() distributionProvider.loadDistributions() + // Plugins from the build's bundle; the setup completes whatever they do. + try { + startBundledPlugins(context) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + log.warn("Could not start the bundled plugins", e) + } + _state.update { InstallationComplete } } @@ -177,3 +190,13 @@ class InstallationViewModel( return@withContext true } } + +/** Without the plugin system (not initialized yet) there is nothing to start; the files stay for the next start. */ +private suspend fun startBundledPluginsWithManager(context: Context) { + val manager = PluginManager.getInstance() ?: return + BundledPluginStartup( + record = BundledAddonsRecord.inFilesDir(context.filesDir), + reloadPlugins = { manager.loadPlugins() }, + loadError = manager::getLoadError, + ).start() +} diff --git a/app/src/test/java/com/itsaky/androidide/assets/AssetsInstallationHelperBundleTest.kt b/app/src/test/java/com/itsaky/androidide/assets/AssetsInstallationHelperBundleTest.kt new file mode 100644 index 0000000000..d203a4780b --- /dev/null +++ b/app/src/test/java/com/itsaky/androidide/assets/AssetsInstallationHelperBundleTest.kt @@ -0,0 +1,168 @@ +package com.itsaky.androidide.assets + +import android.content.Context +import com.aayushatharva.brotli4j.Brotli4jLoader +import com.google.common.truth.Truth.assertThat +import com.itsaky.androidide.app.configuration.CpuArch +import com.itsaky.androidide.app.configuration.IDEBuildConfigProvider +import com.itsaky.androidide.assets.addons.BundledAddonKind +import com.itsaky.androidide.assets.addons.BundledAddons +import com.itsaky.androidide.assets.addons.BundledAddonsRecord +import com.itsaky.androidide.assets.addons.BundledAddonsState +import com.itsaky.androidide.assets.addons.BundledEntry +import com.itsaky.androidide.assets.addons.InstalledAddon +import io.mockk.Runs +import io.mockk.coEvery +import io.mockk.every +import io.mockk.just +import io.mockk.mockk +import io.mockk.mockkObject +import io.mockk.mockkStatic +import io.mockk.unmockkAll +import kotlinx.coroutines.runBlocking +import org.junit.After +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import java.io.File +import java.io.IOException + +/** + * The bundle record is written last and only for a complete installation. Like the other tests of + * the helper, this relies on AssetsInstaller.CURRENT_INSTALLER being SplitAssetsInstaller, which + * only holds for debug builds: run it via :app:testV8DebugUnitTest. + */ +class AssetsInstallationHelperBundleTest { + @get:Rule + val tempFolder = TemporaryFolder() + + private val ctx: Context = mockk(relaxed = true) + private val helper = AssetsInstallationHelper + private lateinit var filesDir: File + + @Before + fun setUp() { + // Load the brotli native for real before mocking Brotli4jLoader, as AssetsInstallationHelperTest + // does: a JVM whose first sight of that class is the mocked one caches "unavailable", and every + // later brotli test fails. + try { + Brotli4jLoader.ensureAvailability() + } catch (e: UnsatisfiedLinkError) { + println("brotli native unavailable on this host, continuing: ${e.message}") + } + + filesDir = tempFolder.newFolder("files") + every { ctx.filesDir } returns filesDir + + mockkObject(helper) + every { + helper["checkStorageAccessibility"](any(), any()) + } returns null + + mockkObject(IDEBuildConfigProvider.Companion) + mockkStatic(Brotli4jLoader::class) + val provider = mockk(relaxed = true) + every { provider.cpuArch } returns CpuArch.AARCH64 + every { IDEBuildConfigProvider.getInstance() } returns provider + every { Brotli4jLoader.ensureAvailability() } just Runs + + mockkObject(SplitAssetsInstaller) + coEvery { SplitAssetsInstaller.preInstall(any(), any()) } just Runs + coEvery { SplitAssetsInstaller.postInstall(any(), any()) } just Runs + } + + @After + fun tearDown() { + unmockkAll() + } + + private val record get() = BundledAddonsRecord.inFilesDir(filesDir) + + private val bundle = + listOf( + BundledEntry(BundledAddonKind.PLUGIN, "a.cgp", 10L), + BundledEntry(BundledAddonKind.PLUGIN, "b.cgp", 20L), + BundledEntry(BundledAddonKind.TEMPLATE, "t.cgt", 30L), + ) + + private fun installed(name: String) = + when { + name.endsWith(".cgt") -> InstalledAddon(BundledAddonKind.TEMPLATE, File(filesDir, name), null) + else -> InstalledAddon(BundledAddonKind.PLUGIN, File(filesDir, "$name-hash.cgp"), "id.${name.removeSuffix(".cgp")}") + } + + @Test + fun `every entry is installed, then the record is written`() = + runBlocking { + val seen = + java.util.concurrent.ConcurrentHashMap + .newKeySet() + every { SplitAssetsInstaller.listBundledAddons(any()) } returns bundle + every { SplitAssetsInstaller.installedAddons() } returns bundle.map { installed(it.fileName) } + coEvery { SplitAssetsInstaller.doInstall(any(), any(), any(), any()) } coAnswers { + assertThat(record.read()).isNull() + seen += arg(3) + } + + val result = helper.install(ctx) + + assertThat(result).isEqualTo(AssetsInstallationHelper.Result.Success) + assertThat(seen).containsExactlyElementsIn(AssetsInstallationHelper.entriesToInstall(bundle)) + assertThat(record.read()) + .isEqualTo( + BundledAddonsState( + fingerprint = BundledAddons.fingerprint(bundle), + pluginIds = listOf("id.a", "id.b"), + templateFiles = listOf("t.cgt"), + ), + ) + } + + @Test + fun `a thin build installs the eight entries and records an empty bundle`() = + runBlocking { + val seen = + java.util.concurrent.ConcurrentHashMap + .newKeySet() + every { SplitAssetsInstaller.listBundledAddons(any()) } returns emptyList() + every { SplitAssetsInstaller.installedAddons() } returns emptyList() + coEvery { SplitAssetsInstaller.doInstall(any(), any(), any(), any()) } coAnswers { seen += arg(3) } + + helper.install(ctx) + + assertThat(seen).containsExactlyElementsIn(AssetsInstallationHelper.expectedEntries) + assertThat(seen).hasSize(8) + assertThat(record.read()).isEqualTo(BundledAddonsState(fingerprint = BundledAddons.fingerprint(emptyList()))) + } + + @Test + fun `no record is written when one bundled copy fails`() = + runBlocking { + every { SplitAssetsInstaller.listBundledAddons(any()) } returns bundle + every { SplitAssetsInstaller.installedAddons() } returns bundle.map { installed(it.fileName) } + coEvery { SplitAssetsInstaller.doInstall(any(), any(), any(), any()) } coAnswers { + if (arg(3) == "plugins/b.cgp") throw IOException("disk full") + } + + val result = helper.install(ctx) + + assertThat(result).isInstanceOf(AssetsInstallationHelper.Result.Failure::class.java) + assertThat(record.read()).isNull() + assertThat(File(filesDir, BundledAddonsRecord.FILE_NAME).exists()).isFalse() + } + + @Test + fun `no record is written when a fixed entry fails`() = + runBlocking { + every { SplitAssetsInstaller.listBundledAddons(any()) } returns bundle + every { SplitAssetsInstaller.installedAddons() } returns bundle.map { installed(it.fileName) } + coEvery { SplitAssetsInstaller.doInstall(any(), any(), any(), any()) } coAnswers { + if (arg(3) == "bootstrap.zip") throw IOException("disk full") + } + + helper.install(ctx) + + assertThat(record.read()).isNull() + } +} diff --git a/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonInstallerTest.kt b/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonInstallerTest.kt new file mode 100644 index 0000000000..2426e6a711 --- /dev/null +++ b/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonInstallerTest.kt @@ -0,0 +1,204 @@ +package com.itsaky.androidide.assets.addons + +import com.google.common.truth.Truth.assertThat +import com.itsaky.androidide.plugins.manager.core.PluginBuildFiles +import org.junit.Assert.assertThrows +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import java.io.ByteArrayInputStream +import java.io.File +import java.io.IOException +import java.io.InputStream +import java.security.MessageDigest + +class BundledAddonInstallerTest { + @get:Rule + val tempFolder = TemporaryFolder() + + private lateinit var pluginsDir: File + private lateinit var templatesDir: File + + @Before + fun setUp() { + pluginsDir = File(tempFolder.root, "plugins") + templatesDir = File(tempFolder.root, "templates") + } + + private fun installer( + readPluginId: (File) -> String? = { + "com.example.plugin" + }, + ) = BundledAddonInstaller(pluginsDir, templatesDir, readPluginId) + + private fun bytes(text: String): InputStream = ByteArrayInputStream(text.toByteArray()) + + private fun sha256(text: String): String = + MessageDigest.getInstance("SHA-256").digest(text.toByteArray()).joinToString("") { "%02x".format(it) } + + /** Delivers [first], then fails, like a copy cut short. */ + private fun failingAfter(first: String): InputStream = + object : InputStream() { + private val head = first.toByteArray() + private var pos = 0 + + override fun read(): Int = if (pos < head.size) head[pos++].toInt() else throw IOException("cut short") + } + + @Test + fun `a plugin is installed as pluginId-hash dot cgp`() { + val installed = installer().install(BundledAddonKind.PLUGIN, "whatever.cgp", bytes("plugin bytes")) + + val expectedStem = PluginBuildFiles.fileStem("com.example.plugin", installed.file!!) + assertThat(installed.file!!.name).isEqualTo("$expectedStem.cgp") + assertThat(installed.file!!.name).startsWith("com.example.plugin-") + assertThat(installed.file!!.parentFile).isEqualTo(pluginsDir) + assertThat(installed.file!!.readText()).isEqualTo("plugin bytes") + assertThat(installed.pluginId).isEqualTo("com.example.plugin") + assertThat(pluginsDir.list()!!.toList()).containsExactly(installed.file!!.name) + } + + @Test + fun `the same plugin bytes always get the same name and another build another one`() { + val first = installer().install(BundledAddonKind.PLUGIN, "a.cgp", bytes("one")).file!!.name + val again = installer().install(BundledAddonKind.PLUGIN, "a.cgp", bytes("one")).file!!.name + val other = installer().install(BundledAddonKind.PLUGIN, "a.cgp", bytes("two")).file!!.name + + assertThat(again).isEqualTo(first) + assertThat(other).isNotEqualTo(first) + } + + @Test + fun `a template is installed under its bundled name`() { + val installed = installer().install(BundledAddonKind.TEMPLATE, "starter.cgt", bytes("template bytes")) + + assertThat(installed.file!!).isEqualTo(File(templatesDir, "starter.cgt")) + assertThat(installed.file!!.readText()).isEqualTo("template bytes") + assertThat(installed.pluginId).isNull() + assertThat(templatesDir.list()!!.toList()).containsExactly("starter.cgt") + } + + @Test + fun `an installed template replaces an older file of its name`() { + templatesDir.mkdirs() + File(templatesDir, "starter.cgt").writeText("old") + + installer().install(BundledAddonKind.TEMPLATE, "starter.cgt", bytes("new")) + + assertThat(File(templatesDir, "starter.cgt").readText()).isEqualTo("new") + assertThat(templatesDir.list()!!.toList()).containsExactly("starter.cgt") + } + + @Test + fun `a plugin whose content matches its index hash is installed`() { + val installed = installer().install(BundledAddonKind.PLUGIN, "a.cgp", bytes("plugin bytes"), sha256("plugin bytes")) + + assertThat(installed.failure).isNull() + assertThat(installed.file!!.readText()).isEqualTo("plugin bytes") + } + + @Test + fun `a plugin whose content differs from its index hash is reported, not thrown, and leaves no file`() { + var manifestRead = false + val installed = + installer(readPluginId = { + manifestRead = true + "com.example.plugin" + }).install(BundledAddonKind.PLUGIN, "a.cgp", bytes("tampered"), sha256("plugin bytes")) + + assertThat(installed.file).isNull() + assertThat(installed.pluginId).isNull() + assertThat(installed.sourceName).isEqualTo("a.cgp") + assertThat(installed.failure).contains("does not match the bundle index") + assertThat(manifestRead).isFalse() + assertThat(pluginsDir.list()!!.toList()).isEmpty() + } + + @Test + fun `a template whose content differs from its index hash is reported and keeps the old one`() { + templatesDir.mkdirs() + File(templatesDir, "starter.cgt").writeText("old") + + val installed = installer().install(BundledAddonKind.TEMPLATE, "starter.cgt", bytes("tampered"), sha256("new")) + + assertThat(installed.file).isNull() + assertThat(installed.sourceName).isEqualTo("starter.cgt") + assertThat(installed.failure).contains("does not match the bundle index") + assertThat(templatesDir.list()!!.toList()).containsExactly("starter.cgt") + assertThat(File(templatesDir, "starter.cgt").readText()).isEqualTo("old") + } + + @Test + fun `a template whose content matches its index hash replaces the old one`() { + templatesDir.mkdirs() + File(templatesDir, "starter.cgt").writeText("old") + + val installed = installer().install(BundledAddonKind.TEMPLATE, "starter.cgt", bytes("new"), sha256("new")) + + assertThat(installed.failure).isNull() + assertThat(File(templatesDir, "starter.cgt").readText()).isEqualTo("new") + } + + @Test + fun `a plugin copy that fails leaves no file behind`() { + assertThrows(IOException::class.java) { + installer().install(BundledAddonKind.PLUGIN, "a.cgp", failingAfter("truncated")) + } + + assertThat(pluginsDir.list()!!.toList()).isEmpty() + } + + @Test + fun `a template copy that fails leaves no partial file and keeps the old one`() { + templatesDir.mkdirs() + File(templatesDir, "starter.cgt").writeText("old") + + assertThrows(IOException::class.java) { + installer().install(BundledAddonKind.TEMPLATE, "starter.cgt", failingAfter("truncated")) + } + + assertThat(templatesDir.list()!!.toList()).containsExactly("starter.cgt") + assertThat(File(templatesDir, "starter.cgt").readText()).isEqualTo("old") + } + + @Test + fun `a plugin without a readable manifest is reported, not thrown, and leaves no file`() { + val result = installer(readPluginId = { null }).install(BundledAddonKind.PLUGIN, "a.cgp", bytes("not a plugin")) + + assertThat(result.file).isNull() + assertThat(result.pluginId).isNull() + assertThat(result.sourceName).isEqualTo("a.cgp") + assertThat(result.failure).isNotNull() + assertThat(pluginsDir.list()!!.toList()).isEmpty() + } + + @Test + fun `a plugin whose manifest reader throws is reported, not thrown`() { + val result = + installer(readPluginId = { throw IllegalStateException("bad zip") }) + .install(BundledAddonKind.PLUGIN, "a.cgp", bytes("not a plugin")) + + assertThat(result.failure).isNotNull() + assertThat(pluginsDir.list()!!.toList()).isEmpty() + } + + @Test + fun `a plugin whose ID is a path is reported, not thrown, and leaves no file`() { + val result = installer(readPluginId = { "../escape" }).install(BundledAddonKind.PLUGIN, "a.cgp", bytes("plugin")) + + assertThat(result.file).isNull() + assertThat(result.failure).contains("../escape") + assertThat(pluginsDir.list()!!.toList()).isEmpty() + } + + @Test + fun `a plugin whose ID is too long for a file name is reported, not thrown, and leaves no file`() { + val result = + installer(readPluginId = { "a".repeat(300) }).install(BundledAddonKind.PLUGIN, "a.cgp", bytes("plugin")) + + assertThat(result.file).isNull() + assertThat(result.failure).contains("too long") + assertThat(pluginsDir.list()!!.toList()).isEmpty() + } +} diff --git a/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonsRecordTest.kt b/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonsRecordTest.kt new file mode 100644 index 0000000000..6a8e396518 --- /dev/null +++ b/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonsRecordTest.kt @@ -0,0 +1,181 @@ +package com.itsaky.androidide.assets.addons + +import com.google.common.truth.Truth.assertThat +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import java.io.File + +class BundledAddonsRecordTest { + @get:Rule + val tempFolder = TemporaryFolder() + + private lateinit var file: File + private lateinit var record: BundledAddonsRecord + + private val state = + BundledAddonsState( + fingerprint = "abc123", + pluginIds = listOf("com.example.one", "com.example.two"), + templateFiles = listOf("starter.cgt"), + ) + + @Before + fun setUp() { + file = File(tempFolder.root, "files/bundled_addons.properties") + record = BundledAddonsRecord(file) + } + + @Test + fun `no file reads as no record`() { + assertThat(record.read()).isNull() + assertThat(record.unreportedFailures()).isEmpty() + assertThat(record.markReported(listOf(BundledPluginFailure("com.example.one", "boom")))).isEmpty() + } + + @Test + fun `a written record reads back`() { + record.write(state) + + assertThat(BundledAddonsRecord(file).read()).isEqualTo(state) + } + + @Test + fun `a thin record reads back with an empty bundle`() { + val thin = BundledAddonsState(fingerprint = BundledAddons.fingerprint(emptyList())) + + record.write(thin) + + assertThat(record.read()).isEqualTo(thin) + } + + @Test + fun `writing replaces the whole record and leaves no temporary file`() { + record.write(state) + record.recordFailures(mapOf("com.example.one" to "boom")) + + val next = BundledAddonsState(fingerprint = "def456", pluginIds = listOf("com.example.three")) + record.write(next) + + assertThat(record.read()).isEqualTo(next) + assertThat(file.parentFile!!.list()!!.toList()).containsExactly(file.name) + } + + @Test + fun `an unreadable file reads as no record`() { + file.parentFile!!.mkdirs() + file.writeText("pluginX=\\u12") + + assertThat(record.read()).isNull() + } + + @Test + fun `a file without a fingerprint reads as no record`() { + file.parentFile!!.mkdirs() + file.writeText("plugin.0=com.example.one\n") + + assertThat(record.read()).isNull() + } + + @Test + fun `failures are stored unreported and kept with the bundle`() { + record.write(state) + + record.recordFailures(linkedMapOf("com.example.one" to "boom", "com.example.two" to "bang")) + + assertThat(record.unreportedFailures()) + .containsExactly( + BundledPluginFailure("com.example.one", "boom", reported = false), + BundledPluginFailure("com.example.two", "bang", reported = false), + ).inOrder() + assertThat(record.read()!!.copy(failures = emptyList())).isEqualTo(state) + } + + @Test + fun `failures with odd characters survive`() { + record.write(state) + val message = "line one\nline two = \"quoted\" \\ back: é" + + record.recordFailures(mapOf("com.example.one" to message)) + + assertThat(record.unreportedFailures().single().message).isEqualTo(message) + } + + @Test + fun `markReported hands the failures out once`() { + record.write(state) + record.recordFailures(mapOf("com.example.one" to "boom")) + + val told = record.unreportedFailures() + val first = record.markReported(told) + val second = record.markReported(told) + + assertThat(first).containsExactly(BundledPluginFailure("com.example.one", "boom", reported = false)) + assertThat(second).isEmpty() + assertThat(record.unreportedFailures()).isEmpty() + assertThat(record.read()!!.failures).containsExactly(BundledPluginFailure("com.example.one", "boom", reported = true)) + } + + @Test + fun `a new failure after a report is unreported again`() { + record.write(state) + record.recordFailures(mapOf("com.example.one" to "boom")) + record.markReported(record.unreportedFailures()) + + record.recordFailures(mapOf("com.example.two" to "bang")) + + assertThat(record.unreportedFailures()).containsExactly(BundledPluginFailure("com.example.two", "bang", reported = false)) + } + + @Test + fun `markReported leaves a failure recorded after the told ones were read`() { + record.write(state) + record.recordFailures(mapOf("com.example.one" to "boom")) + val told = record.unreportedFailures() + + record.recordFailures(mapOf("com.example.two" to "bang")) + val marked = record.markReported(told) + + assertThat(marked).containsExactly(BundledPluginFailure("com.example.one", "boom")) + assertThat(record.unreportedFailures()).containsExactly(BundledPluginFailure("com.example.two", "bang")) + } + + @Test + fun `markReported leaves a failure recorded again with another message`() { + record.write(state) + record.recordFailures(mapOf("com.example.one" to "boom")) + val told = record.unreportedFailures() + + record.recordFailures(mapOf("com.example.one" to "bang")) + record.markReported(told) + + assertThat(record.unreportedFailures()).containsExactly(BundledPluginFailure("com.example.one", "bang")) + } + + @Test + fun `recording load failures keeps failures recorded under other keys`() { + record.write(state.copy(failures = listOf(BundledPluginFailure("broken.cgp", "it has no readable manifest")))) + + record.recordFailures(mapOf("com.example.one" to "boom")) + + assertThat(record.unreportedFailures()).containsExactly( + BundledPluginFailure("broken.cgp", "it has no readable manifest"), + BundledPluginFailure("com.example.one", "boom"), + ) + } + + @Test + fun `recording failures without a record does nothing`() { + record.recordFailures(mapOf("com.example.one" to "boom")) + + assertThat(file.exists()).isFalse() + } + + @Test + fun `every caller of one files folder shares one record, so its lock covers them all`() { + val filesDir = File(tempFolder.root, "files") + + assertThat(BundledAddonsRecord.inFilesDir(filesDir)).isSameInstanceAs(BundledAddonsRecord.inFilesDir(File(filesDir, "."))) + } +} diff --git a/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonsTest.kt b/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonsTest.kt new file mode 100644 index 0000000000..d4528818f2 --- /dev/null +++ b/app/src/test/java/com/itsaky/androidide/assets/addons/BundledAddonsTest.kt @@ -0,0 +1,321 @@ +package com.itsaky.androidide.assets.addons + +import com.google.common.truth.Truth.assertThat +import com.google.common.truth.Truth.assertWithMessage +import com.itsaky.androidide.assets.AssetsInstallationHelper +import org.adfa.constants.ANDROID_SDK_ZIP +import org.adfa.constants.DOCUMENTATION_DB +import org.adfa.constants.GRADLE_API_NAME_JAR_ZIP +import org.adfa.constants.GRADLE_DISTRIBUTION_ARCHIVE_NAME +import org.adfa.constants.LOCAL_MAVEN_REPO_ARCHIVE_ZIP_NAME +import org.adfa.constants.TEMPLATE_CORE_ARCHIVE +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import java.io.ByteArrayInputStream +import java.io.InputStream +import java.util.zip.ZipEntry +import java.util.zip.ZipFile +import java.util.zip.ZipOutputStream + +class BundledAddonsTest { + @get:Rule + val tempFolder = TemporaryFolder() + + private class FakeSource( + private val files: Map>, + private val indexText: String? = null, + ) : BundleSource { + override fun index() = indexText + + override fun names(dir: String) = files[dir]?.keys?.toList().orEmpty() + + override fun size( + dir: String, + name: String, + ) = files.getValue(dir).getValue(name) + + override fun open( + dir: String, + name: String, + ): InputStream = ByteArrayInputStream(ByteArray(0)) + } + + private fun source( + plugins: Map = emptyMap(), + templates: Map = emptyMap(), + index: String? = null, + ) = FakeSource(mapOf("plugins" to plugins, "templates" to templates), index) + + /** A source with only an index: asking it for a folder, a size or a file fails the test. */ + private class IndexOnlySource( + private val indexText: String, + ) : BundleSource { + override fun names(dir: String): List = throw AssertionError("listed $dir") + + override fun size( + dir: String, + name: String, + ): Long = throw AssertionError("sized $dir/$name") + + override fun open( + dir: String, + name: String, + ): InputStream = throw AssertionError("opened $dir/$name") + + override fun index() = indexText + } + + private val shaA = "a".repeat(64) + private val shaB = "b".repeat(64) + private val shaT = "c".repeat(64) + + private fun line( + entryName: String, + size: Long, + sha256: String, + ) = "$entryName\t$size\t$sha256\n" + + @Test + fun `a thin bundle lists nothing`() { + assertThat(BundledAddons.list(source())).isEmpty() + } + + @Test + fun `a thin build installs exactly the eight fixed entries`() { + assertThat(AssetsInstallationHelper.entriesToInstall(emptyList())) + .containsExactly( + GRADLE_DISTRIBUTION_ARCHIVE_NAME, + ANDROID_SDK_ZIP, + DOCUMENTATION_DB, + LOCAL_MAVEN_REPO_ARCHIVE_ZIP_NAME, + "bootstrap.zip", + GRADLE_API_NAME_JAR_ZIP, + "plugin-artifacts.zip", + TEMPLATE_CORE_ARCHIVE, + ).inOrder() + } + + @Test + fun `a fat build installs the fixed entries then each bundled file`() { + val bundled = BundledAddons.list(source(plugins = mapOf("a.cgp" to 5L), templates = mapOf("t.cgt" to 7L))) + + val entries = AssetsInstallationHelper.entriesToInstall(bundled) + + assertThat(entries).hasSize(10) + assertThat(entries.take(8)).containsExactlyElementsIn(AssetsInstallationHelper.entriesToInstall(emptyList())).inOrder() + assertThat(entries.takeLast(2)).containsExactly("plugins/a.cgp", "templates/t.cgt").inOrder() + } + + @Test + fun `some entries carry their size and sort by name, plugins first`() { + val entries = + BundledAddons.list( + source( + plugins = mapOf("b.cgp" to 20L, "a.cgp" to 10L), + templates = mapOf("t.cgt" to 30L), + ), + ) + + assertThat(entries) + .containsExactly( + BundledEntry(BundledAddonKind.PLUGIN, "a.cgp", 10L), + BundledEntry(BundledAddonKind.PLUGIN, "b.cgp", 20L), + BundledEntry(BundledAddonKind.TEMPLATE, "t.cgt", 30L), + ).inOrder() + assertThat(entries.map { it.entryName }).containsExactly("plugins/a.cgp", "plugins/b.cgp", "templates/t.cgt").inOrder() + } + + @Test + fun `many entries are all listed`() { + val plugins = (1..200).associate { "p$it.cgp" to it.toLong() } + val templates = (1..150).associate { "t$it.cgt" to it.toLong() } + + assertThat(BundledAddons.list(source(plugins, templates))).hasSize(350) + } + + @Test + fun `files that are not add-ons of their folder are ignored`() { + val entries = + BundledAddons.list( + source( + plugins = + mapOf( + "a.cgp" to 1L, + "readme.txt" to 2L, + "t.cgt" to 3L, + ".hidden.cgp" to 4L, + "sub/b.cgp" to 5L, + "UPPER.CGP" to 6L, + ), + templates = mapOf("t.cgt" to 7L, "a.cgp" to 8L), + ), + ) + + assertThat(entries.map { it.entryName }).containsExactly("plugins/UPPER.CGP", "plugins/a.cgp", "templates/t.cgt").inOrder() + } + + @Test + fun `a bundled template named like the core template is ignored`() { + val templates = mapOf("core.cgt" to 1L, "Core.CGT" to 2L, "t.cgt" to 3L) + val entries = BundledAddons.list(source(templates = templates)) + + assertThat(entries.map { it.entryName }).containsExactly("templates/t.cgt") + } + + @Test + fun `parse recognizes only the names a listing produces`() { + assertThat(BundledAddons.parse("plugins/a.cgp")).isEqualTo(BundledAddonKind.PLUGIN to "a.cgp") + assertThat(BundledAddons.parse("templates/t.cgt")).isEqualTo(BundledAddonKind.TEMPLATE to "t.cgt") + assertThat(BundledAddons.parse("plugins/t.cgt")).isNull() + assertThat(BundledAddons.parse("plugins/../a.cgp")).isNull() + assertThat(BundledAddons.parse("core.cgt")).isNull() + assertThat(BundledAddons.parse("plugin-artifacts.zip")).isNull() + } + + @Test + fun `the fingerprint is stable for the same bundle in any order`() { + val a = BundledEntry(BundledAddonKind.PLUGIN, "a.cgp", 10L) + val t = BundledEntry(BundledAddonKind.TEMPLATE, "t.cgt", 30L) + + assertThat(BundledAddons.fingerprint(listOf(a, t))).isEqualTo(BundledAddons.fingerprint(listOf(t, a))) + assertThat(BundledAddons.fingerprint(listOf(a, t))).isEqualTo(BundledAddons.fingerprint(listOf(a, t))) + } + + @Test + fun `the fingerprint changes with a name, a size, a kind or an entry`() { + val a = BundledEntry(BundledAddonKind.PLUGIN, "a.cgp", 10L) + val base = BundledAddons.fingerprint(listOf(a)) + + assertThat(BundledAddons.fingerprint(listOf(a.copy(fileName = "b.cgp")))).isNotEqualTo(base) + assertThat(BundledAddons.fingerprint(listOf(a.copy(size = 11L)))).isNotEqualTo(base) + assertThat(BundledAddons.fingerprint(listOf(a.copy(kind = BundledAddonKind.TEMPLATE, fileName = "a.cgt")))).isNotEqualTo(base) + assertThat(BundledAddons.fingerprint(listOf(a, BundledEntry(BundledAddonKind.TEMPLATE, "t.cgt", 1L)))).isNotEqualTo(base) + assertThat(BundledAddons.fingerprint(emptyList())).isNotEqualTo(base) + } + + @Test + fun `the empty bundle has a fingerprint`() { + assertThat(BundledAddons.fingerprint(emptyList())).matches("[0-9a-f]{64}") + } + + @Test + fun `a zip source lists only the direct files of a folder, with their sizes`() { + val zipFile = tempFolder.newFile("assets.zip") + ZipOutputStream(zipFile.outputStream()).use { zip -> + val entries = listOf("bootstrap.zip" to 3, "plugins/a.cgp" to 5, "plugins/nested/b.cgp" to 9, "templates/t.cgt" to 7) + entries.forEach { (name, size) -> + zip.putNextEntry(ZipEntry(name)) + zip.write(ByteArray(size)) + zip.closeEntry() + } + } + + ZipFile(zipFile).use { zip -> + val entries = BundledAddons.list(ZipBundleSource(zip)) + + assertThat(entries) + .containsExactly( + BundledEntry(BundledAddonKind.PLUGIN, "a.cgp", 5L), + BundledEntry(BundledAddonKind.TEMPLATE, "t.cgt", 7L), + ).inOrder() + assertThat(ZipBundleSource(zip).open("plugins", "a.cgp").use { it.readBytes() }).hasLength(5) + } + } + + @Test + fun `an index lists the bundle without listing, sizing or opening an add-on`() { + val index = line("plugins/b.cgp", 20L, shaB) + line("templates/t.cgt", 30L, shaT) + line("plugins/a.cgp", 10L, shaA) + + assertThat(BundledAddons.list(IndexOnlySource(index))) + .containsExactly( + BundledEntry(BundledAddonKind.PLUGIN, "a.cgp", 10L, shaA), + BundledEntry(BundledAddonKind.PLUGIN, "b.cgp", 20L, shaB), + BundledEntry(BundledAddonKind.TEMPLATE, "t.cgt", 30L, shaT), + ).inOrder() + } + + @Test + fun `an empty index is a thin bundle`() { + assertThat(BundledAddons.list(IndexOnlySource(""))).isEmpty() + assertThat(BundledAddons.list(IndexOnlySource("\n"))).isEmpty() + } + + @Test + fun `the fingerprint notices new content at the same name and size`() { + val old = BundledAddons.list(IndexOnlySource(line("plugins/a.cgp", 10L, shaA))) + val rebuilt = BundledAddons.list(IndexOnlySource(line("plugins/a.cgp", 10L, shaB))) + + assertThat(BundledAddons.fingerprint(rebuilt)).isNotEqualTo(BundledAddons.fingerprint(old)) + assertThat(BundledAddons.fingerprint(old)).isNotEqualTo(BundledAddons.fingerprint(emptyList())) + } + + @Test + fun `a malformed index leaves the folders to decide`() { + val folders = listOf(BundledEntry(BundledAddonKind.PLUGIN, "a.cgp", 10L)) + val malformed = + listOf( + "plugins/a.cgp\t10\n", + "plugins/a.cgp\t10\t$shaA\textra\n", + "plugins/a.cgp\tten\t$shaA\n", + "plugins/a.cgp\t-1\t$shaA\n", + "plugins/a.cgp\t10\t${shaA.uppercase()}\n", + "plugins/a.cgp\t10\t${shaA.drop(1)}\n", + line("other/a.cgp", 10L, shaA), + line("plugins/nested/a.cgp", 10L, shaA), + line("plugins/.hidden.cgp", 10L, shaA), + line("templates/$TEMPLATE_CORE_ARCHIVE", 10L, shaA), + line("plugins/a.cgp", 10L, shaA) + line("plugins/a.cgp", 10L, shaB), + ) + + malformed.forEach { index -> + assertWithMessage(index).that(BundledAddons.list(source(plugins = mapOf("a.cgp" to 10L), index = index))).isEqualTo(folders) + } + } + + @Test + fun `a bundle without an index is listed from its folders, without hashes`() { + val entries = BundledAddons.list(source(plugins = mapOf("a.cgp" to 10L))) + + assertThat(entries).containsExactly(BundledEntry(BundledAddonKind.PLUGIN, "a.cgp", 10L)) + assertThat(entries.single().sha256).isNull() + } + + @Test + fun `a zip source reads its index, and has none without the entry`() { + val indexed = tempFolder.newFile("indexed.zip") + ZipOutputStream(indexed.outputStream()).use { zip -> + zip.putNextEntry(ZipEntry("plugins/a.cgp")) + zip.write(ByteArray(5)) + zip.closeEntry() + zip.putNextEntry(ZipEntry(BundledAddons.INDEX_FILE)) + zip.write(line("plugins/a.cgp", 5L, shaA).toByteArray()) + zip.closeEntry() + } + val plain = tempFolder.newFile("plain.zip") + ZipOutputStream(plain.outputStream()).use { zip -> + zip.putNextEntry(ZipEntry("plugins/a.cgp")) + zip.write(ByteArray(5)) + zip.closeEntry() + } + + ZipFile(indexed).use { zip -> + assertThat(BundledAddons.list(ZipBundleSource(zip))).containsExactly(BundledEntry(BundledAddonKind.PLUGIN, "a.cgp", 5L, shaA)) + } + ZipFile(plain).use { zip -> + assertThat(ZipBundleSource(zip).index()).isNull() + assertThat(BundledAddons.list(ZipBundleSource(zip))).containsExactly(BundledEntry(BundledAddonKind.PLUGIN, "a.cgp", 5L)) + } + } + + @Test + fun `a zip source without the folders lists nothing`() { + val zipFile = tempFolder.newFile("thin.zip") + ZipOutputStream(zipFile.outputStream()).use { zip -> + zip.putNextEntry(ZipEntry("bootstrap.zip")) + zip.closeEntry() + } + + ZipFile(zipFile).use { assertThat(BundledAddons.list(ZipBundleSource(it))).isEmpty() } + } +} diff --git a/app/src/test/java/com/itsaky/androidide/assets/addons/BundledFailureReportTest.kt b/app/src/test/java/com/itsaky/androidide/assets/addons/BundledFailureReportTest.kt new file mode 100644 index 0000000000..558074e7f8 --- /dev/null +++ b/app/src/test/java/com/itsaky/androidide/assets/addons/BundledFailureReportTest.kt @@ -0,0 +1,114 @@ +package com.itsaky.androidide.assets.addons + +import com.google.common.truth.Truth.assertThat +import com.google.common.truth.Truth.assertWithMessage +import com.itsaky.androidide.utils.TrackedFlashbar +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.Job +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import java.io.File +import kotlin.coroutines.EmptyCoroutineContext + +/** + * The bundled plugin failures stay unreported until the user dismisses their bar (F30): a screen + * recreated by a font scale change took the bar away, and the failures, already marked when the bar + * appeared, never showed again. + */ +@OptIn(ExperimentalCoroutinesApi::class) +class BundledFailureReportTest { + @get:Rule + val tempFolder = TemporaryFolder() + + private lateinit var record: BundledAddonsRecord + private val bars = ArrayList() + + private class FakeBar( + val failures: List, + ) : TrackedFlashbar { + val dismissed = CompletableDeferred() + + override suspend fun awaitShown() = true + + override suspend fun awaitDismissed() = dismissed.await() + } + + @Before + fun setUp() { + record = BundledAddonsRecord(File(tempFolder.root, "bundled_addons.properties")) + record.write(BundledAddonsState("fp", listOf("com.example.one", "com.example.two"))) + record.recordFailures(mapOf("com.example.one" to "boom")) + bars.clear() + } + + private fun TestScope.startReport(): Job { + val job = launch { record.reportFailures(EmptyCoroutineContext) { FakeBar(it).also(bars::add) } } + runCurrent() + return job + } + + @Test + fun `the failures stay unreported until the user dismisses the bar, so the next screen shows them again`() = + runTest { + val report = startReport() + assertThat(bars).hasSize(1) + assertWithMessage("failures marked reported while the bar is still up") + .that(record.unreportedFailures()) + .containsExactly(BundledPluginFailure("com.example.one", "boom")) + + // The screen goes away with the bar up: its scope ends, and no dismiss callback fires. + report.cancel() + runCurrent() + assertThat(record.unreportedFailures()).containsExactly(BundledPluginFailure("com.example.one", "boom")) + + val next = startReport() + assertThat(bars).hasSize(2) + assertThat(bars[1].failures).containsExactly(BundledPluginFailure("com.example.one", "boom")) + next.cancel() + } + + @Test + fun `the report lasts while the bar is up, and dismissing it marks the failures reported`() = + runTest { + val report = startReport() + assertWithMessage("report ended before the user dismissed the bar").that(report.isActive).isTrue() + + bars.single().dismissed.complete(Unit) + runCurrent() + + assertThat(report.isCompleted).isTrue() + assertThat(record.unreportedFailures()).isEmpty() + startReport() + assertWithMessage("a bar shown again after the user dismissed it").that(bars).hasSize(1) + } + + @Test + fun `a failure recorded while the bar is up stays unreported`() = + runTest { + startReport() + record.recordFailures(mapOf("com.example.two" to "bang")) + + bars.single().dismissed.complete(Unit) + runCurrent() + + assertThat(record.unreportedFailures()).containsExactly(BundledPluginFailure("com.example.two", "bang")) + } + + @Test + fun `no unreported failure shows no bar`() = + runTest { + record.markReported(record.unreportedFailures()) + + val report = startReport() + + assertThat(bars).isEmpty() + assertThat(report.isCompleted).isTrue() + } +} diff --git a/app/src/test/java/com/itsaky/androidide/assets/addons/BundledPluginStartupTest.kt b/app/src/test/java/com/itsaky/androidide/assets/addons/BundledPluginStartupTest.kt new file mode 100644 index 0000000000..05b44b6580 --- /dev/null +++ b/app/src/test/java/com/itsaky/androidide/assets/addons/BundledPluginStartupTest.kt @@ -0,0 +1,104 @@ +package com.itsaky.androidide.assets.addons + +import com.google.common.truth.Truth.assertThat +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.runBlocking +import org.junit.Assert.assertThrows +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import java.io.File + +class BundledPluginStartupTest { + @get:Rule + val tempFolder = TemporaryFolder() + + private lateinit var record: BundledAddonsRecord + private var reloads = 0 + + @Before + fun setUp() { + record = BundledAddonsRecord(File(tempFolder.root, "bundled_addons.properties")) + reloads = 0 + } + + private fun startup( + reload: suspend () -> Unit = { reloads++ }, + loadError: (String) -> String? = { null }, + ) = BundledPluginStartup(record, reload, loadError) + + private fun writeBundle(vararg pluginIds: String) = record.write(BundledAddonsState("fp", pluginIds.toList())) + + @Test + fun `no record or a thin one starts nothing`() { + runBlocking { + startup().start() + record.write(BundledAddonsState("fp")) + startup().start() + + assertThat(reloads).isEqualTo(0) + } + } + + @Test + fun `a bundle with plugins reloads once and records nothing when all load`() { + runBlocking { + writeBundle("a", "b") + + startup().start() + + assertThat(reloads).isEqualTo(1) + assertThat(record.unreportedFailures()).isEmpty() + } + } + + @Test + fun `only bundled plugins that report a load error are recorded, unreported`() { + runBlocking { + writeBundle("a", "b") + val errors = mapOf("b" to "needs a newer IDE", "other" to "not ours") + + startup(loadError = errors::get).start() + + assertThat(record.unreportedFailures()).containsExactly(BundledPluginFailure("b", "needs a newer IDE", reported = false)) + } + } + + @Test + fun `a reload that throws is recorded for every bundled plugin and does not escape`() { + runBlocking { + writeBundle("a", "b") + + startup(reload = { throw IllegalStateException("registry broken") }).start() + + assertThat(record.unreportedFailures().map { it.pluginId to it.message }) + .containsExactly("a" to "registry broken", "b" to "registry broken") + } + } + + @Test + fun `cancellation is not swallowed`() { + writeBundle("a") + + assertThrows(CancellationException::class.java) { + runBlocking { startup(reload = { throw CancellationException("stop") }).start() } + } + assertThat(record.unreportedFailures()).isEmpty() + } + + @Test + fun `a failure is reported once`() { + runBlocking { + writeBundle("a") + startup(loadError = { "boom" }).start() + + val told = record.unreportedFailures() + val first = record.markReported(told) + val second = record.markReported(told) + + assertThat(first.map { it.pluginId }).containsExactly("a") + assertThat(second).isEmpty() + } + } +} diff --git a/common/src/main/java/com/itsaky/androidide/utils/FlashbarActivityUtils.kt b/common/src/main/java/com/itsaky/androidide/utils/FlashbarActivityUtils.kt index 82e4f3e6d0..f3b82d4e21 100644 --- a/common/src/main/java/com/itsaky/androidide/utils/FlashbarActivityUtils.kt +++ b/common/src/main/java/com/itsaky/androidide/utils/FlashbarActivityUtils.kt @@ -63,7 +63,7 @@ private fun Flashbar.Builder.applyIcon(iconType: IconType): Flashbar.Builder = /** * Builds and configures a Flashbar for [msg]/[iconType] (icon, and - for an indefinite error - the * dismiss button plus tap/swipe dismissal), without showing it yet. Shared by [showFlashBar] and - * [showFlashBarAwaitShown] + * [showTrackedFlashBar] * so their setup can't silently diverge. Returns `null` for a `null` [msg] (nothing to show). */ private fun Activity.configureFlashbar( @@ -161,21 +161,34 @@ fun Activity.flashInfo(msg: String?) = showFlashBar(msg, IconType.INFO) // is the difference between an explanation and a flicker. fun Activity.flashInfoLong(msg: String?) = showFlashBar(msg, IconType.INFO, duration = DURATION_LONG) +/** A bar shown by [flashErrorTracked], for a caller that waits for it to appear or to be dismissed. */ +interface TrackedFlashbar { + /** Suspends until the bar has finished appearing; false if it has not within [FLASH_SHOWN_TIMEOUT_MS]. */ + suspend fun awaitShown(): Boolean + + /** + * Suspends until the bar is dismissed; for an indefinite error bar, only the user does that. + * Destroying the activity fires no dismiss callback (the bar's view is only detached), so if the + * activity goes away first this never returns: wait in a scope that ends with the activity, such + * as its lifecycleScope. + */ + suspend fun awaitDismissed() +} + /** - * Like [showFlashBar], but suspends until the bar's entrance animation has actually finished (or - * [FLASH_SHOWN_TIMEOUT_MS] elapses) instead of firing-and-forgetting - for callers (e.g. a - * one-shot screen about to finish()) that need the message to be visible before proceeding, - * rather than guessing a fixed delay that may or may not outlast the real animation. + * Like [showFlashBar], but returns a [TrackedFlashbar] to wait on: for its entrance animation to + * finish, or for its dismissal. Returns `null` for a `null` [msg]. */ -private suspend fun Activity.showFlashBarAwaitShown( +private fun Activity.showTrackedFlashBar( msg: Any?, iconType: IconType, gravity: Flashbar.Gravity = TOP, duration: Long = Flashbar.DURATION_SHORT, -) { - val builder = configureFlashbar(msg, iconType, gravity, duration) ?: return +): TrackedFlashbar? { + val builder = configureFlashbar(msg, iconType, gravity, duration) ?: return null val shown = CompletableDeferred() + val dismissed = CompletableDeferred() builder.barShowListener( object : Flashbar.OnBarShowListener { override fun onShowing(bar: Flashbar) = Unit @@ -190,15 +203,56 @@ private suspend fun Activity.showFlashBarAwaitShown( } }, ) + builder.barDismissListener( + object : Flashbar.OnBarDismissListener { + override fun onDismissing( + bar: Flashbar, + isSwiped: Boolean, + ) = Unit + + override fun onDismissProgress( + bar: Flashbar, + progress: Float, + ) = Unit + + override fun onDismissed( + bar: Flashbar, + event: Flashbar.DismissEvent, + ) { + dismissed.complete(Unit) + } + }, + ) runOnUiThread { builder.build().show() } - withTimeoutOrNull(FLASH_SHOWN_TIMEOUT_MS) { shown.await() } + return object : TrackedFlashbar { + override suspend fun awaitShown() = withTimeoutOrNull(FLASH_SHOWN_TIMEOUT_MS) { shown.await() } != null + + override suspend fun awaitDismissed() = dismissed.await() + } } +/** + * Like [showFlashBar], but suspends until the bar's entrance animation has actually finished (or + * [FLASH_SHOWN_TIMEOUT_MS] elapses) instead of firing-and-forgetting - for callers (e.g. a + * one-shot screen about to finish()) that need the message to be visible before proceeding, + * rather than guessing a fixed delay that may or may not outlast the real animation. + * Returns whether the bar finished appearing: false for a `null` [msg] or on timeout. + */ +private suspend fun Activity.showFlashBarAwaitShown( + msg: Any?, + iconType: IconType, + gravity: Flashbar.Gravity = TOP, + duration: Long = Flashbar.DURATION_SHORT, +): Boolean = showTrackedFlashBar(msg, iconType, gravity, duration)?.awaitShown() ?: false + suspend fun Activity.flashSuccessAwaitShown(msg: String?) = showFlashBarAwaitShown(msg, IconType.SUCCESS) suspend fun Activity.flashErrorAwaitShown(msg: String?) = showFlashBarAwaitShown(msg, IconType.ERROR, duration = DURATION_INDEFINITE) +/** Shows an indefinite error bar, as [flashError] does, and returns it to wait on; `null` for a `null` [msg]. */ +fun Activity.flashErrorTracked(msg: String?): TrackedFlashbar? = showTrackedFlashBar(msg, IconType.ERROR, duration = DURATION_INDEFINITE) + fun Activity.flashSuccess( @StringRes msg: Int, ) = showFlashBar(msg, IconType.SUCCESS) diff --git a/common/src/test/java/com/itsaky/androidide/utils/TrackedFlashbarTest.kt b/common/src/test/java/com/itsaky/androidide/utils/TrackedFlashbarTest.kt new file mode 100644 index 0000000000..0f061e26a1 --- /dev/null +++ b/common/src/test/java/com/itsaky/androidide/utils/TrackedFlashbarTest.kt @@ -0,0 +1,88 @@ +package com.itsaky.androidide.utils + +import android.app.Activity +import android.content.res.Configuration +import android.os.Bundle +import android.os.Looper +import android.view.View +import com.google.common.truth.Truth.assertThat +import com.itsaky.androidide.resources.R +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeoutOrNull +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.Robolectric +import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf +import java.time.Duration +import com.itsaky.androidide.flashbar.R as FlashbarR + +/** + * Whether an indefinite error bar counts as dismissed: by the Dismiss button yes, by its activity + * going away no. Destroying the activity only detaches the bar's view, and Flashbar fires no dismiss + * callback for that, which is what lets a caller keep a report unread when a font scale change + * recreates the screen (F30). + */ +@RunWith(RobolectricTestRunner::class) +class TrackedFlashbarTest { + class ThemedActivity : Activity() { + override fun onCreate(savedInstanceState: Bundle?) { + setTheme(R.style.Theme_AndroidIDE) + super.onCreate(savedInstanceState) + } + } + + private fun idle() = shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(5)) + + private fun TrackedFlashbar.isShown() = runBlocking { awaitShown() } + + private fun TrackedFlashbar.isDismissed() = runBlocking { withTimeoutOrNull(1) { awaitDismissed() } } != null + + @Test + fun `the Dismiss button dismisses the bar`() { + val controller = Robolectric.buildActivity(ThemedActivity::class.java).setup() + val bar = controller.get().flashErrorTracked("boom")!! + idle() + assertThat(bar.isShown()).isTrue() + assertThat(bar.isDismissed()).isFalse() + + controller + .get() + .window.decorView + .findViewById(FlashbarR.id.fbPositiveAction) + .performClick() + idle() + + assertThat(bar.isDismissed()).isTrue() + } + + @Test + fun `a font scale change that recreates the activity does not dismiss the bar`() { + val controller = Robolectric.buildActivity(ThemedActivity::class.java).setup() + val first = controller.get() + val bar = first.flashErrorTracked("boom")!! + idle() + assertThat(bar.isShown()).isTrue() + + controller.configurationChange(Configuration(first.resources.configuration).apply { fontScale = 2f }) + idle() + + assertThat(controller.get()).isNotSameInstanceAs(first) + assertThat(first.isDestroyed).isTrue() + assertThat(bar.isDismissed()).isFalse() + } + + @Test + fun `finishing and destroying the activity does not dismiss the bar`() { + val controller = Robolectric.buildActivity(ThemedActivity::class.java).setup() + val bar = controller.get().flashErrorTracked("boom")!! + idle() + assertThat(bar.isShown()).isTrue() + + controller.get().finish() + controller.pause().stop().destroy() + idle() + + assertThat(bar.isDismissed()).isFalse() + } +} diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginIds.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginIds.kt index cd0910fe70..dc9f403d91 100644 --- a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginIds.kt +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginIds.kt @@ -10,7 +10,7 @@ import org.adfa.constants.PLUGIN_ARCHIVE_EXTENSION * CoGo build. Uninstalling either would delete what it names. * Nullable because a `plugin.json` manifest without an ID parses to a null one. */ -internal fun checkPluginId(id: String?): Result = +fun checkPluginId(id: String?): Result = when { id.isNullOrEmpty() || id == "." || id == ".." || id.any { it == '/' || it == '\\' || it == '\u0000' } -> { Result.failure(IllegalArgumentException("Invalid plugin ID \"$id\": it must be a name, not a path")) diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManager.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManager.kt index 6dc4b62e01..df3a628b5a 100644 --- a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManager.kt +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManager.kt @@ -453,14 +453,19 @@ class PluginManager private constructor( // After loading all plugins, verify documentation for already loaded plugins verifyDocumentationForLoadedPlugins() - val pluginFiles = + val allFiles = pluginsDir.listFiles { file -> file.isFile && file.name.endsWith(".$PLUGIN_ARCHIVE_EXTENSION", ignoreCase = true) } ?: return@withContext - logger.info("Found ${pluginFiles.size} plugin files") + // Loading a file again would replace its entry without deactivating the old instance. + val loadedPaths = loadedPlugins.values.map { it.apkPath }.toSet() + val pluginFiles = allFiles.filter { it.absolutePath !in loadedPaths } - loadFailures.clear() + logger.info("Found ${allFiles.size} plugin files, ${pluginFiles.size} not loaded yet") + + // Keep what a loaded plugin failed at (activation), which a skipped file cannot report again. + loadFailures.keys.removeAll { !loadedPlugins.containsKey(it) } // Load plugins in parallel val loadJobs = @@ -804,8 +809,10 @@ class PluginManager private constructor( buildActionManager.registerManifestActions(manifest.id, manifest.name, manifest) lifecycleDispatcher.notifyActivated(manifest.id) notifyLanguageContributionsChanged(plugin) + loadFailures.remove(manifest.id) }.onFailure { e -> logger.error("Failed to activate plugin: ${manifest.id}", e) + loadFailures[manifest.id] = e.message ?: e.toString() loadedPlugin.isEnabled = false savePluginState(manifest.id, false) // activate() may have registered workspace listeners before it failed. diff --git a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerLoadPassTest.kt b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerLoadPassTest.kt new file mode 100644 index 0000000000..454506bd9d --- /dev/null +++ b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerLoadPassTest.kt @@ -0,0 +1,143 @@ +package com.itsaky.androidide.plugins.manager.core + +import com.google.common.truth.Truth.assertThat +import com.google.common.truth.Truth.assertWithMessage +import com.itsaky.androidide.plugins.IPlugin +import com.itsaky.androidide.plugins.PluginContext +import kotlinx.coroutines.runBlocking +import org.junit.After +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config +import java.io.File +import java.util.concurrent.atomic.AtomicInteger + +/** + * loadPlugins() runs at startup, after every install and when bundled plugins start, so a pass + * meets plugins an earlier pass loaded. It leaves their files alone, so it keeps the activation + * failures they reported, which nothing would report again. It forgets the failures of plugins no + * longer loaded, and a plugin that activates clears its failure. + */ +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34]) +class PluginManagerLoadPassTest { + private val pluginsDir by lazy { File(RuntimeEnvironment.getApplication().filesDir, "plugins") } + + @Before + fun resetPlugin() = CountingPlugin.reset() + + @After + fun forgetManager() = forgetPluginManager() + + @Test + fun aSecondPassDoesNotLoadOrActivateALoadedPluginAgain() { + countingPlugin("a") + load() + val first = pluginManager().getPlugin("a") + assertWithMessage("plugin a did not load: ${pluginManager().getLoadError("a")}").that(first).isNotNull() + + load() + + assertWithMessage("the second pass replaced plugin a").that(pluginManager().getPlugin("a")).isSameInstanceAs(first) + assertWithMessage("the second pass initialized plugin a again").that(CountingPlugin.initializations.get()).isEqualTo(1) + assertWithMessage("the second pass activated plugin a again").that(CountingPlugin.activations.get()).isEqualTo(1) + } + + @Test + fun aSecondPassDoesNotOpenAFileAlreadyLoaded() { + val file = countingPlugin("a") + load() + assertThat(pluginManager().getLoadedPluginIds()).containsExactly("a") + // Robolectric reads a plugin's manifest from the package manager: the loaded file now reads + // as plugin "b", which only a pass that opened the file again would load. + fakePlugin(file, "b", NoopPlugin::class.java.name) + + load() + + assertWithMessage("the second pass opened the loaded file again").that(pluginManager().getLoadedPluginIds()).containsExactly("a") + } + + @Test + fun aLoadedPluginsActivationFailureSurvivesALaterPass() { + CountingPlugin.failActivation = true + countingPlugin("a") + load() + assertThat(pluginManager().getLoadedPluginIds()).containsExactly("a") + assertThat(pluginManager().getLoadError("a")).isEqualTo(CountingPlugin.ACTIVATION_ERROR) + + load() + + assertWithMessage("the later pass dropped the activation failure of loaded plugin a") + .that(pluginManager().getLoadError("a")) + .isEqualTo(CountingPlugin.ACTIVATION_ERROR) + } + + @Test + fun aPassDropsTheFailureOfAPluginNoLongerLoaded() { + CountingPlugin.failActivation = true + countingPlugin("a") + load() + assertThat(pluginManager().getLoadError("a")).isEqualTo(CountingPlugin.ACTIVATION_ERROR) + assertThat(pluginManager().uninstallPlugin("a")).isTrue() + // Its main class is missing, so the pass records a failure of its own, which it must report. + fakePlugin(File(pluginsDir, "b-0123456789012345.cgp"), "b") + + load() + + assertWithMessage("the failure of uninstalled plugin a outlived the pass").that(pluginManager().getLoadError("a")).isNull() + assertWithMessage("the pass dropped the failure it recorded itself").that(pluginManager().getLoadError("b")).isNotNull() + } + + @Test + fun aSuccessfulActivationClearsTheEarlierFailure() { + CountingPlugin.failActivation = true + countingPlugin("a") + load() + assertThat(pluginManager().getLoadError("a")).isEqualTo(CountingPlugin.ACTIVATION_ERROR) + + CountingPlugin.failActivation = false + assertWithMessage("enabling plugin a failed").that(pluginManager().enablePlugin("a")).isTrue() + + assertWithMessage("plugin a activated, but its earlier failure is still reported").that(pluginManager().getLoadError("a")).isNull() + } + + private fun load() = runBlocking { pluginManager().loadPlugins() } + + private fun countingPlugin(id: String) = fakePlugin(File(pluginsDir, "$id-0123456789012345.cgp"), id, CountingPlugin::class.java.name) + + /** Counts its initialize() and activate() calls. activate() throws while [failActivation] is set. */ + class CountingPlugin : IPlugin { + override fun initialize(context: PluginContext): Boolean { + initializations.incrementAndGet() + return true + } + + override fun activate(): Boolean { + activations.incrementAndGet() + check(!failActivation) { ACTIVATION_ERROR } + return true + } + + override fun deactivate() = true + + override fun dispose() = Unit + + companion object { + const val ACTIVATION_ERROR = "activate() failed on purpose" + val initializations = AtomicInteger() + val activations = AtomicInteger() + + @Volatile + var failActivation = false + + fun reset() { + initializations.set(0) + activations.set(0) + failActivation = false + } + } + } +} diff --git a/resources/src/main/res/values/strings.xml b/resources/src/main/res/values/strings.xml index d449d21e2e..c8584484b5 100644 --- a/resources/src/main/res/values/strings.xml +++ b/resources/src/main/res/values/strings.xml @@ -109,6 +109,8 @@ Missing installation files. %1$s installation might be corrupt or incomplete. Assets file \'%1$s\' not found. Copy it to %2$s, then restart %3$s. + + Some plugins or templates that came with the app could not be installed or started:\n%1$s The picked file is not a directory. Please wait for a moment. Not enough storage available for installation. An additional %1$.1fGB is required on the internal storage partition. You currently have %2$.1fGB available.