diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 7c0b4a0857..c2672d0adb 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -65,7 +65,7 @@ The optional file path is attacker-controllable (a URL segment), so it's resolve Whether the open project *can* be named at all is `isDeepLinkTargetOfOpenProject` (`ProjectValidations.kt`): a link can only ever resolve to `/`, but a project can be opened from anywhere. Its `deepLinkTargetOfOpenProjectWithoutIo` half exists so a caller on the main thread can settle the common case — equal path strings name the same directory — without the `canonicalPath` calls the full rule needs. `CreateLinkAction` sends its residue to `Dispatchers.IO` rather than to the StrictMode whitelist (ADR 0007); the two older callers (`EditorHandlerActivity.onNewIntent`, `BaseEditorActivity.onCreate`) still fall through to `canonicalPath` on the main thread and have not been migrated, so the shortcut narrows that exposure rather than removing it. -**Project session lifecycle: language servers stop before the project is destroyed, and only when the editor finishes.** Closing a project runs one teardown from `ProjectHandlerActivity.onPause` while the activity finishes (`ProjectSessionCloser`, with a `preDestroy` fallback for a `finish()` that arrives while already paused). Its order is the contract: (1) every language server's `shutdown()`, which must not block; (2) `ProjectManagerImpl.destroy()`, which ends the `IndexingServiceManager`'s session lifetime at once and closes its services and `IndexRegistry` in the background; (3) the Quick Build session restart. The next project's manager waits for that background close before it reopens the index databases, which are global files. Work the old session still has in flight may touch its closed indexes: reads return empty results, and `SQLiteIndex` logs that at DEBUG because the lifetime has ended (use after close in a live session stays ERROR, since it is a real bug). A closed registry refuses new indexes with `IndexRegistryClosedException`, which the Kotlin server's `CompilerSession` treats as the end of an update, not a failure. Each Kotlin project update binds one manager, under the same lock as its shutdown check, so a closing session never reads or writes the next session's indexes. A configuration change (rotation, font scale, dark mode) never runs the teardown: `isFinishing` is false, and servers and indexes survive the recreation. Other readers of the global `ProjectManagerImpl.indexingServiceManager` (the project setup, `GradleBuildService`, the Java and XML class lookups) are not bound to a session yet; a manager that sees a sync before any service registers retries setup on the next sync instead of staying empty. +**Project session lifecycle: language servers stop before the project is destroyed, and only when the editor finishes.** Closing a project runs one teardown from `ProjectHandlerActivity.onPause` while the activity finishes (`ProjectSessionCloser`, with a `preDestroy` fallback for a `finish()` that arrives while already paused). It first reports the close to plugins (`PluginWorkspaceEvents.projectClosed`, which only queues `onProjectClosed` on the plugins' own thread), but only for the directory this editor reported open, kept in `EditorViewModel`. This path, and the open and save reports beside it, call the plugin manager directly rather than through EventBus: no event marks a project open or close, and `DocumentSaveEvent` is also posted on every Enter, with nothing written. After that, its order is the contract: (1) every language server's `shutdown()`, which must not block; (2) `ProjectManagerImpl.destroy()`, which ends the `IndexingServiceManager`'s session lifetime at once and closes its services and `IndexRegistry` in the background; (3) the Quick Build session restart. The next project's manager waits for that background close before it reopens the index databases, which are global files. Work the old session still has in flight may touch its closed indexes: reads return empty results, and `SQLiteIndex` logs that at DEBUG because the lifetime has ended (use after close in a live session stays ERROR, since it is a real bug). A closed registry refuses new indexes with `IndexRegistryClosedException`, which the Kotlin server's `CompilerSession` treats as the end of an update, not a failure. Each Kotlin project update binds one manager, under the same lock as its shutdown check, so a closing session never reads or writes the next session's indexes. A configuration change (rotation, font scale, dark mode) never runs the teardown: `isFinishing` is false, and servers and indexes survive the recreation. Other readers of the global `ProjectManagerImpl.indexingServiceManager` (the project setup, `GradleBuildService`, the Java and XML class lookups) are not bound to a session yet; a manager that sees a sync before any service registers retries setup on the next sync instead of staying empty. **Gradle build output lives in app storage, not the project folder (ADFA-4930).** Projects sit on shared storage (`/sdcard`), which Android serves through FUSE, so every file a build writes pays a user-space round trip. Each project's build output goes to `noBackupFilesDir/gradle-build//` (`services/builder/BuildOutputLocation`), keyed like Quick Build's scratch (`ProjectStorageKey` in `:shared`): - `main/-/` per Gradle project (`` of its full path, so `:core:ui` is not inside `:core`'s output); nested builds get their own key. The init script plugin sets `layout.buildDirectory` from `-Pcotg.build.outputDir` (`gradle-plugin/.../BuildOutputRedirect`). diff --git a/app/src/main/java/com/itsaky/androidide/actions/file/InstallFileAction.kt b/app/src/main/java/com/itsaky/androidide/actions/file/InstallFileAction.kt index 18cf2c188e..fa58d3effd 100644 --- a/app/src/main/java/com/itsaky/androidide/actions/file/InstallFileAction.kt +++ b/app/src/main/java/com/itsaky/androidide/actions/file/InstallFileAction.kt @@ -26,6 +26,7 @@ import com.itsaky.androidide.actions.markInvisible import com.itsaky.androidide.activities.ExternalFileInstallActivity import com.itsaky.androidide.activities.editor.EditorHandlerActivity import com.itsaky.androidide.repositories.PluginRepository +import com.itsaky.androidide.repositories.PluginStillLoadedException import com.itsaky.androidide.resources.R import com.itsaky.androidide.utils.DialogUtils import com.itsaky.androidide.utils.fileProviderUriFor @@ -108,7 +109,13 @@ class InstallFileAction( flashSuccess(getString(R.string.msg_plugin_installed_restart)) DialogUtils.showRestartPrompt(this@doAction) }.onFailure { e -> - flashError(getString(R.string.msg_plugin_install_failed, e.message)) + flashError( + if (e is PluginStillLoadedException) { + getString(R.string.msg_plugin_install_still_loaded, e.pluginId) + } else { + getString(R.string.msg_plugin_install_failed, e.message) + }, + ) } } } diff --git a/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt b/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt index 126b52f792..9e6b1c30ea 100644 --- a/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt +++ b/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt @@ -74,6 +74,7 @@ import com.itsaky.androidide.plugins.extensions.ProjectSearchExtension import com.itsaky.androidide.plugins.extensions.ProjectSearchRequest import com.itsaky.androidide.plugins.extensions.ProjectSearchResult import com.itsaky.androidide.plugins.extensions.ProjectSearchSection +import com.itsaky.androidide.plugins.manager.services.PluginWorkspaceEvents import com.itsaky.androidide.projects.IProjectManager import com.itsaky.androidide.projects.ProjectManagerImpl import com.itsaky.androidide.projects.builder.BuildService @@ -94,6 +95,7 @@ import com.itsaky.androidide.quickbuild.QuickBuildWontStayUpRestart import com.itsaky.androidide.quickbuild.quickBuildStatusBarUpdate import com.itsaky.androidide.quickbuild.resolve import com.itsaky.androidide.repositories.PluginRepository +import com.itsaky.androidide.repositories.PluginStillLoadedException import com.itsaky.androidide.resources.R.string import com.itsaky.androidide.search.replace.ReplaceCoordinator import com.itsaky.androidide.search.replace.ReplaceHost @@ -282,6 +284,9 @@ abstract class ProjectHandlerActivity : const val STATE_KEY_SHOULD_INITIALIZE = "ide.editor.isInitializing" private const val PLUGIN_SEARCH_TIMEOUT_SECONDS = 10L + + // Pairs each editor's plugin open report with its close; see initializeProject. + private val pluginProjectLock = Any() } abstract fun doCloseAll() @@ -1156,10 +1161,14 @@ abstract class ProjectHandlerActivity : showRestartPrompt(this@ProjectHandlerActivity) }.onFailure { error -> flashError( - getString( - string.msg_plugin_install_failed, - error.message ?: "Unknown error", - ), + if (error is PluginStillLoadedException) { + getString(string.msg_plugin_install_still_loaded, error.pluginId) + } else { + getString( + string.msg_plugin_install_failed, + error.message ?: "Unknown error", + ) + }, ) } setStatus("") @@ -1191,6 +1200,15 @@ abstract class ProjectHandlerActivity : } private fun closeProjectSession() { + // Only the live editor's teardown reports the close; a doomed instance (onPause) does not. + synchronized(pluginProjectLock) { + editorViewModel.pluginOpenedProjectDir?.let { dir -> + // Reporting to plugins must never stop the editor's teardown. + runCatching { PluginWorkspaceEvents.getInstance().projectClosed(dir) } + .onFailure { logger.error("Failed to report a project close to plugins", it) } + } + editorViewModel.pluginOpenedProjectDir = null + } stopLanguageServers() closeProjectState() } @@ -1591,6 +1609,19 @@ abstract class ProjectHandlerActivity : handleMissingProjectDirectory(projectDir) return@launch } + // As the editor starts opening the project; the sync below does not wait for listeners. + // A re-sync of the same project is not reported again. Not from an editor already tearing + // down: a late initialize after its close was reported would reopen a closed project. + // Under the lock the close takes: this runs on Dispatchers.Default and can race onPause's + // teardown, which would otherwise read no open project between the report and the record. + synchronized(pluginProjectLock) { + if (!isDestroying && !isFinishing) { + // The directory as plugins heard it, so the close compares it without touching the disk. + runCatching { PluginWorkspaceEvents.getInstance().projectOpened(projectDir) } + .onSuccess { editorViewModel.pluginOpenedProjectDir = it } + .onFailure { logger.error("Failed to report a project open to plugins", it) } + } + } val needsSync = try { diff --git a/app/src/main/java/com/itsaky/androidide/repositories/PluginRepositoryImpl.kt b/app/src/main/java/com/itsaky/androidide/repositories/PluginRepositoryImpl.kt index 8c3c29860e..0454c8af85 100644 --- a/app/src/main/java/com/itsaky/androidide/repositories/PluginRepositoryImpl.kt +++ b/app/src/main/java/com/itsaky/androidide/repositories/PluginRepositoryImpl.kt @@ -71,8 +71,8 @@ class PluginRepositoryImpl( ?: throw IllegalStateException("Plugin system not available") Log.d(TAG, "Uninstalling plugin: $pluginId") - val result = manager.uninstallPlugin(pluginId) - result + // A load already under way could otherwise load the plugin again after it was removed. + manager.whileNotLoading { manager.uninstallPlugin(pluginId) } }.onFailure { exception -> Log.e(TAG, "Failed to uninstall plugin: $pluginId", exception) } @@ -135,13 +135,6 @@ class PluginRepositoryImpl( } } - try { - manager.uninstallPlugin(pluginId) - Log.d(TAG, "Uninstalled existing version of plugin: $pluginId") - } catch (e: Exception) { - Log.w(TAG, "Error uninstalling existing plugin: ${e.message}") - } - val fileExtension = if (pluginFile.name.endsWith(".$PLUGIN_ARCHIVE_EXTENSION", ignoreCase = true)) ".$PLUGIN_ARCHIVE_EXTENSION" else ".apk" val finalFileName = "${pluginId}$fileExtension" @@ -152,13 +145,25 @@ class PluginRepositoryImpl( val finalFile = File(pluginsDir, finalFileName) - try { - pluginFile.copyTo(finalFile, overwrite = true) - Log.d(TAG, "Plugin file copied to: ${finalFile.absolutePath}") - pluginFile.delete() - } catch (e: Exception) { - Log.e(TAG, "Failed to copy plugin file to plugins directory", e) - throw e + // No load may run between the unload and the copy: it could load the old file again. + manager.whileNotLoading { + try { + manager.uninstallPlugin(pluginId) + Log.d(TAG, "Uninstalled existing version of plugin: $pluginId") + } catch (e: Exception) { + Log.w(TAG, "Error uninstalling existing plugin: ${e.message}") + } + // loadPlugins() keeps a plugin that is still loaded, so the new file would never load. + if (manager.getPlugin(pluginId) != null) throw PluginStillLoadedException(pluginId) + + try { + pluginFile.copyTo(finalFile, overwrite = true) + Log.d(TAG, "Plugin file copied to: ${finalFile.absolutePath}") + pluginFile.delete() + } catch (e: Exception) { + Log.e(TAG, "Failed to copy plugin file to plugins directory", e) + throw e + } } manager.loadPlugins() diff --git a/app/src/main/java/com/itsaky/androidide/repositories/PluginStillLoadedException.kt b/app/src/main/java/com/itsaky/androidide/repositories/PluginStillLoadedException.kt new file mode 100644 index 0000000000..ce8e3867a0 --- /dev/null +++ b/app/src/main/java/com/itsaky/androidide/repositories/PluginStillLoadedException.kt @@ -0,0 +1,10 @@ +package com.itsaky.androidide.repositories + +/** + * Installing [pluginId] found its installed version still loaded after uninstalling it, so the new + * file was not put in place: loading skips a plugin that is already loaded. Shown to the user as + * `msg_plugin_install_still_loaded`. + */ +class PluginStillLoadedException( + val pluginId: String, +) : IllegalStateException("The installed version of $pluginId could not be unloaded") diff --git a/app/src/main/java/com/itsaky/androidide/ui/CodeEditorView.kt b/app/src/main/java/com/itsaky/androidide/ui/CodeEditorView.kt index 895b49e983..a94bdfde54 100644 --- a/app/src/main/java/com/itsaky/androidide/ui/CodeEditorView.kt +++ b/app/src/main/java/com/itsaky/androidide/ui/CodeEditorView.kt @@ -56,6 +56,7 @@ import com.itsaky.androidide.lsp.java.JavaLanguageServer import com.itsaky.androidide.lsp.kotlin.KotlinLanguageServer import com.itsaky.androidide.lsp.xml.XMLLanguageServer import com.itsaky.androidide.models.Range +import com.itsaky.androidide.plugins.manager.services.PluginWorkspaceEvents import com.itsaky.androidide.preferences.internal.EditorPreferences import com.itsaky.androidide.syntax.colorschemes.SchemeAndroidIDE import com.itsaky.androidide.tasks.cancelIfActive @@ -415,8 +416,17 @@ class CodeEditorView( _binding?.rwProgress?.isVisible = false } - markUnmodified() - notifySaved() + try { + markUnmodified() + notifySaved() + } finally { + // Here, not from DocumentSaveEvent: the editor also posts that on every Enter, with nothing + // written. After markUnmodified(), so a listener asking whether the file is modified hears + // no; in finally, because that throws once the tab is closed mid-save, though the file is + // written. A failure here must not fail the save. + runCatching { PluginWorkspaceEvents.getInstance().fileSaved(file) } + .onFailure { log.error("Failed to report a save to plugins", it) } + } return true } diff --git a/app/src/main/java/com/itsaky/androidide/viewmodel/EditorViewModel.kt b/app/src/main/java/com/itsaky/androidide/viewmodel/EditorViewModel.kt index e8d602b5a4..7cd5826ad9 100644 --- a/app/src/main/java/com/itsaky/androidide/viewmodel/EditorViewModel.kt +++ b/app/src/main/java/com/itsaky/androidide/viewmodel/EditorViewModel.kt @@ -272,6 +272,15 @@ class EditorViewModel : ViewModel() { _isInternalBuildInProgress.value = value } + /** + * The project directory this editor last reported open to plugins, as + * `PluginWorkspaceEvents.projectOpened` returned it (canonical). Held here rather than on the + * activity so a recreated editor closes the project its predecessor opened, and rather than read + * from the global project path, which a pending project switch may already have changed. + */ + @Volatile + var pluginOpenedProjectDir: File? = null + var isInitializing: Boolean get() = _isInitializing.value ?: false set(value) { diff --git a/app/src/main/java/com/itsaky/androidide/viewmodels/PluginManagerViewModel.kt b/app/src/main/java/com/itsaky/androidide/viewmodels/PluginManagerViewModel.kt index 17c945ecf3..3e02e104b0 100644 --- a/app/src/main/java/com/itsaky/androidide/viewmodels/PluginManagerViewModel.kt +++ b/app/src/main/java/com/itsaky/androidide/viewmodels/PluginManagerViewModel.kt @@ -8,6 +8,7 @@ import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.itsaky.androidide.plugins.PluginInfo import com.itsaky.androidide.repositories.PluginRepository +import com.itsaky.androidide.repositories.PluginStillLoadedException import com.itsaky.androidide.resources.R import com.itsaky.androidide.ui.models.PluginInstallSource import com.itsaky.androidide.ui.models.PluginManagerUiEffect @@ -421,10 +422,14 @@ class PluginManagerViewModel( }.onFailure { exception -> Log.e(TAG, "Failed to install plugin", exception) _uiEffect.send( - PluginManagerUiEffect.ShowError( - R.string.msg_plugin_install_failed, - listOf(exception.message ?: ""), - ), + if (exception is PluginStillLoadedException) { + PluginManagerUiEffect.ShowError(R.string.msg_plugin_install_still_loaded, listOf(exception.pluginId)) + } else { + PluginManagerUiEffect.ShowError( + R.string.msg_plugin_install_failed, + listOf(exception.message ?: ""), + ) + }, ) // A failed install deletes nothing but our own disposable temp copy - a // user-picked PickedUri is preserved so they can retry, matching diff --git a/docs/PLUGIN_API_CHANGELOG.md b/docs/PLUGIN_API_CHANGELOG.md index d37c7f42c7..ff2281e5bb 100644 --- a/docs/PLUGIN_API_CHANGELOG.md +++ b/docs/PLUGIN_API_CHANGELOG.md @@ -35,6 +35,19 @@ need a source change, a recompile, or both · `tooling` = API-stability milestone. **[verified]** = read from the checked-in ABI dump. **[reconstructed]** = diffed from `plugin-api/src` history (predates the dump; symbol-accurate). +### 26.47 — unreleased +- **added — Hear the editor open and close a project, and save a file** _(ADFA-3570)_ **[verified]** + `IdeProjectService.addProjectLifecycleListener(ProjectLifecycleListener)` calls + `onProjectOpened(projectDir)` when the editor starts opening a project (its sync does not wait + for listeners), and + `onProjectClosed(projectDir)` when it closes one; a re-sync is not another open, and switching + projects reports the close first. `IdeEditorService.addFileSaveListener(FileSaveListener)` calls + `onFileSaved(file)` after each file the editor writes, whoever asked for the save. Both need + `filesystem.read`. Calls arrive in order on one background thread shared by every plugin, so + return quickly. The IDE drops the listeners when the plugin is disabled or unloads, so register + them from `activate()`. A listener added while a project is open hears `onProjectOpened` for it + first. Paths are canonical. Floor `plugin.min_ide_version` at `26.47` to use them. + ### 26.43 — unreleased - **tooling — Interface bodies are Java default methods again** _(ADFA-6560)_ **[verified]** Since ADFA-4058 (May 2026) pinned `languageVersion`, `plugin-api` compiled each Kotlin interface diff --git a/docs/PLUGIN_AUTHORING.md b/docs/PLUGIN_AUTHORING.md index eff39136fe..b1cb92dac7 100644 --- a/docs/PLUGIN_AUTHORING.md +++ b/docs/PLUGIN_AUTHORING.md @@ -385,6 +385,7 @@ Code on the Go cannot load Android Studio or IntelliJ plugins ([ADR 0018](adr/00 | Highlighting layered over a language (e.g. rainbow brackets) | `EditorDecorationProvider`, which adds foreground colours only | | `searchEverywhereContributor` | `ProjectSearchExtension`, which appends sections to Search Results | | `runConfigurationType`, external tools | `BuildActionExtension` returning `PluginBuildAction`s that run a `CommandSpec` | +| `projectListeners` for project open and close, `FileDocumentManagerListener` for saves | `IdeProjectService.addProjectLifecycleListener` and `IdeEditorService.addFileSaveListener`. A save is reported after the file is written, so there is no `beforeDocumentSaving` | | Project or module wizard | A `.cgt` template, built with `IdeTemplateService.createTemplateBuilder` and added with `registerTemplate` | | `applicationService` / `projectService` | Objects your plugin owns. Offer one to other plugins with `PluginContext.registerService`; reach IDE services with `PluginContext.services.get(...)` | @@ -392,7 +393,7 @@ No equivalent yet: - **Editor context-menu actions.** `UIExtension.getContextMenuItems()` exists, but the IDE does not call it. - **Quick fixes, intention actions and hover documentation.** The language-server bridge does not request code actions or hover. -- **Message-bus listeners** (`applicationListeners`, `projectListeners`). `PluginContext.eventBus` is the IDE's EventBus, typed `Any`; its events are not part of the [plugin API contract](plugin-api.md), so a subscriber can break on any release. +- **Other message-bus listeners** (`applicationListeners`, and `projectListeners` beyond project open, close and file save). `PluginContext.eventBus` is the IDE's EventBus, typed `Any`; its events are not part of the [plugin API contract](plugin-api.md), so a subscriber can break on any release. - **Anything that depends on the Android plugin** bundled with Android Studio (`org.jetbrains.android`). ## Porting a VS Code extension @@ -411,6 +412,7 @@ Code on the Go does not host VS Code's extension API ([ADR 0019](adr/0019-vscode | `window.createWebviewPanel` | A `Fragment` hosting an Android `WebView`, shown as an `EditorTabExtension` tab - `markdown-preview-plugin` does this | | `contributes.configuration` | `SettingsExtension`, storing values with `PluginContext.getPluginSharedPreferences` | | `contributes.taskDefinitions` | `BuildActionExtension` returning `PluginBuildAction`s that run a `CommandSpec` | +| `workspace.onDidSaveTextDocument` | `IdeEditorService.addFileSaveListener` | No equivalent yet: @@ -418,7 +420,7 @@ No equivalent yet: - **Debuggers** (`contributes.debuggers`). The IDE's debugger does not speak the Debug Adapter Protocol. - **Explorer and editor context menus** (`menus["explorer/context"]`, `menus["editor/context"]`). `UIExtension.getContextMenuItems()` exists, but the IDE does not call it. - **In-process language providers** (`languages.registerCompletionItemProvider` and the like). Put the logic in a language server instead. -- **Workspace events** (`workspace.onDidSaveTextDocument` and the like). As for Android Studio's message-bus listeners, `PluginContext.eventBus` is not part of the plugin API contract. +- **Other workspace events** (`workspace.onDidCreateFiles`, `onDidRenameFiles` and the like). As for Android Studio's message-bus listeners, `PluginContext.eventBus` is not part of the plugin API contract. ## Troubleshooting diff --git a/plugin-api/api/plugin-api.api b/plugin-api/api/plugin-api.api index df35e7d108..412049157e 100644 --- a/plugin-api/api/plugin-api.api +++ b/plugin-api/api/plugin-api.api @@ -1686,6 +1686,10 @@ public abstract interface class com/itsaky/androidide/plugins/services/FileChang public abstract fun onFileChanged (Ljava/io/File;)V } +public abstract interface class com/itsaky/androidide/plugins/services/FileSaveListener { + public abstract fun onFileSaved (Ljava/io/File;)V +} + public abstract interface class com/itsaky/androidide/plugins/services/GradleSyncCallback { public abstract fun onComplete (ZLjava/lang/String;)V } @@ -1806,6 +1810,7 @@ public final class com/itsaky/androidide/plugins/services/IdeCommandService$Defa public abstract interface class com/itsaky/androidide/plugins/services/IdeEditorService { public fun addContentChangeListener (Lcom/itsaky/androidide/plugins/services/EditorContentChangeListener;)V public abstract fun addFileChangeListener (Lcom/itsaky/androidide/plugins/services/FileChangeListener;)V + public fun addFileSaveListener (Lcom/itsaky/androidide/plugins/services/FileSaveListener;)V public abstract fun appendToLine (Ljava/io/File;ILjava/lang/String;)Z public fun clearPeerCursors (Ljava/io/File;)V public abstract fun deleteLine (Ljava/io/File;I)Z @@ -1834,6 +1839,7 @@ public abstract interface class com/itsaky/androidide/plugins/services/IdeEditor public abstract fun prependToLine (Ljava/io/File;ILjava/lang/String;)Z public fun removeContentChangeListener (Lcom/itsaky/androidide/plugins/services/EditorContentChangeListener;)V public abstract fun removeFileChangeListener (Lcom/itsaky/androidide/plugins/services/FileChangeListener;)V + public fun removeFileSaveListener (Lcom/itsaky/androidide/plugins/services/FileSaveListener;)V public abstract fun replaceLine (Ljava/io/File;ILjava/lang/String;)Z public abstract fun replaceRange (Ljava/io/File;Lcom/itsaky/androidide/plugins/services/SelectionRange;Ljava/lang/String;)Z public abstract fun replaceSelection (Ljava/lang/String;)Z @@ -1845,10 +1851,12 @@ public abstract interface class com/itsaky/androidide/plugins/services/IdeEditor public final class com/itsaky/androidide/plugins/services/IdeEditorService$DefaultImpls { public static fun addContentChangeListener (Lcom/itsaky/androidide/plugins/services/IdeEditorService;Lcom/itsaky/androidide/plugins/services/EditorContentChangeListener;)V + public static fun addFileSaveListener (Lcom/itsaky/androidide/plugins/services/IdeEditorService;Lcom/itsaky/androidide/plugins/services/FileSaveListener;)V public static fun clearPeerCursors (Lcom/itsaky/androidide/plugins/services/IdeEditorService;Ljava/io/File;)V public static fun dismissInlineSuggestion (Lcom/itsaky/androidide/plugins/services/IdeEditorService;)V public static fun hidePeerCursor (Lcom/itsaky/androidide/plugins/services/IdeEditorService;Ljava/io/File;Ljava/lang/String;)Z public static fun removeContentChangeListener (Lcom/itsaky/androidide/plugins/services/IdeEditorService;Lcom/itsaky/androidide/plugins/services/EditorContentChangeListener;)V + public static fun removeFileSaveListener (Lcom/itsaky/androidide/plugins/services/IdeEditorService;Lcom/itsaky/androidide/plugins/services/FileSaveListener;)V public static fun saveFile (Lcom/itsaky/androidide/plugins/services/IdeEditorService;Ljava/io/File;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; public static fun showInlineSuggestion (Lcom/itsaky/androidide/plugins/services/IdeEditorService;Ljava/lang/String;)V public static fun showPeerCursor (Lcom/itsaky/androidide/plugins/services/IdeEditorService;Ljava/io/File;IILjava/lang/String;Ljava/lang/String;I)Z @@ -1907,16 +1915,20 @@ public final class com/itsaky/androidide/plugins/services/IdeProjectManipulation } public abstract interface class com/itsaky/androidide/plugins/services/IdeProjectService { + public fun addProjectLifecycleListener (Lcom/itsaky/androidide/plugins/services/ProjectLifecycleListener;)V public abstract fun getAllProjects ()Ljava/util/List; public abstract fun getCurrentProject ()Lcom/itsaky/androidide/plugins/extensions/IProject; public fun getModuleContext (Ljava/lang/String;)Lcom/itsaky/androidide/plugins/services/ModuleContext; public abstract fun getProjectByPath (Ljava/io/File;)Lcom/itsaky/androidide/plugins/extensions/IProject; public fun openProject (Ljava/io/File;)Z + public fun removeProjectLifecycleListener (Lcom/itsaky/androidide/plugins/services/ProjectLifecycleListener;)V } public final class com/itsaky/androidide/plugins/services/IdeProjectService$DefaultImpls { + public static fun addProjectLifecycleListener (Lcom/itsaky/androidide/plugins/services/IdeProjectService;Lcom/itsaky/androidide/plugins/services/ProjectLifecycleListener;)V public static fun getModuleContext (Lcom/itsaky/androidide/plugins/services/IdeProjectService;Ljava/lang/String;)Lcom/itsaky/androidide/plugins/services/ModuleContext; public static fun openProject (Lcom/itsaky/androidide/plugins/services/IdeProjectService;Ljava/io/File;)Z + public static fun removeProjectLifecycleListener (Lcom/itsaky/androidide/plugins/services/IdeProjectService;Lcom/itsaky/androidide/plugins/services/ProjectLifecycleListener;)V } public abstract interface class com/itsaky/androidide/plugins/services/IdeSidebarService { @@ -2267,6 +2279,11 @@ public final class com/itsaky/androidide/plugins/services/ModuleContext { public fun toString ()Ljava/lang/String; } +public abstract interface class com/itsaky/androidide/plugins/services/ProjectLifecycleListener { + public abstract fun onProjectClosed (Ljava/io/File;)V + public abstract fun onProjectOpened (Ljava/io/File;)V +} + public abstract class com/itsaky/androidide/plugins/services/QuickBuildAvailability { } diff --git a/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/services/IdeServices.kt b/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/services/IdeServices.kt index 6a49bd6631..f6e705ac01 100644 --- a/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/services/IdeServices.kt +++ b/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/services/IdeServices.kt @@ -63,6 +63,52 @@ interface IdeProjectService { * @return The module context, or null if no module can be resolved */ fun getModuleContext(filePath: String): ModuleContext? = null + + /** + * Registers [listener] to hear when the editor opens and closes a project. A listener added + * while a project is open hears [ProjectLifecycleListener.onProjectOpened] for it first, since + * plugins often load after the editor reopened the last project. Registering the same listener + * twice has no effect. The IDE drops + * the listener when the plugin is disabled or unloads, so register it from + * [com.itsaky.androidide.plugins.IPlugin.activate]. Available since 26.47. + * + * Requires the FILESYSTEM_READ permission. + * + * @throws SecurityException if the plugin lacks FILESYSTEM_READ. + */ + fun addProjectLifecycleListener(listener: ProjectLifecycleListener) {} + + /** Unregisters a listener added with [addProjectLifecycleListener]. Available since 26.47. */ + fun removeProjectLifecycleListener(listener: ProjectLifecycleListener) {} +} + +/** + * Hears the editor open and close a project. Calls arrive in order on one background thread + * shared by every plugin, so return quickly and hand slow work to your own thread. + * Available since 26.47. + */ +interface ProjectLifecycleListener { + /** + * The editor started opening the project rooted at [projectDir], or the project was already open + * when this listener was added. The IDE does not wait for this call: the project's sync may + * already be running, so do not rely on finishing work before it starts. A later sync or build + * of the same project does not call this again. [projectDir] is canonical. + */ + fun onProjectOpened(projectDir: File) + + /** The editor closed the project rooted at [projectDir], as given to [onProjectOpened]. */ + fun onProjectClosed(projectDir: File) +} + +/** + * Hears the editor write a file to disk: the user saving, the IDE saving before a build, or a + * plugin calling [IdeEditorService.saveFile]. Typing alone, without a save, is never reported. + * Calls arrive in order on one background thread shared by every plugin, so return quickly. + * Available since 26.47. + */ +fun interface FileSaveListener { + /** [file] is canonical, the same form as a project directory, so `file.startsWith(dir)` works. */ + fun onFileSaved(file: File) } /** @@ -287,6 +333,20 @@ interface IdeEditorService { */ fun removeContentChangeListener(listener: EditorContentChangeListener) {} + /** + * Registers [listener] to hear each file the editor saves. Registering the same listener twice + * has no effect. The IDE drops the listener when the plugin is disabled or unloads, so register + * it from [com.itsaky.androidide.plugins.IPlugin.activate]. Available since 26.47. + * + * Requires the FILESYSTEM_READ permission. + * + * @throws SecurityException if the plugin lacks FILESYSTEM_READ. + */ + fun addFileSaveListener(listener: FileSaveListener) {} + + /** Unregisters a listener added with [addFileSaveListener]. Available since 26.47. */ + fun removeFileSaveListener(listener: FileSaveListener) {} + /** * Shows an inline suggestion (ghost text) at the cursor position. * The suggestion is displayed semi-transparently and can be dismissed. 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 03e42340e7..8135dd9442 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 @@ -60,6 +60,7 @@ import com.itsaky.androidide.plugins.manager.services.IdeThemeServiceImpl import com.itsaky.androidide.plugins.manager.services.IdeTooltipServiceImpl import com.itsaky.androidide.plugins.manager.services.IdeUIServiceImpl import com.itsaky.androidide.plugins.manager.services.PluginBuildService +import com.itsaky.androidide.plugins.manager.services.PluginWorkspaceEvents import com.itsaky.androidide.plugins.manager.snippets.PluginSnippetManager import com.itsaky.androidide.plugins.manager.ui.PluginEditorTabManager import com.itsaky.androidide.plugins.services.IdeArchiveService @@ -90,6 +91,7 @@ import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeoutOrNull import org.adfa.constants.PLUGIN_ARCHIVE_EXTENSION import java.io.File import java.util.concurrent.ConcurrentHashMap @@ -342,6 +344,13 @@ class PluginManager private constructor( private val statePersistScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) private val statePersistMutex = Mutex() + // One plugin load at a time. Startup and an install can both load plugins, and two loads that + // overlap could each find a plugin not loaded yet and load it twice. + private val loadMutex = Mutex() + + // How long a load, install or uninstall waits for the load lock. Internal so tests can shorten it. + internal var loadLockWaitMs = 30_000L + fun setTemplateReloadListener(listener: (() -> Unit)?) { this.templateReloadListener = listener PluginProjectManager.getInstance().setTemplateReloadListener(listener) @@ -395,7 +404,40 @@ class PluginManager private constructor( } } - suspend fun loadPlugins() = + /** Loads every plugin file not loaded yet. Waits for a load already under way: see [withLoadLock]. */ + suspend fun loadPlugins() = withLoadLock("load plugins") { loadAllPlugins() } + + /** + * Runs [block] while no plugin load is under way. Install swaps a plugin's file in it, so a load + * that started first can't load the old file after the old version was unloaded. See [withLoadLock]. + */ + suspend fun whileNotLoading(block: suspend () -> T): T = withLoadLock("change a plugin file", block) + + /** + * Runs [block] holding the load lock, waiting at most [loadLockWaitMs] for it, then without it. + * A load holds the lock while plugins' initialize() and activate() run, so a plugin that never + * returns would otherwise block every later install and uninstall for good, including installing + * its fixed version. Going on without the lock is how loads behaved before it existed, with the + * same risks, now only behind a plugin stuck past the wait: if that stuck load later finishes, + * it can register a second instance of its plugin beside one loaded meanwhile, or, failing, + * drop by plugin id the listeners and sidebar slots of the instance installed meanwhile. + */ + private suspend fun withLoadLock( + action: String, + block: suspend () -> T, + ): T { + val locked = loadMutex.lockWithin(loadLockWaitMs) + if (!locked) { + logger.warn("A plugin load has held the load lock for over ${loadLockWaitMs / 1000} s; going on to $action without it") + } + return try { + block() + } finally { + if (locked) loadMutex.unlock() + } + } + + private suspend fun loadAllPlugins() = withContext(Dispatchers.IO) { logger.info("Loading plugins from directory: ${pluginsDir.absolutePath}") @@ -540,6 +582,8 @@ class PluginManager private constructor( */ fun loadPlugin(file: File): Result { var reservedSlotsPluginId: String? = null + // Set once initialize() may have registered workspace listeners, so a later failure drops them. + var listenersPluginId: String? = null return try { logger.debug("Loading plugin from: ${file.absolutePath}") @@ -565,6 +609,14 @@ class PluginManager private constructor( logger.debug("Parsed manifest for plugin: ${manifest.name} (${manifest.id})") + // loadPlugins() runs on every install. Loading a plugin that is already loaded again would + // leave the old instance active, its listeners still registered, beside the new one. + // Installing over a plugin unloads it first, so its new file still loads. + loadedPlugins[manifest.id]?.let { loaded -> + logger.debug("Plugin already loaded, keeping its instance: ${manifest.id}") + return Result.success(loaded.plugin) + } + if (!securityManager.validatePlugin(file, manifest)) { return Result.failure(SecurityException("plugin failed security validation: ${manifest.id}")) } @@ -651,9 +703,11 @@ class PluginManager private constructor( val pluginContext = createPluginContextWithResources(manifest.id, manifest.name, classLoader, permissions, ctx) logger.debug("Initializing plugin: ${manifest.id}") + listenersPluginId = manifest.id val initResult = initializePlugin(plugin, pluginContext).getOrElse { e -> logger.error("Plugin initialization threw exception for: ${manifest.id}", e) + PluginWorkspaceEvents.getInstance().removeAll(manifest.id) if (manifest.sidebarItems > 0) { SidebarSlotManager.releasePluginSlots(manifest.id) } @@ -662,6 +716,7 @@ class PluginManager private constructor( if (!initResult) { logger.warn(" plugin initialization returned false for: ${manifest.id}") + PluginWorkspaceEvents.getInstance().removeAll(manifest.id) if (manifest.sidebarItems > 0) { SidebarSlotManager.releasePluginSlots(manifest.id) } @@ -689,6 +744,8 @@ class PluginManager private constructor( loadedPlugins[manifest.id] = loadedPlugin if (!isEnabled) { + // A disabled plugin hears no workspace events, as after disablePlugin(). + PluginWorkspaceEvents.getInstance().removeAll(manifest.id) logger.info("Successfully loaded plugin (disabled): ${manifest.name} (${manifest.id})") return Result.success(plugin) } @@ -699,6 +756,9 @@ class PluginManager private constructor( reservedSlotsPluginId?.let { pluginId -> SidebarSlotManager.releasePluginSlots(pluginId) } + listenersPluginId?.let { pluginId -> + runCatching { PluginWorkspaceEvents.getInstance().removeAll(pluginId) } + } logger.error("Failed to load plugin from ${file.name}: ${e.javaClass.simpleName}: ${e.message}", e) val prefix = if (e is RuntimeException) "" else "[${e.javaClass.simpleName}] " Result.failure(RuntimeException("Error loading plugin: $prefix${e.message}", e)) @@ -732,6 +792,8 @@ class PluginManager private constructor( logger.error("Failed to activate plugin: ${manifest.id}", e) loadedPlugin.isEnabled = false savePluginState(manifest.id, false) + // activate() may have registered workspace listeners before it failed. + PluginWorkspaceEvents.getInstance().removeAll(manifest.id) } } @@ -770,6 +832,11 @@ class PluginManager private constructor( fun unloadPlugin(pluginId: String): Boolean { val loadedPlugin = loadedPlugins.remove(pluginId) ?: return false + // First and on its own: the plugin is already out of loadedPlugins, so if a later cleanup step + // throws, nothing could drop its listeners afterwards, and none may reach it while it tears down. + runCatching { PluginWorkspaceEvents.getInstance().removeAll(pluginId) } + .onFailure { logger.error("Failed to drop workspace listeners for: $pluginId", it) } + try { // Remove documentation if plugin implements DocumentationExtension if (loadedPlugin.plugin is DocumentationExtension) { @@ -1196,6 +1263,9 @@ class PluginManager private constructor( }.onFailure { logger.error("Failed to clean snippets for: $pluginId", it) } runCatching { PluginBuildActionManager.getInstance().cleanupPlugin(pluginId) } .onFailure { logger.error("Failed to clean build actions for: $pluginId", it) } + // A disabled plugin must stop hearing workspace events; activate() registers again on enable. + runCatching { PluginWorkspaceEvents.getInstance().removeAll(pluginId) } + .onFailure { logger.error("Failed to drop workspace listeners for: $pluginId", it) } runCatching { val commandService = loadedPlugin.context.services.get(IdeCommandService::class.java) if (commandService is IdeCommandServiceImpl) commandService.cancelAllCommands() @@ -2002,3 +2072,17 @@ internal fun initializePlugin( plugin: IPlugin, context: PluginContext, ): Result = runCatching { plugin.initialize(context) } + +/** + * Waits at most [timeoutMs] for this mutex. True when the caller now holds it, and must unlock it. + * The flag is set inside the wait, not taken from its result: the timeout can fire just after + * lock() returned, and withTimeoutOrNull then reports null for a lock the caller holds. + */ +internal suspend fun Mutex.lockWithin(timeoutMs: Long): Boolean { + var locked = false + withTimeoutOrNull(timeoutMs) { + lock() + locked = true + } + return locked +} diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeEditorServiceImpl.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeEditorServiceImpl.kt index 7de586be3e..e5e61025df 100644 --- a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeEditorServiceImpl.kt +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeEditorServiceImpl.kt @@ -6,6 +6,7 @@ import com.itsaky.androidide.plugins.PluginPermission import com.itsaky.androidide.plugins.services.CursorPosition import com.itsaky.androidide.plugins.services.EditorContentChangeListener import com.itsaky.androidide.plugins.services.FileChangeListener +import com.itsaky.androidide.plugins.services.FileSaveListener import com.itsaky.androidide.plugins.services.IdeEditorService import com.itsaky.androidide.plugins.services.SelectionRange import com.itsaky.androidide.utils.Environment @@ -22,6 +23,7 @@ class IdeEditorServiceImpl( private val readPermissions: Set = setOf(PluginPermission.FILESYSTEM_READ), private val writePermissions: Set = setOf(PluginPermission.FILESYSTEM_WRITE), private val pathValidator: PathValidator? = null, + private val workspaceEvents: PluginWorkspaceEvents = PluginWorkspaceEvents.getInstance(), ) : IdeEditorService { interface PathValidator { fun isPathAllowed(file: File): Boolean @@ -450,6 +452,15 @@ class IdeEditorServiceImpl( contentChangeListeners.remove(listener) } + override fun addFileSaveListener(listener: FileSaveListener) { + requireRead() + workspaceEvents.addFileSaveListener(pluginId, listener) + } + + override fun removeFileSaveListener(listener: FileSaveListener) { + workspaceEvents.removeFileSaveListener(pluginId, listener) + } + override fun showInlineSuggestion(text: String) { // Tag the suggestion with this plugin's id so concurrent plugins don't clobber or dismiss // each other's ghost text. The public IdeEditorService signature is unchanged. diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeProjectServiceImpl.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeProjectServiceImpl.kt index 0e804a00a6..87ae212b02 100644 --- a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeProjectServiceImpl.kt +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeProjectServiceImpl.kt @@ -7,6 +7,7 @@ import com.itsaky.androidide.plugins.extensions.IProject import com.itsaky.androidide.plugins.manager.core.PluginManager import com.itsaky.androidide.plugins.services.IdeProjectService import com.itsaky.androidide.plugins.services.ModuleContext +import com.itsaky.androidide.plugins.services.ProjectLifecycleListener import com.itsaky.androidide.preferences.internal.GeneralPreferences import com.itsaky.androidide.projects.ProjectManagerImpl import com.itsaky.androidide.utils.Environment @@ -24,6 +25,7 @@ class IdeProjectServiceImpl( private val requiredPermissions: Set = setOf(PluginPermission.FILESYSTEM_READ), private val pathValidator: PathValidator? = null, private val activityProvider: PluginManager.ActivityProvider? = null, + private val workspaceEvents: PluginWorkspaceEvents = PluginWorkspaceEvents.getInstance(), ) : IdeProjectService { /** * Interface for validating project path access @@ -164,6 +166,17 @@ class IdeProjectServiceImpl( } } + override fun addProjectLifecycleListener(listener: ProjectLifecycleListener) { + if (!hasRequiredPermissions()) { + throw SecurityException("Plugin $pluginId does not have required permissions: ${getRequiredPermissionsString()}") + } + workspaceEvents.addProjectLifecycleListener(pluginId, listener) + } + + override fun removeProjectLifecycleListener(listener: ProjectLifecycleListener) { + workspaceEvents.removeProjectLifecycleListener(pluginId, listener) + } + private fun resolveProjectDirUnderProjectsDir(path: File): File? { val projectsDir = runCatching { Environment.PROJECTS_DIR }.getOrNull() ?: return null return runCatching { diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/PluginWorkspaceEvents.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/PluginWorkspaceEvents.kt new file mode 100644 index 0000000000..f5c2dfa463 --- /dev/null +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/PluginWorkspaceEvents.kt @@ -0,0 +1,196 @@ +package com.itsaky.androidide.plugins.manager.services + +import com.itsaky.androidide.plugins.services.FileSaveListener +import com.itsaky.androidide.plugins.services.ProjectLifecycleListener +import org.slf4j.LoggerFactory +import java.io.File +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.Executor +import java.util.concurrent.Executors + +/** + * Tells plugins when the editor opens or closes a project and when it saves a file. The app + * reports each moment here; [IdeProjectServiceImpl] and [IdeEditorServiceImpl] register a plugin's + * listeners, keyed by plugin id so [removeAll] drops them when the plugin unloads. + * + * Listeners run in order on [executor], one thread by default: the editor never waits on a plugin, + * and every plugin hears an open before the saves that follow it and the close after them. Each + * event is queued, and every registration added or removed, under [lock], so the queue order is the + * order the state changed in and an event's recipients are a consistent snapshot. + */ +class PluginWorkspaceEvents internal constructor( + private val executor: Executor, +) { + private class Registration( + val pluginId: String, + val listener: L, + ) + + private val projectListeners = CopyOnWriteArrayList>() + private val saveListeners = CopyOnWriteArrayList>() + + private val lock = Any() + + // The project the listeners last heard open, so a re-sync of it is not reported as another open. + private var openProjectDir: File? = null + + /** + * The editor opened [projectDir]. Repeats for the project already open are ignored. Returns the + * directory as listeners hear it, canonical; report the close with that. + */ + fun projectOpened(projectDir: File): File { + val dir = normalize(projectDir) + synchronized(lock) { + if (dir == openProjectDir) return dir + // Switching projects without a close report still tells listeners the old one went away. + openProjectDir?.let { closed -> dispatch(projectListeners, "onProjectClosed") { it.onProjectClosed(closed) } } + openProjectDir = dir + dispatch(projectListeners, "onProjectOpened") { it.onProjectOpened(dir) } + } + return dir + } + + /** + * The editor closed [projectDir], the directory [projectOpened] returned. It is compared as given, + * without resolving it on disk, because the close is reported from the main thread. Ignored + * unless it is the project last reported open, so an editor tearing down a project that is no + * longer the open one cannot close the open one. + */ + fun projectClosed(projectDir: File) { + synchronized(lock) { + if (projectDir != openProjectDir) return + openProjectDir = null + dispatch(projectListeners, "onProjectClosed") { it.onProjectClosed(projectDir) } + } + } + + /** The editor wrote [file] to disk. */ + fun fileSaved(file: File) { + // Canonical like the project directory, so a listener can test saved.startsWith(projectDir). + // Resolved on the listeners' thread: the caller is often the main thread. + val saved = lazy { normalize(file) } + synchronized(lock) { + dispatch(saveListeners, "onFileSaved") { it.onFileSaved(saved.value) } + } + } + + /** + * Registers [listener] for [pluginId]. A listener added while a project is open hears that open + * first: plugins load in the background, often after the editor reopened the last project. + */ + internal fun addProjectLifecycleListener( + pluginId: String, + listener: ProjectLifecycleListener, + ) { + synchronized(lock) { + val registration = add(projectListeners, pluginId, listener) ?: return + val open = openProjectDir ?: return + dispatchTo(projectListeners, registration, "onProjectOpened") { it.onProjectOpened(open) } + } + } + + internal fun removeProjectLifecycleListener( + pluginId: String, + listener: ProjectLifecycleListener, + ) = remove(projectListeners, pluginId, listener) + + internal fun addFileSaveListener( + pluginId: String, + listener: FileSaveListener, + ) { + synchronized(lock) { add(saveListeners, pluginId, listener) } + } + + internal fun removeFileSaveListener( + pluginId: String, + listener: FileSaveListener, + ) = remove(saveListeners, pluginId, listener) + + /** Drops every listener [pluginId] registered. */ + internal fun removeAll(pluginId: String) { + synchronized(lock) { + // removeIf replaces the array in one step, so invoke(), which reads without the lock, sees + // the list before or after the removal, never part-way through Kotlin's removeAll {}. + projectListeners.removeIf { it.pluginId == pluginId } + saveListeners.removeIf { it.pluginId == pluginId } + } + } + + /** The new registration, or null when [pluginId] already registered [listener]. */ + private fun add( + registrations: CopyOnWriteArrayList>, + pluginId: String, + listener: L, + ): Registration? { + // Per plugin: two plugins sharing one listener object each keep their own registration. + if (registrations.any { it.pluginId == pluginId && it.listener === listener }) return null + return Registration(pluginId, listener).also(registrations::add) + } + + // Scoped to the plugin, so one plugin cannot unregister another's listener. + private fun remove( + registrations: CopyOnWriteArrayList>, + pluginId: String, + listener: L, + ) { + synchronized(lock) { registrations.removeIf { it.pluginId == pluginId && it.listener === listener } } + } + + private fun dispatch( + registrations: CopyOnWriteArrayList>, + event: String, + call: (L) -> Unit, + ) { + if (registrations.isEmpty()) return + // The listeners registered now: one added later hears the open project through its replay + // instead, so it never hears an open twice. + val targets = ArrayList(registrations) + executor.execute { + targets.forEach { invoke(registrations, it, event, call) } + } + } + + private fun dispatchTo( + registrations: CopyOnWriteArrayList>, + registration: Registration, + event: String, + call: (L) -> Unit, + ) { + executor.execute { invoke(registrations, registration, event, call) } + } + + // Checked when the call runs, without the lock: a plugin removed after the event was queued, or + // while an earlier listener of the same event was running, is not called. One removed just after + // this check can still be called once, while it tears down; unload does not wait for plugin code. + private fun invoke( + registrations: CopyOnWriteArrayList>, + registration: Registration, + event: String, + call: (L) -> Unit, + ) { + if (registration !in registrations) return + try { + call(registration.listener) + } catch (e: Throwable) { + // A plugin's bug must not stop the others hearing the event, nor kill the thread. + log.warn("Plugin {} threw from {}", registration.pluginId, event, e) + } + } + + private fun normalize(file: File): File = runCatching { file.canonicalFile }.getOrDefault(file.absoluteFile) + + companion object { + private val log = LoggerFactory.getLogger(PluginWorkspaceEvents::class.java) + + private val shared: PluginWorkspaceEvents by lazy { + PluginWorkspaceEvents( + Executors.newSingleThreadExecutor { runnable -> + Thread(runnable, "plugin-workspace-events").apply { isDaemon = true } + }, + ) + } + + @JvmStatic + fun getInstance(): PluginWorkspaceEvents = shared + } +} diff --git a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/LockWithinTest.kt b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/LockWithinTest.kt new file mode 100644 index 0000000000..ec16910a6a --- /dev/null +++ b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/LockWithinTest.kt @@ -0,0 +1,47 @@ +package com.itsaky.androidide.plugins.manager.core + +import com.google.common.truth.Truth.assertWithMessage +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.async +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.sync.Mutex +import org.junit.Test +import java.util.concurrent.locks.LockSupport + +/** + * [lockWithin] must never report "not locked" for a lock the caller got. The timeout can fire just + * after lock() returns; reading the result of withTimeoutOrNull then leaked the lock for good, and + * every later plugin load waited out the timeout and ran without it. + */ +class LockWithinTest { + @Test + fun aLockTakenAsTheWaitTimesOutIsReportedHeld() = + runBlocking { + var leaked = 0 + repeat(ROUNDS) { round -> + val mutex = Mutex() + mutex.lock() + val waiter = async(Dispatchers.IO) { mutex.lockWithin(1L) } + // Release around the 1 ms timeout, jittered, so some releases land as it fires. + val releaser = + launch(Dispatchers.Default) { + LockSupport.parkNanos(700_000L + (round % 600) * 1_000L) + mutex.unlock() + } + val locked = waiter.await() + releaser.join() + if (locked) { + mutex.unlock() + } else if (mutex.isLocked) { + leaked++ + } + } + assertWithMessage("rounds where the lock was taken but reported free").that(leaked).isEqualTo(0) + } + + private companion object { + // The old code leaked in about 1 in 100 timeouts, so 3,000 rounds (about 3 s) catch it. + const val ROUNDS = 3_000 + } +} diff --git a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerLoadLockTest.kt b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerLoadLockTest.kt new file mode 100644 index 0000000000..910aa78973 --- /dev/null +++ b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerLoadLockTest.kt @@ -0,0 +1,111 @@ +package com.itsaky.androidide.plugins.manager.core + +import com.google.common.truth.Truth.assertWithMessage +import com.itsaky.androidide.plugins.PluginLogger +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.async +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config + +/** + * Plugin loads run one at a time, and install swaps a plugin's file between them: two overlapping + * loads could each load the same plugin, and a load under way could load a file install replaced. + * The wait is bounded, so a load stuck in a plugin's code can't block every later one. + */ +@RunWith(RobolectricTestRunner::class) +@Config(manifest = Config.NONE, sdk = [28]) +class PluginManagerLoadLockTest { + @Test + fun loadWaitsWhileInstallSwapsAFile() = + runBlocking { + val manager = PluginManager.getInstance(RuntimeEnvironment.getApplication(), Any(), SilentLogger) + val swapping = CompletableDeferred() + val swapDone = CompletableDeferred() + val swap = + launch(Dispatchers.Default) { + manager.whileNotLoading { + swapping.complete(Unit) + swapDone.await() + } + } + swapping.await() + + val load = async(Dispatchers.Default) { manager.loadPlugins() } + // With no plugin files, an unguarded load finishes in milliseconds. + delay(500) + assertWithMessage("loadPlugins() ran while a file swap held the lock").that(load.isCompleted).isFalse() + + swapDone.complete(Unit) + withTimeout(10_000) { + swap.join() + load.await() + } + } + + @Test + fun aLoadStuckHoldingTheLockDoesNotBlockTheNextForever() = + runBlocking { + val manager = PluginManager.getInstance(RuntimeEnvironment.getApplication(), Any(), SilentLogger) + val wait = manager.loadLockWaitMs + manager.loadLockWaitMs = 300 + val stuck = CompletableDeferred() + val holding = CompletableDeferred() + // Stands in for a load whose plugin never returns from initialize() or activate(). + val holder = + launch(Dispatchers.Default) { + manager.whileNotLoading { + holding.complete(Unit) + stuck.await() + } + } + holding.await() + try { + // Waits out loadLockWaitMs, then loads without the lock instead of waiting for good. + withTimeout(10_000) { manager.loadPlugins() } + } finally { + stuck.complete(Unit) + holder.join() + manager.loadLockWaitMs = wait + } + } + + private object SilentLogger : PluginLogger { + override val pluginId = "test" + + override fun debug(message: String) = Unit + + override fun debug( + message: String, + error: Throwable, + ) = Unit + + override fun info(message: String) = Unit + + override fun info( + message: String, + error: Throwable, + ) = Unit + + override fun warn(message: String) = Unit + + override fun warn( + message: String, + error: Throwable, + ) = Unit + + override fun error(message: String) = Unit + + override fun error( + message: String, + error: Throwable, + ) = Unit + } +} diff --git a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/PluginWorkspaceEventsTest.kt b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/PluginWorkspaceEventsTest.kt new file mode 100644 index 0000000000..c32a7ad2af --- /dev/null +++ b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/PluginWorkspaceEventsTest.kt @@ -0,0 +1,458 @@ +package com.itsaky.androidide.plugins.manager.services + +import com.google.common.truth.Truth.assertThat +import com.itsaky.androidide.plugins.PluginPermission +import com.itsaky.androidide.plugins.extensions.IProject +import com.itsaky.androidide.plugins.services.FileSaveListener +import com.itsaky.androidide.plugins.services.ProjectLifecycleListener +import org.junit.After +import org.junit.Before +import org.junit.Test +import java.io.File +import java.nio.file.Files +import java.util.concurrent.CyclicBarrier +import java.util.concurrent.Executor +import java.util.concurrent.Executors +import java.util.concurrent.atomic.AtomicInteger + +class PluginWorkspaceEventsTest { + private lateinit var root: File + private lateinit var projectA: File + private lateinit var projectB: File + private val queued = ArrayDeque() + + @Before + fun setUp() { + root = + File.createTempFile("workspace-events-", "").apply { + delete() + mkdirs() + } + projectA = File(root, "a").apply { mkdirs() }.canonicalFile + projectB = File(root, "b").apply { mkdirs() }.canonicalFile + } + + @After + fun tearDown() { + root.deleteRecursively() + } + + private fun direct() = PluginWorkspaceEvents(Executor { it.run() }) + + private fun deferred() = PluginWorkspaceEvents(Executor { queued.addLast(it) }) + + private class RecordingListener : ProjectLifecycleListener { + val calls = mutableListOf() + + override fun onProjectOpened(projectDir: File) { + calls += "opened ${projectDir.name}" + } + + override fun onProjectClosed(projectDir: File) { + calls += "closed ${projectDir.name}" + } + } + + @Test + fun anOpenedProjectIsReportedWithItsCanonicalDirectory() { + val events = direct() + val dirs = mutableListOf() + events.addProjectLifecycleListener( + "p", + object : ProjectLifecycleListener { + override fun onProjectOpened(projectDir: File) { + dirs += projectDir + } + + override fun onProjectClosed(projectDir: File) = Unit + }, + ) + + events.projectOpened(File(projectA, "../a")) + + assertThat(dirs).containsExactly(projectA) + } + + @Test + fun aResyncOfTheOpenProjectIsNotReportedAsAnotherOpen() { + val events = direct() + val listener = RecordingListener().also { events.addProjectLifecycleListener("p", it) } + + events.projectOpened(projectA) + events.projectOpened(projectA) + + assertThat(listener.calls).containsExactly("opened a") + } + + @Test + fun openingAnotherProjectClosesThePreviousOneFirst() { + val events = direct() + val listener = RecordingListener().also { events.addProjectLifecycleListener("p", it) } + + events.projectOpened(projectA) + events.projectOpened(projectB) + + assertThat(listener.calls).containsExactly("opened a", "closed a", "opened b").inOrder() + } + + @Test + fun aCloseIsReportedOnceAndOnlyAfterAnOpen() { + val events = direct() + val listener = RecordingListener().also { events.addProjectLifecycleListener("p", it) } + + events.projectClosed(projectA) + events.projectOpened(projectA) + events.projectClosed(projectA) + events.projectClosed(projectA) + + assertThat(listener.calls).containsExactly("opened a", "closed a").inOrder() + } + + @Test + fun reopeningAClosedProjectIsReportedAgain() { + val events = direct() + val listener = RecordingListener().also { events.addProjectLifecycleListener("p", it) } + + events.projectOpened(projectA) + events.projectClosed(projectA) + events.projectOpened(projectA) + + assertThat(listener.calls).containsExactly("opened a", "closed a", "opened a").inOrder() + } + + @Test + fun aSavedFileIsReportedToSaveListeners() { + val events = direct() + val saved = mutableListOf() + events.addFileSaveListener("p") { saved += it } + + val file = File(projectA, "Main.kt") + events.fileSaved(file) + + assertThat(saved).containsExactly(file) + } + + @Test + fun aListenerThatThrowsDoesNotStopTheOthers() { + val events = direct() + val heard = mutableListOf() + // An Error, not only an Exception: a plugin built against another API throws NoSuchMethodError. + events.addFileSaveListener("broken") { throw NoSuchMethodError("stale plugin") } + events.addFileSaveListener("crashy") { throw IllegalStateException("bug") } + events.addFileSaveListener("fine") { heard += it.name } + + events.fileSaved(File(projectA, "Main.kt")) + + assertThat(heard).containsExactly("Main.kt") + } + + @Test + fun theSameListenerAddedTwiceIsCalledOnce() { + val events = direct() + var calls = 0 + val listener = FileSaveListener { calls++ } + events.addFileSaveListener("p", listener) + events.addFileSaveListener("p", listener) + + events.fileSaved(File(projectA, "Main.kt")) + + assertThat(calls).isEqualTo(1) + } + + @Test + fun aRemovedListenerIsNotCalled() { + val events = direct() + val listener = RecordingListener() + var saves = 0 + val saveListener = FileSaveListener { saves++ } + events.addProjectLifecycleListener("p", listener) + events.addFileSaveListener("p", saveListener) + + events.removeProjectLifecycleListener("p", listener) + events.removeFileSaveListener("p", saveListener) + events.projectOpened(projectA) + events.fileSaved(File(projectA, "Main.kt")) + + assertThat(listener.calls).isEmpty() + assertThat(saves).isEqualTo(0) + } + + @Test + fun removeAllDropsOnlyThatPluginsListeners() { + val events = direct() + val gone = RecordingListener().also { events.addProjectLifecycleListener("gone", it) } + val kept = RecordingListener().also { events.addProjectLifecycleListener("kept", it) } + var goneSaves = 0 + events.addFileSaveListener("gone") { goneSaves++ } + + events.removeAll("gone") + events.projectOpened(projectA) + events.fileSaved(File(projectA, "Main.kt")) + + assertThat(gone.calls).isEmpty() + assertThat(goneSaves).isEqualTo(0) + assertThat(kept.calls).containsExactly("opened a") + } + + @Test + fun aPluginRemovedBeforeAQueuedEventRunsIsNotCalled() { + val events = deferred() + val listener = RecordingListener().also { events.addProjectLifecycleListener("p", it) } + + events.projectOpened(projectA) + events.removeAll("p") + while (queued.isNotEmpty()) queued.removeFirst().run() + + assertThat(listener.calls).isEmpty() + } + + @Test + fun eventsRunInTheOrderTheyWereReported() { + val events = deferred() + val order = mutableListOf() + events.addProjectLifecycleListener( + "p", + object : ProjectLifecycleListener { + override fun onProjectOpened(projectDir: File) { + order += "opened" + } + + override fun onProjectClosed(projectDir: File) { + order += "closed" + } + }, + ) + events.addFileSaveListener("p") { order += "saved" } + + events.projectOpened(projectA) + events.fileSaved(File(projectA, "Main.kt")) + events.projectClosed(projectA) + while (queued.isNotEmpty()) queued.removeFirst().run() + + assertThat(order).containsExactly("opened", "saved", "closed").inOrder() + } + + @Test + fun aListenerAddedWhileAProjectIsOpenHearsThatOpen() { + val events = direct() + events.projectOpened(projectA) + + val late = RecordingListener().also { events.addProjectLifecycleListener("late", it) } + events.projectClosed(projectA) + + assertThat(late.calls).containsExactly("opened a", "closed a").inOrder() + } + + @Test + fun aListenerAddedBeforeAQueuedOpenRunsHearsItOnce() { + val events = deferred() + // Another plugin is listening, so the open is really queued, not skipped as unheard. + events.addProjectLifecycleListener("early", RecordingListener()) + events.projectOpened(projectA) + val late = RecordingListener().also { events.addProjectLifecycleListener("late", it) } + while (queued.isNotEmpty()) queued.removeFirst().run() + + assertThat(late.calls).containsExactly("opened a") + } + + @Test + fun closingAProjectThatIsNotTheOpenOneIsIgnored() { + val events = direct() + val listener = RecordingListener().also { events.addProjectLifecycleListener("p", it) } + + events.projectOpened(projectA) + events.projectClosed(projectB) + + assertThat(listener.calls).containsExactly("opened a") + } + + @Test + fun aPluginRemovedWhileAnEventIsBeingDeliveredIsNotCalled() { + val events = direct() + var removedHeard = 0 + // The first listener unloads the other plugin while this save is being delivered. + events.addFileSaveListener("first") { events.removeAll("second") } + events.addFileSaveListener("second") { removedHeard++ } + + events.fileSaved(File(projectA, "Main.kt")) + + assertThat(removedHeard).isEqualTo(0) + } + + @Test + fun aSavedFileHasTheSameFormAsTheProjectDirectory() { + val events = direct() + val link = File(root, "link").toPath() + Files.createSymbolicLink(link, projectA.toPath()) + val opened = mutableListOf() + val saved = mutableListOf() + events.addProjectLifecycleListener( + "p", + object : ProjectLifecycleListener { + override fun onProjectOpened(projectDir: File) { + opened += projectDir + } + + override fun onProjectClosed(projectDir: File) = Unit + }, + ) + events.addFileSaveListener("p") { saved += it } + + events.projectOpened(link.toFile()) + events.fileSaved(File(link.toFile(), "Main.kt")) + + assertThat(saved.single().startsWith(opened.single())).isTrue() + } + + @Test + fun aPluginCannotRemoveAnotherPluginsListener() { + val events = direct() + var heard = 0 + val listener = FileSaveListener { heard++ } + events.addFileSaveListener("owner", listener) + + events.removeFileSaveListener("other", listener) + events.fileSaved(File(projectA, "Main.kt")) + + assertThat(heard).isEqualTo(1) + } + + @Test + fun twoPluginsSharingOneListenerKeepSeparateRegistrations() { + val events = direct() + var heard = 0 + val shared = FileSaveListener { heard++ } + events.addFileSaveListener("a", shared) + events.addFileSaveListener("b", shared) + + events.removeAll("a") + events.fileSaved(File(projectA, "Main.kt")) + + assertThat(heard).isEqualTo(1) + } + + @Test + fun nothingIsQueuedWhenNoPluginListens() { + var queuedTasks = 0 + val events = PluginWorkspaceEvents(Executor { queuedTasks++ }) + + events.fileSaved(File(projectA, "Main.kt")) + events.projectOpened(projectA) + events.projectClosed(projectA) + + assertThat(queuedTasks).isEqualTo(0) + } + + @Test(expected = SecurityException::class) + fun addingAProjectListenerWithoutReadPermissionThrows() { + projectService(permissions = emptySet()).addProjectLifecycleListener(RecordingListener()) + } + + @Test + fun aProjectListenerAddedThroughTheServiceHearsOpens() { + val events = direct() + val listener = RecordingListener() + projectService(setOf(PluginPermission.FILESYSTEM_READ), events).addProjectLifecycleListener(listener) + + events.projectOpened(projectA) + + assertThat(listener.calls).containsExactly("opened a") + } + + @Test(expected = SecurityException::class) + fun addingASaveListenerWithoutReadPermissionThrows() { + editorService(permissions = emptySet()).addFileSaveListener { } + } + + @Test + fun aSaveListenerAddedThroughTheServiceHearsSaves() { + val events = direct() + val saved = mutableListOf() + editorService(setOf(PluginPermission.FILESYSTEM_READ), events).addFileSaveListener { saved += it } + + val file = File(projectA, "Main.kt") + events.fileSaved(file) + + assertThat(saved).containsExactly(file) + } + + private fun projectService( + permissions: Set, + events: PluginWorkspaceEvents = direct(), + ) = IdeProjectServiceImpl( + pluginId = "p", + permissions = permissions, + projectProvider = NoProjects, + workspaceEvents = events, + ) + + private fun editorService( + permissions: Set, + events: PluginWorkspaceEvents = direct(), + ) = IdeEditorServiceImpl( + pluginId = "p", + permissions = permissions, + editorProvider = NoEditors, + workspaceEvents = events, + ) + + private object NoProjects : IdeProjectServiceImpl.ProjectProvider { + override fun getCurrentProject(): IProject? = null + + override fun getAllProjects(): List = emptyList() + + override fun getProjectByPath(path: File): IProject? = null + } + + private object NoEditors : IdeEditorServiceImpl.EditorProvider { + override fun getCurrentFile(): File? = null + + override fun getOpenFiles(): List = emptyList() + + override fun isFileOpen(file: File): Boolean = false + + override fun getCurrentSelection(): String? = null + } + + @Test + fun registrationsChangedOnManyThreadsAreNeitherLostNorDoubled() { + // One plugin registers while another plugin's listeners are dropped, as at startup when a + // disabled plugin loads beside one that activates. The registration must survive, once. + val saved = File(projectA, "Main.kt") + val pool = Executors.newFixedThreadPool(2) + val start = CyclicBarrier(2) + var wrong = 0 + try { + repeat(ROUNDS) { + val events = direct() + repeat(OTHERS) { i -> events.addFileSaveListener("other", FileSaveListener { _ -> i.hashCode() }) } + val heard = AtomicInteger() + val listener = FileSaveListener { heard.incrementAndGet() } + val drop = + pool.submit { + start.await() + events.removeAll("other") + } + val add = + pool.submit { + start.await() + events.addFileSaveListener("p", listener) + } + drop.get() + add.get() + events.fileSaved(saved) + if (heard.get() != 1) wrong++ + } + } finally { + pool.shutdownNow() + } + assertThat(wrong).isEqualTo(0) + } + + private companion object { + // Enough rounds, with enough of another plugin's listeners to drop, that the old unlocked + // in-place removal loses a registration in almost every run. + const val ROUNDS = 20_000 + const val OTHERS = 64 + } +} diff --git a/resources/src/main/res/values/strings.xml b/resources/src/main/res/values/strings.xml index 49f1ed7302..643591bfce 100644 --- a/resources/src/main/res/values/strings.xml +++ b/resources/src/main/res/values/strings.xml @@ -1316,6 +1316,7 @@ Plugin changes will take effect after restarting the app. Do you want to restart now? Restart now Failed to install plugin: %1$s + Failed to install plugin: the installed version of %1$s could not be unloaded. Restart Code on the Go and try again. \'%1$s\' was installed from a different build variant. Uninstall it before installing this version. Plugin error Plugin file not found