Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
152 changes: 152 additions & 0 deletions app/src/main/java/com/itsaky/androidide/actions/etc/ExportApkAction.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
package com.itsaky.androidide.actions.etc

import android.content.Context
import android.os.Environment
import android.view.MenuItem
import androidx.core.content.ContextCompat
import com.itsaky.androidide.R
import com.itsaky.androidide.actions.ActionData
import com.itsaky.androidide.actions.EditorActivityAction
import com.itsaky.androidide.actions.markInvisible
import com.itsaky.androidide.actions.openApplicationModuleChooser
import com.itsaky.androidide.activities.editor.EditorHandlerActivity
import com.itsaky.androidide.idetooltips.TooltipTag.EDITOR_TOOLBAR_EXPORT_APK
import com.itsaky.androidide.lookup.Lookup
import com.itsaky.androidide.projects.IProjectManager
import com.itsaky.androidide.projects.builder.BuildService
import com.itsaky.androidide.projects.models.assembleTaskOutputListingFile
import com.itsaky.androidide.projects.models.buildDir
import com.itsaky.androidide.quickbuild.QuickBuildTaskPaths
import com.itsaky.androidide.utils.ApkExport
import com.itsaky.androidide.utils.DialogUtils
import com.itsaky.androidide.utils.IntentUtils
import com.itsaky.androidide.utils.flashError
import com.itsaky.androidide.utils.flashSuccess
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.slf4j.LoggerFactory
import java.io.File
import java.io.IOException

/**
* Hands over the selected variant's built APK (ADFA-4930): with relocated build output it is in
* app-private storage, where a file manager cannot reach it. Offers the share sheet, or a copy in
* the Download folder.
*/
class ExportApkAction(
context: Context,
override val order: Int,
) : EditorActivityAction() {
override val id: String = "ide.editor.exportApk"
override var requiresUIThread: Boolean = true

override fun retrieveTooltipTag(isReadOnlyContext: Boolean) = EDITOR_TOOLBAR_EXPORT_APK

init {
label = context.getString(R.string.title_export_apk)
icon = ContextCompat.getDrawable(context, R.drawable.ic_share)
}

override fun prepare(data: ActionData) {
super.prepare(data)
data.getActivity() ?: run {
markInvisible()
return
}

visible = true
// The user-visible flag, like the build actions: Quick Build's prebuild after every project
// open is refused at the tap instead (isBuilding), with a reason.
enabled =
IProjectManager.getInstance().getAndroidAppModules().isNotEmpty() &&
buildService()?.isUserVisibleBuildInProgress != true
}

override suspend fun execAction(data: ActionData) {
if (isBuilding()) return
openApplicationModuleChooser(data) { app ->
val variant = app.getSelectedVariant()
if (variant == null) {
flashError(R.string.err_selected_variant_not_found)
return@openApplicationModuleChooser
}

val activity = data.requireActivity()
val projectManager = IProjectManager.getInstance()
val projectDir = File(projectManager.projectDirPath)
// The module only when it tells two app modules' exports apart.
val module = app.name.takeIf { projectManager.getAndroidAppModules().size > 1 }
val name = listOfNotNull(projectDir.name, module, variant.name).joinToString("-")
activity.activityScope.launch {
val found =
withContext(Dispatchers.IO) {
ApkExport.resolve(
listingFile = variant.mainArtifact.assembleTaskOutputListingFile,
quickBuildReport = QuickBuildTaskPaths.setupJson(app.buildDir, variant.name),
projectDir = projectDir,
)
}
when (found) {
ApkExport.Exportable.NotBuilt -> flashError(R.string.msg_export_apk_not_built)
ApkExport.Exportable.QuickBuildProxy -> flashError(R.string.msg_export_apk_quick_build)
is ApkExport.Exportable.Apk -> withContext(Dispatchers.Main) { offerExport(activity, found.file, name) }
}
}
}
}

private fun buildService(): BuildService? = Lookup.getDefault().lookup(BuildService.KEY_BUILD_SERVICE)

/** A build, Quick Build's prebuild included, may be rewriting the APK; refuse with a reason. */
private fun isBuilding(): Boolean {
if (buildService()?.isBuildInProgress != true) return false
flashError(R.string.msg_export_apk_build_running)
return true
}

private fun offerExport(
activity: EditorHandlerActivity,
apk: File,
name: String,
) {
DialogUtils
.newMaterialDialogBuilder(activity)
.setTitle(R.string.title_export_apk)
.setItems(
arrayOf(
activity.getString(R.string.export_apk_share),
activity.getString(R.string.export_apk_copy_to_download),
),
) { _, which ->
if (which == 0) {
IntentUtils.shareFile(activity, apk, ApkExport.MIME_TYPE)
} else if (!isBuilding()) {
activity.activityScope.launch(Dispatchers.IO) { copyToDownload(activity, apk, name) }
}
}.setNegativeButton(android.R.string.cancel, null)
.show()
}

private fun copyToDownload(
activity: EditorHandlerActivity,
apk: File,
name: String,
) {
@Suppress("DEPRECATION")
val download = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
try {
val copy = ApkExport.copyTo(apk, download, name)
flashSuccess(activity.getString(R.string.msg_export_apk_saved, copy.name))
} catch (e: IOException) {
log.error("Cannot copy {} to {}", apk, download, e)
flashError(R.string.msg_export_apk_failed)
}
}

override fun getShowAsActionFlags(data: ActionData): Int = MenuItem.SHOW_AS_ACTION_IF_ROOM

companion object {
private val log = LoggerFactory.getLogger(ExportApkAction::class.java)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import com.itsaky.androidide.plugins.manager.services.IdeTerminalServiceImpl
import com.itsaky.androidide.preferences.internal.DevOpsPreferences
import com.itsaky.androidide.preferences.internal.GeneralPreferences
import com.itsaky.androidide.resources.localization.LocaleProvider
import com.itsaky.androidide.services.builder.BuildOutputLocation
import com.itsaky.androidide.tooling.api.messages.result.TaskExecutionResult
import com.itsaky.androidide.ui.themes.IDETheme
import com.itsaky.androidide.ui.themes.IThemeManager
Expand Down Expand Up @@ -142,6 +143,13 @@ internal object CredentialProtectedApplicationLoader : ApplicationLoader {
IDEColorSchemeProvider.init()
}

app.coroutineScope.launch(Dispatchers.IO) {
// ADFA-4930: relocated build output of projects deleted, moved or renamed outside
// the IDE.
val removed = BuildOutputLocation.sweep(app.noBackupFilesDir)
if (removed > 0) logger.info("Swept {} orphaned build output tree(s)", removed)
}

if (!VMUtils.isJvm || VMUtils.isInstrumentedTest) {
ToolsManager.init(app, null)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import com.itsaky.androidide.projects.IProjectManager
import com.itsaky.androidide.projects.api.AndroidModule
import com.itsaky.androidide.projects.builder.BuildService
import com.itsaky.androidide.projects.isPluginProject
import com.itsaky.androidide.projects.models.buildDir
import com.itsaky.androidide.resources.R
import com.itsaky.androidide.services.builder.GradleBuildService
import com.itsaky.androidide.tooling.api.GradlePluginConfig
Expand Down Expand Up @@ -459,28 +460,19 @@ class GradleQuickBuildProvisioner(

// Variant-scoped, matching where the Gradle plugin writes it: one report per
// debuggable variant, so a flavored project has several and only this variant's is
// the built app.
val reportPath = QuickBuildTaskPaths.setupJson(variantName)
val reportFile =
sequenceOf(
File(moduleDir, reportPath),
File(projectRoot, reportPath),
).firstOrNull { it.isFile }
?: run {
log.error(
"{} not found under {} or {} after the proxy app build",
reportPath,
moduleDir,
projectRoot,
)
// The build succeeded but wrote no Quick Build setup, which all but
// names the cause: the plugin only configures DEBUGGABLE variants, and
// the release-name check above only catches AGP's own release build
// type. Say so instead of the generic "setup failed".
return ProxyAppBuildResult.Failed(
context.getString(R.string.quick_build_variant_setup_missing, variantName),
)
}
// the built app. Under the build directory the synced model gives the module, which
// relocated build output (ADFA-4930) moves out of the project folder.
val reportFile = QuickBuildTaskPaths.setupJson(module.buildDir, variantName)
if (!reportFile.isFile) {
log.error("{} not found after the proxy app build", reportFile)
// The build succeeded but wrote no Quick Build setup, which all but names the
// cause: the plugin only configures DEBUGGABLE variants, and the release-name
// check above only catches AGP's own release build type. Say so instead of the
// generic "setup failed".
return ProxyAppBuildResult.Failed(
context.getString(R.string.quick_build_variant_setup_missing, variantName),
)
}

val proxyApp =
ProxyAppInfo.parse(reportFile.readText(), projectRoot)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.itsaky.androidide.quickbuild

import java.io.File

/**
* Composes the Gradle task path for the quick-build proxy app build's `assemble<Variant>` task from
* a module's Gradle project path and the variant CoGo has selected.
Expand Down Expand Up @@ -36,10 +38,16 @@ object QuickBuildTaskPaths {
}

/**
* Where the Gradle plugin writes that variant's proxy app report, relative to the
* directory owning the `build/` dir - the other half of the same contract, kept next to
* the task name so the two cannot drift apart. Variant-scoped like every other Quick
* Build output: a flavored project has one report per debuggable variant.
* Where the Gradle plugin writes that variant's proxy app report - the other half of the same
* contract, kept next to the task name so the two cannot drift apart. Variant-scoped like
* every other Quick Build output: a flavored project has one report per debuggable variant.
*
* @param buildDir the module's build directory as the project model has it; relocated build
* output (ADFA-4930) is not under `<module>/build`.
* @param variantName the variant; blank falls back to [DEFAULT_VARIANT].
*/
fun setupJson(variantName: String = DEFAULT_VARIANT): String = "build/quickbuild/${variantName.ifBlank { DEFAULT_VARIANT }}/setup.json"
fun setupJson(
buildDir: File,
variantName: String = DEFAULT_VARIANT,
): File = File(buildDir, "quickbuild/${variantName.ifBlank { DEFAULT_VARIANT }}/setup.json")
}
Loading
Loading