diff --git a/README.md b/README.md index c770de0e..eeabdb5a 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,7 @@ See the official [plugin documentation](https://www.appdevforall.org/codeonthego | [`plugins/AI-Literacy-Course/`](plugins/AI-Literacy-Course/) | An offline "Introduction to AI" course with lesson videos and activities. | | [`plugins/Code-Together/`](plugins/Code-Together/) | Pair programming between two devices on the same network. | | [`plugins/AI-Core/`](plugins/AI-Core/) | The agent chat and the inference router every other AI addon needs. | +| [`plugins/Custom-IDE-Builder/`](plugins/Custom-IDE-Builder/) | Builds a signed copy of Code on the Go with the add-ons you choose. | | [`plugins/Favorite-Snippets/`](plugins/Favorite-Snippets/) | Saves your own code snippets and inserts them in the editor. | | [`plugins/Get-AI-Models/`](plugins/Get-AI-Models/) | Downloads small language models for on-device AI addons. | | [`plugins/Icons-Repository/`](plugins/Icons-Repository/) | Adds vector icons to a project from inside the editor. | diff --git a/plugins/Custom-IDE-Builder/.gitignore b/plugins/Custom-IDE-Builder/.gitignore new file mode 100644 index 00000000..6af499b7 --- /dev/null +++ b/plugins/Custom-IDE-Builder/.gitignore @@ -0,0 +1,29 @@ +# Gradle +.gradle/ +build/ +gradle-app.setting +!gradle-wrapper.jar +.gradletasknamecache + +# IDE +.idea/ +*.iml +*.ipr +*.iws +.project +.classpath +.settings/ +.kotlin/ + +# Local configuration +local.properties + +# OS +.DS_Store +Thumbs.db + +# Logs +*.log + +# Test outputs +test-results/ diff --git a/plugins/Custom-IDE-Builder/README.md b/plugins/Custom-IDE-Builder/README.md new file mode 100644 index 00000000..0809a789 --- /dev/null +++ b/plugins/Custom-IDE-Builder/README.md @@ -0,0 +1,43 @@ +# Custom IDE Builder + +Builds a copy of the installed Code on the Go with a chosen set of plugins (`.cgp`) and templates +(`.cgt`) bundled inside, signed with the user's own key. Release builds only: the host reads the bundle +from `assets/plugins/`, `assets/templates/` and `assets/bundled-addons.tsv` in its APK. + +## Layout + +Everything with logic is in `org.appdevforall.customidebuilder.core` and imports nothing from +`android.*`, so its tests run on a plain JVM. + +```sh +../../gradlew testDebugUnitTest # from this folder: the tests +scripts/build-plugins.sh Custom-IDE-Builder # from the repository root: the .cgp, build/plugin/custom-ide-builder.cgp +``` + +Works with Code on the Go 26.48 and later (`plugin.min_ide_version` 26.48, `plugin.max_ide_version` 99). + +| File | Does | +|---|---| +| `Zip.kt` | Reads a zip's central directory; writes zips with raw (still compressed) entries, 4-byte aligned when stored (`.so` files 16 KB) | +| `ApkRewriter.kt` | Copies the host APK entry by entry, drops the old bundle and v1 signature, adds the add-ons and a new index | +| `Bundle.kt` | The bundle index, byte for byte as Code on the Go's build writes it | +| `Selection.kt` | Validates the chosen add-ons: duplicate plugin IDs, duplicate template names, `core.cgt`, entry names | +| `Staging.kt` | Names the copy of a picked file (`/addon.cgp`, never the provider's name) and checks a path is inside the staging folder before any write or delete | +| `Keystores.kt` | Detects PKCS12 or BKS, rejects JKS with the `keytool` conversion, loads a key | +| `Signing.kt` | apksig: signs v1, v2 and v3, then verifies | +| `Catalog.kt`, `Download.kt` | The v2 catalog, `minAppVersion` filtering, verified downloads from `addons.appdevforall.org` only | +| `Pipeline.kt` | Rewrite, sign, verify, check alignment | + +The Android side (`BuilderFragment`, `Session`, `AndroidBits`) is the screen, the file pickers and +the Storage Access Framework output. + +## Mirrors of Code on the Go + +`AddonKind` repeats `BundledAddonKind`, and `BundleIndex.render` repeats `StageBundledAddons` +(`app/build.gradle.kts`). `BundledAddons.parseIndex` is copied into the index test with a comment naming its +source. If Code on the Go changes the bundle, change these together. + +## Signing dependency + +`com.android.tools.build:apksig` is bundled into the `.cgp`. Its version is kept equal to the Android Gradle +plugin's in `settings.gradle.kts`. diff --git a/plugins/Custom-IDE-Builder/addon.json b/plugins/Custom-IDE-Builder/addon.json new file mode 100644 index 00000000..b45a48f4 --- /dev/null +++ b/plugins/Custom-IDE-Builder/addon.json @@ -0,0 +1,15 @@ +{ + "summary": "Builds a signed copy of Code on the Go with the add-ons you choose.", + "description": "Makes a copy of the Code on the Go installed on this device with the plugins and templates you pick bundled inside, and signs it with your own keystore, so you can hand out a version that arrives ready to use.", + "tags": [ + "signing", + "release", + "distribution" + ], + "origin": "appdevforall", + "license": "AGPL-3.0-or-later", + "author": { + "name": "App Dev For All", + "url": "https://www.appdevforall.org" + } +} diff --git a/plugins/Custom-IDE-Builder/build.gradle.kts b/plugins/Custom-IDE-Builder/build.gradle.kts new file mode 100644 index 00000000..c7e31e41 --- /dev/null +++ b/plugins/Custom-IDE-Builder/build.gradle.kts @@ -0,0 +1,85 @@ +import org.jetbrains.kotlin.gradle.dsl.JvmTarget + +plugins { + id("com.android.application") + id("com.itsaky.androidide.plugins.build") +} + +pluginBuilder { + pluginName = "custom-ide-builder" +} + +android { + namespace = "org.appdevforall.customidebuilder" + compileSdk = 36 + + defaultConfig { + applicationId = "org.appdevforall.customidebuilder" + minSdk = 26 + targetSdk = 36 + versionCode = 1 + versionName = "1.0.0" + } + + buildTypes { + release { + isMinifyEnabled = false + proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro") + } + } + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + packaging { + resources { + excludes += setOf( + "META-INF/versions/9/OSGI-INF/MANIFEST.MF", + "META-INF/DEPENDENCIES", + "META-INF/LICENSE", + "META-INF/LICENSE.txt", + "META-INF/NOTICE", + "META-INF/NOTICE.txt" + ) + } + } +} + +kotlin { + compilerOptions { + jvmTarget.set(JvmTarget.JVM_17) + } +} + +dependencies { + // plugin-api is the IDE-side contract: compile against it, the IDE provides it. + compileOnly(files("../../libs/plugin-api.jar")) + + // Code on the Go loads classes parent-first and carries its own AndroidX, so the Fragment and + // Activity Result classes this screen uses come from the host, never from a bundled copy. + compileOnly("androidx.fragment:fragment:1.8.8") + + implementation("org.jetbrains.kotlin:kotlin-stdlib:2.3.21") + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.8.1") + + // Signs the APK (v1, v2 and v3) and verifies the result. It is the same version as the Android + // Gradle plugin in settings.gradle.kts, which publishes apksig beside itself on Google Maven. + // Bundled into the .cgp: the host does not carry it. + implementation("com.android.tools.build:apksig:9.3.1") + + // Tests run on a computer's Java. There Android's org.json is an empty stub, so they bring their own, + // and BouncyCastle writes the BKS keystores that Android's built-in provider reads and makes the test certificates. + testImplementation("junit:junit:4.13.2") + testImplementation("org.json:json:20240303") + testImplementation("org.bouncycastle:bcprov-jdk18on:1.78") + testImplementation("org.bouncycastle:bcpkix-jdk18on:1.78") +} + +tasks.matching { + it.name.contains("checkDebugAarMetadata") || + it.name.contains("checkReleaseAarMetadata") +}.configureEach { + enabled = false +} diff --git a/plugins/Custom-IDE-Builder/custom-ide-builder.html b/plugins/Custom-IDE-Builder/custom-ide-builder.html new file mode 100644 index 00000000..93da97a9 --- /dev/null +++ b/plugins/Custom-IDE-Builder/custom-ide-builder.html @@ -0,0 +1,147 @@ + + + + + +Custom IDE Builder + + + +

Custom IDE Builder

+ +

Executive overview

+

Custom IDE Builder makes a copy of the Code on the Go installed on this device, with the + plugins and templates you choose bundled inside it, and signs the copy with your own key. Use it to + hand out a version of Code on the Go that arrives with the add-ons a class, a team or a community needs + already in place.

+ +
+

Read this before you install a copy. The copy is signed with your key, not ours, so Android + treats it as a different app. It installs only after Code on the Go has been uninstalled, and + uninstalling erases the projects stored in the app's data. Copy your projects out first.

+
+ +

Core functionality

+ + +

Technical architecture

+ + +

Usage

+

What you need

+ + +

How to use it

+
    +
  1. Open Custom IDE Builder from the main menu.
  2. +
  3. Add-ons. Tap Add from this device to pick several files at once. Tap + Add from the website to choose from the add-ons that work with this version of Code on the Go. + Nothing is downloaded until you confirm; the downloads come from addons.appdevforall.org + and each one is checked against the size and SHA-256 the website publishes. Tap Remove beside an + add-on to take it off the list.
  4. +
  5. Signing key. Choose the keystore file, type the store password and tap Read keys, + then pick the key. Leave the key password blank if it is the same as the store password.
  6. +
  7. Output folder. Choose it once; it is remembered.
  8. +
  9. Tap Build APK. Tap Cancel to stop it. A cancelled or failed + build saves nothing: if it had already begun writing the APK to your folder, that unfinished file is + deleted.
  10. +
+

Long-press any button or field on the screen for a short explanation.

+ +

Key benefits

+ + +

Good to know

+ + + diff --git a/plugins/Custom-IDE-Builder/gradle.properties b/plugins/Custom-IDE-Builder/gradle.properties new file mode 100644 index 00000000..9ba44411 --- /dev/null +++ b/plugins/Custom-IDE-Builder/gradle.properties @@ -0,0 +1,4 @@ +android.useAndroidX=true +android.nonTransitiveRClass=true +kotlin.code.style=official +org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 diff --git a/plugins/Custom-IDE-Builder/proguard-rules.pro b/plugins/Custom-IDE-Builder/proguard-rules.pro new file mode 100644 index 00000000..5beb2270 --- /dev/null +++ b/plugins/Custom-IDE-Builder/proguard-rules.pro @@ -0,0 +1,2 @@ +# Keep plugin classes — the IDE loads them by name via plugin.main_class and the screen by class name. +-keep class org.appdevforall.customidebuilder.** { *; } diff --git a/plugins/Custom-IDE-Builder/settings.gradle.kts b/plugins/Custom-IDE-Builder/settings.gradle.kts new file mode 100644 index 00000000..71909681 --- /dev/null +++ b/plugins/Custom-IDE-Builder/settings.gradle.kts @@ -0,0 +1,30 @@ +pluginManagement { + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} + +buildscript { + repositories { + google() + mavenCentral() + } + dependencies { + classpath(files("../../libs/plugin-api.jar")) + classpath(files("../../libs/gradle-plugin.jar")) + classpath("com.android.tools.build:gradle:9.3.1") + classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:2.3.21") + } +} + +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { + google() + mavenCentral() + } +} + +rootProject.name = "custom-ide-builder" diff --git a/plugins/Custom-IDE-Builder/src/main/AndroidManifest.xml b/plugins/Custom-IDE-Builder/src/main/AndroidManifest.xml new file mode 100644 index 00000000..b14ab93c --- /dev/null +++ b/plugins/Custom-IDE-Builder/src/main/AndroidManifest.xml @@ -0,0 +1,65 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/Custom-IDE-Builder/src/main/assets/docs/index.html b/plugins/Custom-IDE-Builder/src/main/assets/docs/index.html new file mode 100644 index 00000000..93da97a9 --- /dev/null +++ b/plugins/Custom-IDE-Builder/src/main/assets/docs/index.html @@ -0,0 +1,147 @@ + + + + + +Custom IDE Builder + + + +

Custom IDE Builder

+ +

Executive overview

+

Custom IDE Builder makes a copy of the Code on the Go installed on this device, with the + plugins and templates you choose bundled inside it, and signs the copy with your own key. Use it to + hand out a version of Code on the Go that arrives with the add-ons a class, a team or a community needs + already in place.

+ +
+

Read this before you install a copy. The copy is signed with your key, not ours, so Android + treats it as a different app. It installs only after Code on the Go has been uninstalled, and + uninstalling erases the projects stored in the app's data. Copy your projects out first.

+
+ +

Core functionality

+ + +

Technical architecture

+ + +

Usage

+

What you need

+ + +

How to use it

+
    +
  1. Open Custom IDE Builder from the main menu.
  2. +
  3. Add-ons. Tap Add from this device to pick several files at once. Tap + Add from the website to choose from the add-ons that work with this version of Code on the Go. + Nothing is downloaded until you confirm; the downloads come from addons.appdevforall.org + and each one is checked against the size and SHA-256 the website publishes. Tap Remove beside an + add-on to take it off the list.
  4. +
  5. Signing key. Choose the keystore file, type the store password and tap Read keys, + then pick the key. Leave the key password blank if it is the same as the store password.
  6. +
  7. Output folder. Choose it once; it is remembered.
  8. +
  9. Tap Build APK. Tap Cancel to stop it. A cancelled or failed + build saves nothing: if it had already begun writing the APK to your folder, that unfinished file is + deleted.
  10. +
+

Long-press any button or field on the screen for a short explanation.

+ +

Key benefits

+ + +

Good to know

+ + + diff --git a/plugins/Custom-IDE-Builder/src/main/assets/icon_day.png b/plugins/Custom-IDE-Builder/src/main/assets/icon_day.png new file mode 100644 index 00000000..19d71e73 Binary files /dev/null and b/plugins/Custom-IDE-Builder/src/main/assets/icon_day.png differ diff --git a/plugins/Custom-IDE-Builder/src/main/assets/icon_night.png b/plugins/Custom-IDE-Builder/src/main/assets/icon_night.png new file mode 100644 index 00000000..d30185a7 Binary files /dev/null and b/plugins/Custom-IDE-Builder/src/main/assets/icon_night.png differ diff --git a/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/AndroidBits.kt b/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/AndroidBits.kt new file mode 100644 index 00000000..f28bf669 --- /dev/null +++ b/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/AndroidBits.kt @@ -0,0 +1,170 @@ +package org.appdevforall.customidebuilder + +import android.content.Context +import android.content.pm.PackageManager +import android.net.Uri +import android.os.Build +import android.provider.DocumentsContract +import android.provider.OpenableColumns +import java.io.File +import java.io.IOException + +/** What the screen needs to know about the Code on the Go that is running. */ +class HostInfo( + val apk: File, + val splitDirs: List, + val label: String, + val versionName: String?, + val minSdk: Int, +) + +/** The Android-only reads. Everything with logic in it is in `core`, where it can be tested on a JVM. */ +object AndroidBits { + const val APK_MIME = "application/vnd.android.package-archive" + + /** + * The HOST's APK. The plugin's own context would name the .cgp. `applicationContext` of the + * context the host gave the plugin is the host's; [fallback] (the screen's own context, also + * the host's) is used if that ever turns out to be the plugin file. + */ + fun hostInfo(pluginContext: Context?, fallback: Context): HostInfo { + var app = (pluginContext ?: fallback).applicationContext + if (app.applicationInfo.sourceDir.endsWith(".cgp", ignoreCase = true)) app = fallback.applicationContext + val info = app.applicationInfo + val pm = app.packageManager + @Suppress("DEPRECATION") + val versionName = pm.getPackageInfo(app.packageName, 0).versionName + return HostInfo( + apk = File(info.sourceDir), + splitDirs = info.splitSourceDirs?.toList().orEmpty(), + label = pm.getApplicationLabel(info).toString(), + versionName = versionName, + minSdk = info.minSdkVersion, + ) + } + + /** + * The `plugin.id` in a .cgp's manifest, the way the host reads it (PluginLoader.getPluginMetadata): + * the meta-data entry, else the package name. Null when the file is not an APK or lacks + * `plugin.main_class`, which the host also requires. + */ + fun readPluginId(context: Context, file: File): String? { + val pm = context.packageManager + val info = + try { + if (Build.VERSION.SDK_INT >= 33) { + pm.getPackageArchiveInfo(file.path, PackageManager.PackageInfoFlags.of(PackageManager.GET_META_DATA.toLong())) + } else { + @Suppress("DEPRECATION") + pm.getPackageArchiveInfo(file.path, PackageManager.GET_META_DATA) + } + } catch (e: Exception) { + null + } ?: return null + val meta = info.applicationInfo?.metaData ?: return null + if (meta.getString("plugin.main_class").isNullOrEmpty()) return null + return meta.getString("plugin.id") ?: info.packageName + } + + fun displayName(context: Context, uri: Uri): String? = + try { + context.contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { + if (it.moveToFirst()) it.getString(0) else null + } + } catch (e: Exception) { + null + } + + /** The size the provider reports for [uri] in bytes, or null when it does not say. */ + fun displaySize(context: Context, uri: Uri): Long? = + try { + context.contentResolver.query(uri, arrayOf(OpenableColumns.SIZE), null, null, null)?.use { + if (it.moveToFirst() && !it.isNull(0)) it.getLong(0).takeIf { n -> n >= 0 } else null + } + } catch (e: Exception) { + null + } + + /** + * Copies what [uri] holds into [target], stopping at [limit] bytes. [checkCancelled] is called + * between buffers and may throw to stop; [target] is then left partly written for the caller to delete. + */ + fun copyToFile(context: Context, uri: Uri, target: File, limit: Long = Long.MAX_VALUE, checkCancelled: () -> Unit = {}) { + target.parentFile?.mkdirs() + val input = context.contentResolver.openInputStream(uri) ?: throw IOException("Cannot open $uri") + input.use { source -> + target.outputStream().use { out -> + val buffer = ByteArray(64 * 1024) + var total = 0L + while (true) { + checkCancelled() + val n = source.read(buffer) + if (n < 0) break + total += n + if (total > limit) throw IOException("The file is larger than expected.") + out.write(buffer, 0, n) + } + } + } + } + + fun readBytes(context: Context, uri: Uri, limit: Int): ByteArray { + val input = context.contentResolver.openInputStream(uri) ?: throw IOException("Cannot open $uri") + input.use { source -> + val out = java.io.ByteArrayOutputStream() + val buffer = ByteArray(8192) + while (true) { + val n = source.read(buffer) + if (n < 0) break + out.write(buffer, 0, n) + if (out.size() > limit) throw IOException("The file is larger than expected.") + } + return out.toByteArray() + } + } + + /** Creates [name] in the folder [tree] (a tree URI from ACTION_OPEN_DOCUMENT_TREE) and returns its URI. */ + fun createInTree(context: Context, tree: Uri, name: String): Uri { + val parent = DocumentsContract.buildDocumentUriUsingTree(tree, DocumentsContract.getTreeDocumentId(tree)) + return DocumentsContract.createDocument(context.contentResolver, parent, APK_MIME, name) + ?: throw IOException("The folder would not create $name. Choose the folder again.") + } + + /** + * Copies [source] into the document [target]. [checkCancelled] is called between buffers and may + * throw to stop; [target] then holds a partial file, which the caller removes with [deleteDocument]. + */ + fun copyFileTo(context: Context, source: File, target: Uri, checkCancelled: () -> Unit = {}, onBytes: (Long) -> Unit) { + val out = context.contentResolver.openOutputStream(target, "w") ?: throw IOException("Cannot write to the folder.") + out.use { sink -> + source.inputStream().use { input -> + val buffer = ByteArray(64 * 1024) + var total = 0L + while (true) { + checkCancelled() + val n = input.read(buffer) + if (n < 0) break + sink.write(buffer, 0, n) + total += n + onBytes(total) + } + } + } + } + + /** Removes the document [uri]; false if the provider would not (a failed cleanup is not worth a second error). */ + fun deleteDocument(context: Context, uri: Uri): Boolean = + try { + DocumentsContract.deleteDocument(context.contentResolver, uri) + } catch (e: Exception) { + false + } + + /** A readable name for a tree URI, such as `Download/Builds`. */ + fun treeLabel(tree: Uri): String = + try { + DocumentsContract.getTreeDocumentId(tree).substringAfter(':').ifEmpty { "the storage root" } + } catch (e: Exception) { + tree.toString() + } +} diff --git a/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/BuilderFragment.kt b/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/BuilderFragment.kt new file mode 100644 index 00000000..9409c332 --- /dev/null +++ b/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/BuilderFragment.kt @@ -0,0 +1,377 @@ +package org.appdevforall.customidebuilder + +import android.app.AlertDialog +import android.content.Context +import android.content.Intent +import android.content.SharedPreferences +import android.net.Uri +import android.os.Bundle +import android.text.InputType +import android.util.TypedValue +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.AdapterView +import android.widget.ArrayAdapter +import android.widget.Button +import android.widget.EditText +import android.widget.LinearLayout +import android.widget.ProgressBar +import android.widget.ScrollView +import android.widget.Spinner +import android.widget.TextView +import androidx.activity.result.contract.ActivityResultContracts +import androidx.fragment.app.Fragment +import org.appdevforall.customidebuilder.core.AddonKind +import org.appdevforall.customidebuilder.core.Catalog + +/** + * The Custom IDE Builder screen. Views are built in code, so there is no layout to inflate against the + * host's resources, and every text size is in sp and every gap in dp, inside a ScrollView, so the screen + * holds up at 2x font scale. State that must outlive the screen is in [Session]. + */ +class BuilderFragment : Fragment() { + private lateinit var prefs: SharedPreferences + private lateinit var itemsBox: LinearLayout + private lateinit var keystoreLabel: TextView + private lateinit var storePassword: EditText + private lateinit var keyPassword: EditText + private lateinit var aliasSpinner: Spinner + private lateinit var fingerprint: TextView + private lateinit var folderLabel: TextView + private lateinit var progress: ProgressBar + private lateinit var stageLabel: TextView + private lateinit var messageLabel: TextView + private lateinit var cancelButton: Button + private val actionButtons = ArrayList