Skip to content
Open
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
2 changes: 1 addition & 1 deletion ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ Local builds get `documentation.db` from dev-assets instead, which is updated by

> **Persistence policy (authoritative):** new relational/queryable persistence uses **Room** (`@Entity` + DAO + `RoomDatabase` with explicit migrations, provided via Koin). Non-relational settings use the **filesystem/preferences (DataStore)**. **Raw SQLite is the exception, not the default** — see [ADR 0001](docs/adr/0001-prefer-room-for-persistence.md).
>
> **Recent Projects** is the reference example of the default: `app/src/main/java/com/itsaky/androidide/roomData/recentproject/` (`RecentProjectRoomDatabase`, `@Database version = 4` with migrations 1→4; `RecentProjectDao`; the `RecentProject` `@Entity` → table `recent_project_table`). It's provided via Koin in `di/AppModule.kt` and consumed by `RecentProjectsViewModel`, `ProjectInfoBottomSheet`, and `ProjectCreationManager` directly, and by `MainActivity`/`EditorHandlerActivity` indirectly through `RecentProjectRepository` (`repositories/RecentProjectRepository.kt`) -- kept behind that interface, rather than injecting the DAO into those two Activities directly, per this section's own UI -> ViewModel -> Repository -> data source layering.
> **Recent Projects** is the reference example of the default: `app/src/main/java/com/itsaky/androidide/roomData/recentproject/` (`RecentProjectRoomDatabase`, `@Database version = 6` with migrations 1→6; the `DebuggerEndpoint` `@Entity` → table `debugger_endpoint_table` pairs an app with its project through a foreign key to `recent_project_table.location`; `RecentProjectDao`; the `RecentProject` `@Entity` → table `recent_project_table`). It's provided via Koin in `di/AppModule.kt` and consumed by `RecentProjectsViewModel`, `ProjectInfoBottomSheet`, and `ProjectCreationManager` directly, and by `MainActivity`/`EditorHandlerActivity` indirectly through `RecentProjectRepository` (`repositories/RecentProjectRepository.kt`) -- kept behind that interface, rather than injecting the DAO into those two Activities directly, per this section's own UI -> ViewModel -> Repository -> data source layering.
>
> **Raw SQLite is allowed only when** the database is prebuilt and opened read-only, the data is performance/allocation-critical and needs granular schema control, or the schema is shared across a process/component boundary. Current exceptions: symbol indexing (`lsp/indexing/SQLiteIndex.kt`), tooltips (`idetooltips/ToolTipManager.kt`), in-app/plugin help (`plugin-manager/.../documentation/PluginDocumentationManager.kt` — the one *writer*, inserting plugin-contributed rows into a schema owned elsewhere), the shared compression-dictionary loader (`common/.../utils/DocumentationCompression.kt`), and documentation serving (`common/.../documentation/DocumentationContentSource.kt`, the one read pipeline behind both the in-process WebView transport and `app/.../localWebServer/WebServer.kt`). The `androidx.room:*` strings in `editor`'s `GroovyAutoComplete` are autocomplete suggestions for the *user's* code, not CoGo persistence.
>
Expand Down
12 changes: 12 additions & 0 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -360,6 +360,18 @@
</intent-filter>
</receiver>

<!-- The SQLite debugger library in an app built here reports its token and port. The sender
is another app, so it is exported; the receiver ignores apps it has no pairing row for. -->
<receiver
android:name=".sqlitedebugger.DebuggerEndpointReceiver"
android:enabled="true"
android:exported="true"
tools:ignore="ExportedReceiver">
<intent-filter>
<action android:name="com.itsaky.androidide.SQLITE_DEBUGGER_ENDPOINT" />
</intent-filter>
</receiver>

<!--
Receiver used to receive broadcasts when foreground application changes
This receiver *must* have permissions that are not usually granted to
Expand Down
137 changes: 76 additions & 61 deletions app/src/main/java/com/itsaky/androidide/actions/etc/LaunchAppAction.kt
Original file line number Diff line number Diff line change
Expand Up @@ -27,77 +27,92 @@ import com.itsaky.androidide.actions.markInvisible
import com.itsaky.androidide.actions.openApplicationModuleChooser
import com.itsaky.androidide.idetooltips.TooltipTag.EDITOR_TOOLBAR_LAUNCH_APP
import com.itsaky.androidide.projects.IProjectManager
import com.itsaky.androidide.repositories.DebuggerEndpointRepository
import com.itsaky.androidide.utils.IntentUtils
import com.itsaky.androidide.utils.flashError
import kotlinx.coroutines.launch
import org.koin.core.context.GlobalContext
import org.slf4j.LoggerFactory
import java.io.File

/**
* An action to launch the already installed application on the device.
*
* @author Akash Yadav
*/
class LaunchAppAction(context: Context, override val order: Int) : EditorActivityAction() {

override val id: String = "ide.editor.launchInstalledApp"
override var requiresUIThread: Boolean = true
override fun retrieveTooltipTag(isReadOnlyContext: Boolean) = EDITOR_TOOLBAR_LAUNCH_APP

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

companion object {
private val log = LoggerFactory.getLogger(LaunchAppAction::class.java)
}

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

visible = true

val projectManager = IProjectManager.getInstance()
enabled = projectManager.getAndroidAppModules().isNotEmpty()
}

override suspend fun execAction(data: ActionData) {
openApplicationModuleChooser(data) { app ->
val variant = app.getSelectedVariant()

log.debug("Selected variant: {}", variant?.name)

if (variant == null) {
flashError(R.string.err_selected_variant_not_found)
return@openApplicationModuleChooser
}

val applicationId = variant.mainArtifact.applicationId
if (applicationId == null) {
log.error("Unable to launch application. variant.mainArtifact.applicationId is null")
flashError(R.string.err_cannot_determine_package)
return@openApplicationModuleChooser
}

log.info("Launching application: {}", applicationId)

val activity = data.requireActivity()
activity.activityScope.launch {
IntentUtils.launchApp(
class LaunchAppAction(
context: Context,
override val order: Int,
) : EditorActivityAction() {
override val id: String = "ide.editor.launchInstalledApp"
override var requiresUIThread: Boolean = true

override fun retrieveTooltipTag(isReadOnlyContext: Boolean) = EDITOR_TOOLBAR_LAUNCH_APP

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

companion object {
private val log = LoggerFactory.getLogger(LaunchAppAction::class.java)
}

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

visible = true

val projectManager = IProjectManager.getInstance()
enabled = projectManager.getAndroidAppModules().isNotEmpty()
}

override suspend fun execAction(data: ActionData) {
openApplicationModuleChooser(data) { app ->
val variant = app.getSelectedVariant()

log.debug("Selected variant: {}", variant?.name)

if (variant == null) {
flashError(R.string.err_selected_variant_not_found)
return@openApplicationModuleChooser
}

val applicationId = variant.mainArtifact.applicationId
if (applicationId == null) {
log.error("Unable to launch application. variant.mainArtifact.applicationId is null")
flashError(R.string.err_cannot_determine_package)
return@openApplicationModuleChooser
}

log.info("Launching application: {}", applicationId)

val projectDirPath = IProjectManager.getInstance().projectDirPath

val activity = data.requireActivity()
activity.activityScope.launch {
// Awaited so the app's first report cannot arrive before its row exists.
if (projectDirPath.isNotBlank()) {
GlobalContext
.get()
.get<DebuggerEndpointRepository>()
.recordLaunched(applicationId, File(projectDirPath))
}
IntentUtils.launchApp(
context = activity,
packageName = applicationId,
logError = false
logError = false,
)
}
}
}

override fun getShowAsActionFlags(data: ActionData): Int {
// prefer showing this in the overflow menu
return MenuItem.SHOW_AS_ACTION_IF_ROOM
}
}
}
}
}

override fun getShowAsActionFlags(data: ActionData): Int {
// prefer showing this in the overflow menu
return MenuItem.SHOW_AS_ACTION_IF_ROOM
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ package com.itsaky.androidide.activities.editor
import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.content.pm.PackageInstaller
import android.content.res.Configuration
import android.graphics.Color
import android.graphics.Rect
Expand Down Expand Up @@ -755,7 +756,33 @@ abstract class BaseEditorActivity :
return
}

val packageName = onResult(this, intent) ?: return
val packageName = onResult(this, intent)
if (packageName == null) {
val extras = intent.extras
val installed = extras?.getString(PackageInstaller.EXTRA_PACKAGE_NAME)
if (installed != null && extras.getInt(PackageInstaller.EXTRA_STATUS) != PackageInstaller.STATUS_PENDING_USER_ACTION) {
onInstallEndedWithoutLaunch(installed)
}
return
}
// Runs before the launch so the app's first report finds its pairing row.
activityScope.launch(Dispatchers.Main.immediate) {
beforePostInstallLaunch(packageName)
launchAfterInstall(event, packageName)
}
}

/** Called on the main thread when an install of [packageName] ended and no post-install launch follows (failed, cancelled, or suppressed). */
protected open fun onInstallEndedWithoutLaunch(packageName: String) {}

/** Called on the main thread after an install succeeded, before the app is launched. Must not throw. */
protected open suspend fun beforePostInstallLaunch(packageName: String) {}

private fun launchAfterInstall(
event: InstallationEvent.InstallationResultEvent,
packageName: String,
) {
if (isDestroying) return
val isDebugging = event.intent.getBooleanExtra(DebugAction.ID, false)
if (!isDebugging) {
doLaunchApp(packageName)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
package com.itsaky.androidide.activities.editor

import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.system.ErrnoException
import android.system.OsConstants
Expand Down Expand Up @@ -93,6 +94,7 @@ import com.itsaky.androidide.quickbuild.QuickBuildStatusTracker
import com.itsaky.androidide.quickbuild.QuickBuildWontStayUpRestart
import com.itsaky.androidide.quickbuild.quickBuildStatusBarUpdate
import com.itsaky.androidide.quickbuild.resolve
import com.itsaky.androidide.repositories.DebuggerEndpointRepository
import com.itsaky.androidide.repositories.PluginRepository
import com.itsaky.androidide.resources.R.string
import com.itsaky.androidide.search.replace.ReplaceCoordinator
Expand Down Expand Up @@ -183,6 +185,7 @@ abstract class ProjectHandlerActivity :
ReplaceHost {
protected val buildVariantsViewModel by viewModels<BuildVariantsViewModel>()
private val pluginRepository: PluginRepository by inject()
private val debuggerEndpointRepository: DebuggerEndpointRepository by inject()

protected var mSearchingProgress: ProgressSheet? = null
protected var mFindInProjectDialog: AlertDialog? = null
Expand Down Expand Up @@ -719,13 +722,35 @@ abstract class ProjectHandlerActivity :
*
* @param apk the built APK; parsed with the package manager, so it must exist on disk.
*/
private fun apkApplicationId(apk: File): String? =
private fun apkApplicationId(apk: File): String? = apkApplicationId(packageManager, apk)

private fun apkApplicationId(
packageManager: PackageManager,
apk: File,
): String? =
runCatching { packageManager.getPackageArchiveInfo(apk.absolutePath, 0)?.packageName }
.onFailure { logger.warn("Could not read the applicationId of {}", apk, it) }
.getOrNull()
?.takeIf { it.isNotBlank() }

override suspend fun beforePostInstallLaunch(packageName: String) {
debuggerEndpointRepository.confirmInstall(packageName)
}

override fun onInstallEndedWithoutLaunch(packageName: String) {
debuggerEndpointRepository.discardPendingInstall(packageName)
}

private fun doInstallApk(state: BuildState.AwaitingInstall) {
val projectDirPath = IProjectManager.getInstance().projectDirPath
if (projectDirPath.isNotBlank()) {
val apk = state.apkFile
// The lambda outlives this Activity in the application scope. The pairing itself is written
// by beforePostInstallLaunch, once the install has succeeded.
val packageManager = applicationContext.packageManager
debuggerEndpointRepository.expectInstallAsync(File(projectDirPath)) { apkApplicationId(packageManager, apk) }
}

apkInstallationViewModel.installApk(
context = this,
apk = state.apkFile,
Expand Down
9 changes: 9 additions & 0 deletions app/src/main/java/com/itsaky/androidide/di/AppModule.kt
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import com.itsaky.androidide.deeplink.PendingDeepLinkOpen
import com.itsaky.androidide.editor.language.outline.OutlineProvider
import com.itsaky.androidide.editor.language.outline.TreeSitterOutlineProvider
import com.itsaky.androidide.git.core.GitCredentialsManager
import com.itsaky.androidide.repositories.DebuggerEndpointRepository
import com.itsaky.androidide.repositories.RecentProjectRepository
import com.itsaky.androidide.repositories.RecentProjectRepositoryImpl
import com.itsaky.androidide.roomData.recentproject.RecentProjectRoomDatabase
Expand Down Expand Up @@ -57,6 +58,14 @@ val coreModule =
get<RecentProjectRoomDatabase>().recentProjectDao()
}

single {
get<RecentProjectRoomDatabase>().debuggerEndpointDao()
}

single {
DebuggerEndpointRepository(get(), get(named(APPLICATION_SCOPE)))
}

single<RecentProjectRepository> {
RecentProjectRepositoryImpl(get())
}
Expand Down
Loading
Loading