diff --git a/.github/workflows/instrumentation-test.yml b/.github/workflows/instrumentation-test.yml index ac07df9f54..63e56c76da 100644 --- a/.github/workflows/instrumentation-test.yml +++ b/.github/workflows/instrumentation-test.yml @@ -101,7 +101,7 @@ jobs: --results-dir=test-results/kotlin \ --results-bucket=gs://firebase-test-results-${RANDOM} \ --project=codeonthego-64a92 \ - --test-targets "class com.itsaky.androidide.ProjectBuildTestWithKtsGradle" > test-results/kotlin/test_output.txt 2>&1 || KOTLIN_EXIT_CODE=$? + --test-targets "class org.appdevforall.codeonthego.ProjectBuildTestWithKtsGradle" > test-results/kotlin/test_output.txt 2>&1 || KOTLIN_EXIT_CODE=$? echo "Kotlin tests exit code: $KOTLIN_EXIT_CODE" @@ -129,7 +129,7 @@ jobs: --results-dir=test-results/groovy \ --results-bucket=gs://firebase-test-results-${RANDOM} \ --project=codeonthego-64a92 \ - --test-targets "class com.itsaky.androidide.ProjectBuildTestWithGroovyGradle" > test-results/groovy/test_output.txt 2>&1 || GROOVY_EXIT_CODE=$? + --test-targets "class org.appdevforall.codeonthego.ProjectBuildTestWithGroovyGradle" > test-results/groovy/test_output.txt 2>&1 || GROOVY_EXIT_CODE=$? echo "Groovy tests exit code: $GROOVY_EXIT_CODE" diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index fd60cebe40..2abeba2829 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -51,7 +51,7 @@ Feature code layers as **UI → ViewModel → Repository → data source**, with **EventBus is a deliberate side-channel.** Long-running, cross-module signals (build/install lifecycle, editor events) are broadcast via GreenRobot EventBus (`@Subscribe(threadMode = ThreadMode.MAIN)`) and the `eventbus-events` module's shared event types. Treat it as the integration bus *between* subsystems; don't use it to replace a ViewModel's own state inside a single screen. -**App Links enter through a UI-less trampoline, not `MainActivity` directly.** `DeepLinkActivity` (`app/src/main/java/com/itsaky/androidide/activities/DeepLinkActivity.kt`) is the sole `` holder for `https://appdevforall.org/device/open/project/...` (and the identical `www` subdomain). It never renders anything — it parses the URI into a `DeepLinkRequest` (project name plus an optional file/line/column), checks whether an editor is already on screen (`ActionContextProvider.getActivity()`, the live `EditorHandlerActivity` tracker -- not `IProjectManager`'s `workspace`, which stays null for the whole duration of a Gradle sync even while the editor is already open), and routes to `MainActivity` (nothing open) or the live, `singleTask` `EditorActivityKt`/`EditorHandlerActivity` (a project is open — reused via `onNewIntent`), then finishes itself. This avoids a visible flash of `MainActivity`'s real UI when the actual destination is the already-running editor. +**App Links enter through a UI-less trampoline, not `MainActivity` directly.** `DeepLinkActivity` (`app/src/main/java/org/appdevforall/codeonthego/activities/DeepLinkActivity.kt`) is the sole `` holder for `https://appdevforall.org/device/open/project/...` (and the identical `www` subdomain). It never renders anything — it parses the URI into a `DeepLinkRequest` (project name plus an optional file/line/column), checks whether an editor is already on screen (`ActionContextProvider.getActivity()`, the live `EditorHandlerActivity` tracker -- not `IProjectManager`'s `workspace`, which stays null for the whole duration of a Gradle sync even while the editor is already open), and routes to `MainActivity` (nothing open) or the live, `singleTask` `EditorActivityKt`/`EditorHandlerActivity` (a project is open — reused via `onNewIntent`), then finishes itself. This avoids a visible flash of `MainActivity`'s real UI when the actual destination is the already-running editor. `EditorHandlerActivity.onNewIntent` then branches on `projectDirPath` (set as soon as a project starts opening) rather than `workspace` so the mid-sync case still matches correctly: **same project already open** — no project-wise work, just navigate to the requested file (`applyDeepLinkFileRequest`); **a different project is open** — the existing, unmodified `confirmProjectClose()` dialog runs (it also guards against a second confirm-close request overlapping a manual close or an in-flight save, and a *third* overlapping request supersedes the second's pending callback rather than being dropped), and only once the user actually confirms does an `onDestroy()`-triggered hand-off (`PendingDeepLinkOpen`, Koin-provided) start the new project — deliberately deferred to `onDestroy()`, not fired synchronously after `finish()`, so the new `PROJECT_PATH` can't race a `singleTask` re-delivery to the dying instance; `projectDirPath` **is still blank** — this instance never actually finished initializing a project (e.g. recreated after process death with no `PROJECT_PATH` extra), so `confirmProjectClose()` would silently no-op (`contentOrNull` is null); this case reuses the same `onDestroy()`-deferred hand-off instead of showing a close dialog for a project that was never really open; **nothing was open** — `MainActivity.openProject`/`EditorHandlerActivity.postProjectInit` apply the pending file request once the cold-opened project's sync succeeds. @@ -130,7 +130,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/org/appdevforall/codeonthego/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. > > **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. > diff --git a/REVIEW.md b/REVIEW.md index 036de3a0bc..92940d0881 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -213,7 +213,7 @@ Features that aren't fully stabilized ship behind the **experimental feature fla The plugin API is **not frozen** and we don't yet guarantee backward/binary compatibility (see [plugin-api.md](docs/plugin-api.md)). So the bar isn't "never break plugins" — it's **don't break them by accident**. -- **Does the change touch the plugin API surface?** Anything in `:plugin-api` (package `com.itsaky.androidide.plugins`), a manifest `plugin.*` meta-data key, a permission key string, a service interface reached via `ServiceRegistry`, or a format contract (`.cgp`/`.cgt`, the `plugin_documentation.db` schema, `scripts.json`, the `localhost:6174` help URLs). If so, treat it as a contract change. +- **Does the change touch the plugin API surface?** Anything in `:plugin-api` (package `org.appdevforall.codeonthego.plugins`), a manifest `plugin.*` meta-data key, a permission key string, a service interface reached via `ServiceRegistry`, or a format contract (`.cgp`/`.cgt`, the `plugin_documentation.db` schema, `scripts.json`, the `localhost:6174` help URLs). If so, treat it as a contract change. - **If it breaks compatibility, is that deliberate and documented?** The PR should say what breaks, who's affected, and why it's worth it. Watch the Kotlin traps that look source-compatible but aren't — data-class constructor params, enum constants, methods added to plugin-implemented interfaces (plugin-api.md lists them). - **Do a mechanical impact check:** build/load the in-tree example plugins (`apk-viewer-plugin`, `markdown-preview-plugin`, `keystore-generator-plugin`) — and, for significant changes, the external `plugin-examples` repo — against the change. - **Even without an API change,** new core features can break plugins (shared UI, toolbar action IDs, service behavior) and plugins can conflict with each other. Keep that in view. diff --git a/actions/src/main/java/com/itsaky/androidide/actions/ActionData.java b/actions/src/main/java/com/itsaky/androidide/actions/ActionData.java deleted file mode 100644 index d41a215070..0000000000 --- a/actions/src/main/java/com/itsaky/androidide/actions/ActionData.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.actions; - -import android.content.Context; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; - -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; - -/** - * @author Akash Yadav - */ -public class ActionData { - - private ActionData() {} - - /** - * Creates a new {@link ActionData} instance. - * - * @param context The context to this instance is attached to. - * @return A new {@link ActionData} instance. - */ - @NonNull - public static ActionData create(@NonNull Context context) { - final var data = new ActionData(); - data.put(Context.class, context); - return data; - } - - private final Map, Object> instances = new HashMap<>(); - - public void put(@NonNull Class type, @Nullable T object) { - Objects.requireNonNull(type); - this.instances.put(type, object); - } - - @Nullable - public T get(@NonNull Class type) { - Objects.requireNonNull(type); - - final var object = this.instances.get(type); - if (object == null) { - return null; - } - - return type.cast(object); - } - - public void clear() { - this.instances.clear(); - } -} diff --git a/actions/src/main/java/com/itsaky/androidide/actions/ActionsRegistry.kt b/actions/src/main/java/com/itsaky/androidide/actions/ActionsRegistry.kt deleted file mode 100644 index b779774b33..0000000000 --- a/actions/src/main/java/com/itsaky/androidide/actions/ActionsRegistry.kt +++ /dev/null @@ -1,123 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ -package com.itsaky.androidide.actions - -import com.itsaky.androidide.actions.internal.DefaultActionsRegistry -import com.itsaky.androidide.utils.ServiceLoader -import com.itsaky.androidide.utils.VMUtils - -/** @author Akash Yadav */ -abstract class ActionsRegistry { - - companion object { - - private var instance: ActionsRegistry? = null - - @JvmStatic - fun getInstance(): ActionsRegistry { - if (instance == null) { - instance = if (VMUtils.isJvm) { - DefaultActionsRegistry() - } else ServiceLoader.load(ActionsRegistry::class.java).findFirstOrThrow() - } - - return instance as ActionsRegistry - } - } - - /** - * Register the given action. - * - * @param action The action to register. Must not be `null`. - * @return `true` if the action was registered successfully. `false` otherwise. - */ - abstract fun registerAction(action: ActionItem): Boolean - - /** - * Unregister the given action. - * - * @param action The action to unregister. Must not be `null`. - * @return `true` if the action was unregistered successfully. `false` otherwise. - */ - abstract fun unregisterAction(action: ActionItem): Boolean - - /** - * Unregister the action with the given ID. - * - * @param id The ID of action to unregister. Must not be `null`. - * @return `true` if the action was unregistered successfully. `false` otherwise. - */ - abstract fun unregisterAction(id: String): Boolean - - /** - * Find the action with the given ID. - * - * @param id The ID of the action to find. - * @return The found action or `null`. - */ - abstract fun findAction(location: ActionItem.Location, id: String): ActionItem? - - /** - * Find the action with the given unique item ID. - * - * @param itemId The ID of the action to find. - * @return The found action or `null`. - */ - abstract fun findAction(location: ActionItem.Location, itemId: Int): ActionItem? - - /** - * Fill the given menu with the registered actions. - * - * Subclasses must first call [ActionItem.prepare] to update the action. - */ - abstract fun fillMenu(params: FillMenuParams) - - /** Get all the registered actions at the given location. */ - abstract fun getActions(location: ActionItem.Location): Map - - /** Clear all the registered actions. */ - abstract fun clearActions(location: ActionItem.Location) - - /** Clear all actions at the given location except those matching the predicate. */ - abstract fun clearActionsExceptWhere(location: ActionItem.Location, predicate: (ActionItem) -> Boolean) - - /** - * Register a listener that will be called when any action is executed. The callbacks are called - * irrespective of the action's execution result. - * - * @param listener The listener to register. - */ - abstract fun registerActionExecListener(listener: ActionExecListener) - - /** - * Unregister the given listener. - * - * @param listener The listener to unregister. - */ - abstract fun unregisterActionExecListener(listener: ActionExecListener) - - /** Listener for listening to callbacks for action execution. */ - interface ActionExecListener { - - /** - * The given action was executed. - * @param action The action that was executed. - * @param result The result of the action execution. - */ - fun onExec(action: ActionItem, result: Any) - } -} diff --git a/actions/src/main/java/com/itsaky/androidide/actions/EditTextAdapter.kt b/actions/src/main/java/com/itsaky/androidide/actions/EditTextAdapter.kt deleted file mode 100644 index 78362bbe3b..0000000000 --- a/actions/src/main/java/com/itsaky/androidide/actions/EditTextAdapter.kt +++ /dev/null @@ -1,84 +0,0 @@ -package com.itsaky.androidide.actions - -import android.content.ClipData -import android.content.ClipboardManager -import android.content.Context -import android.view.View -import android.widget.EditText - -class EditTextAdapter(private val view: EditText) : MutableTextTarget { - private val clipboard: ClipboardManager? - get() = view.context.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager - - override fun copyText() { - val start = view.selectionStart - val end = view.selectionEnd - - if (start < 0 || end < 0) return - if (start == end) return - - val content = view.text.subSequence(minOf(start, end), maxOf(start, end)) - val clip = ClipData.newPlainText("Copied Text", content) - clipboard?.setPrimaryClip(clip) - } - - override fun cut() { - val start = view.selectionStart - val end = view.selectionEnd - if (start < 0 || end < 0) return - if (start == end) return - - copyText() - view.text.delete(minOf(start, end), maxOf(start, end)) - view.setSelection(minOf(start, end)) - } - - override fun paste() { - val clip = clipboard?.primaryClip ?: return - if (clip.itemCount <= 0) return - - val pasteText = clip.getItemAt(0).coerceToText(view.context) ?: return - var start = view.selectionStart - var end = view.selectionEnd - - if (start < 0 || end < 0) { - view.requestFocus() - val safePos = view.text?.length ?: 0 - view.setSelection(safePos) - start = view.selectionStart - end = view.selectionEnd - } - val min = minOf(start, end) - val max = maxOf(start, end) - - if (min != max) { - view.text.replace(min, max, pasteText) - view.setSelection(min + pasteText.length) - } else { - view.text.insert(min, pasteText) - view.setSelection(min + pasteText.length) - } - } - - override fun selectAll() { - view.selectAll() - } - - override fun hasSelection() = view.hasSelection() - override fun isEditable() = view.isEnabled - - override fun getSelectedText(): String? { - val start = view.selectionStart - val end = view.selectionEnd - - if (start < 0 || end < 0 || start == end) { return null } - - val min = minOf(start, end) - val max = maxOf(start, end) - - if (max > view.length()) { return null } - return view.text.subSequence(min, max).toString() - } - - override fun getAnchorView(): View = view -} \ No newline at end of file diff --git a/actions/src/main/java/com/itsaky/androidide/actions/FillMenuParams.kt b/actions/src/main/java/com/itsaky/androidide/actions/FillMenuParams.kt deleted file mode 100644 index cef44b6123..0000000000 --- a/actions/src/main/java/com/itsaky/androidide/actions/FillMenuParams.kt +++ /dev/null @@ -1,36 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.actions - -import android.view.Menu -import com.itsaky.androidide.actions.internal.DefaultActionsRegistry - -/** - * Parameters required by [ActionsRegistry] to fill a menu. - * - * @author Akash Yadav - */ -data class FillMenuParams( - val data: ActionData, - val location: ActionItem.Location, - val menu: Menu, - val onMenuItemClick: OnActionClickListener = OnActionClickListener { registry, action, _, actionData -> - (registry as DefaultActionsRegistry).executeAction(action, actionData) - true - } -) diff --git a/actions/src/main/java/com/itsaky/androidide/actions/OnActionClickListener.kt b/actions/src/main/java/com/itsaky/androidide/actions/OnActionClickListener.kt deleted file mode 100644 index 6c35ab0cc1..0000000000 --- a/actions/src/main/java/com/itsaky/androidide/actions/OnActionClickListener.kt +++ /dev/null @@ -1,38 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.actions - -import android.view.MenuItem - -/** - * Listener for listening to click events on [ActionItem]. - * - * @author Akash Yadav - */ -fun interface OnActionClickListener { - - /** - * Called when the given [action] is clicked. - * - * @param registry The [ActionsRegistry]. - * @param action The action that was clicked. - * @param data The action data associated with the action. - * @return Whether the click event was consumed. - */ - fun onClick(registry: ActionsRegistry, action: ActionItem, item: MenuItem, data: ActionData): Boolean -} \ No newline at end of file diff --git a/actions/src/main/java/com/itsaky/androidide/actions/SidebarActionItem.kt b/actions/src/main/java/com/itsaky/androidide/actions/SidebarActionItem.kt deleted file mode 100644 index b243391a1a..0000000000 --- a/actions/src/main/java/com/itsaky/androidide/actions/SidebarActionItem.kt +++ /dev/null @@ -1,45 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.actions - -import androidx.fragment.app.Fragment -import androidx.navigation.fragment.FragmentNavigatorDestinationBuilder -import kotlin.reflect.KClass - -/** - * An [ActionItem] that is shown in the editor activity's sidebar. If the action's [fragmentClass] is null, - * the [ActionItem.execAction] is called when the user clicks on the navigation item in the navigation rail. - * - * The [id] property of the action is used as the route for the navigation graph. - * - * @author Akash Yadav - */ -interface SidebarActionItem : ActionItem { - - /** - * The fragment class for this action item. Implementations can provide a fragment class which - * will be shown when this action item is selected. - */ - val fragmentClass: KClass? - - /** - * Build/setup the fragment navigation for this action item. This method is called only if the [fragmentClass] property - * is non-null. - */ - fun FragmentNavigatorDestinationBuilder.buildNavigation() {} -} \ No newline at end of file diff --git a/actions/src/main/java/com/itsaky/androidide/actions/TextTarget.kt b/actions/src/main/java/com/itsaky/androidide/actions/TextTarget.kt deleted file mode 100644 index f4d611f3ad..0000000000 --- a/actions/src/main/java/com/itsaky/androidide/actions/TextTarget.kt +++ /dev/null @@ -1,17 +0,0 @@ -package com.itsaky.androidide.actions - -import android.view.View - -interface TextTarget { - fun copyText() - fun selectAll() - fun hasSelection(): Boolean - fun getSelectedText(): String? - fun getAnchorView(): View? -} - -interface MutableTextTarget : TextTarget { - fun cut() - fun paste() - fun isEditable(): Boolean -} \ No newline at end of file diff --git a/actions/src/main/java/com/itsaky/androidide/actions/internal/DefaultActionsRegistry.kt b/actions/src/main/java/com/itsaky/androidide/actions/internal/DefaultActionsRegistry.kt deleted file mode 100644 index 67c086f76d..0000000000 --- a/actions/src/main/java/com/itsaky/androidide/actions/internal/DefaultActionsRegistry.kt +++ /dev/null @@ -1,286 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ -package com.itsaky.androidide.actions.internal - -import android.view.Menu -import android.view.MenuItem -import com.google.auto.service.AutoService -import com.itsaky.androidide.actions.ActionData -import com.itsaky.androidide.actions.ActionItem -import com.itsaky.androidide.actions.ActionMenu -import com.itsaky.androidide.actions.ActionsRegistry -import com.itsaky.androidide.actions.FillMenuParams -import com.itsaky.androidide.actions.OnActionClickListener -import com.itsaky.androidide.actions.locations.CodeActionsMenu -import com.itsaky.androidide.utils.withStopWatch -import kotlinx.coroutines.CancellationException -import kotlinx.coroutines.CoroutineName -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.Job -import kotlinx.coroutines.launch -import kotlinx.coroutines.plus -import kotlinx.coroutines.withContext -import org.slf4j.LoggerFactory -import java.util.concurrent.ConcurrentHashMap - -/** - * Default implementation for the [ActionsRegistry] - * - * @author Akash Yadav - */ -@AutoService(ActionsRegistry::class) -class DefaultActionsRegistry : ActionsRegistry() { - - private val actions = ConcurrentHashMap>() - private val listeners = HashSet() - - private val actionsCoroutineScope = CoroutineScope(Dispatchers.Default) + - CoroutineName("DefaultActionsRegistry") - - companion object { - private val log = LoggerFactory.getLogger(DefaultActionsRegistry::class.java) - private const val DEBUG_PREFIX = "ACTION_DEBUG: " - } - - init { - registerAction(CodeActionsMenu) - } - - override fun getActions(location: ActionItem.Location): MutableMap { - return actions.getOrPut(location.id) { LinkedHashMap() } - } - - override fun registerAction(action: ActionItem): Boolean { - val actions = getActions(action.location) - val isUpdating = actions.containsKey(action.id) - log.debug( - "$DEBUG_PREFIX ${if (isUpdating) "Updating" else "Registering"} action '${action.id}' at location '${action.location.id}'. " + - "Current count: ${actions.size}." - ) - actions.remove(action.id) - actions[action.id] = action - log.debug("$DEBUG_PREFIX Location '${action.location.id}' now has ${actions.size} actions.") - if (actions.size == 3) { - log.debug("$DEBUG_PREFIX readhed the 3 target") - } - return true - } - - override fun unregisterAction(action: ActionItem): Boolean { - val actions = getActions(action.location) - log.debug( - "$DEBUG_PREFIX Unregistering action '${action.id}' from location '${action.location.id}'. " + - "Current count: ${actions.size}." - ) - val older = actions.remove(action.id) - if (older != null) { - older.destroy() - log.debug("$DEBUG_PREFIX Unregistered '${action.id}'. Location '${action.location.id}' now has ${actions.size} actions.") - return true - } - log.debug("$DEBUG_PREFIX Action '${action.id}' not found at location '${action.location.id}'.") - return false - } - - override fun unregisterAction(id: String): Boolean { - log.debug("$DEBUG_PREFIX Attempting to unregister action with id '$id' from all locations.") - for ((locationId, locations) in this.actions) { - val older = locations.remove(id) - if (older != null) { - older.destroy() - log.debug("$DEBUG_PREFIX Removed action '$id' from location '$locationId'. New count: ${locations.size}.") - return true - } - } - log.debug("$DEBUG_PREFIX Action with id '$id' not found in any location.") - return false - } - - override fun findAction(location: ActionItem.Location, id: String): ActionItem? = - getActions(location)[id] - - override fun findAction(location: ActionItem.Location, itemId: Int): ActionItem? { - for (action in getActions(location)) { - if (action.value.itemId == itemId) { - return action.value - } - } - - return null - } - - override fun clearActions(location: ActionItem.Location) { - val actions = getActions(location) - log.debug("$DEBUG_PREFIX Clearing all ${actions.size} actions from location '${location.id}'.") - actions.forEach { it.value.destroy() } - actions.clear() - log.debug("$DEBUG_PREFIX Location '${location.id}' is now empty.") - } - - override fun clearActionsExceptWhere( - location: ActionItem.Location, - predicate: (ActionItem) -> Boolean - ) { - val actions = getActions(location) - val initialCount = actions.size - val toRemove = mutableListOf() - - log.debug("$DEBUG_PREFIX Conditionally clearing actions from location '${location.id}'. Initial count: $initialCount.") - - actions.forEach { (key, action) -> - if (!predicate(action)) { - toRemove.add(key) - } - } - - if (toRemove.isNotEmpty()) { - log.debug("$DEBUG_PREFIX Removing ${toRemove.size} actions from location '${location.id}': $toRemove") - toRemove.forEach { key -> - actions[key]?.destroy() - actions.remove(key) - } - log.debug("$DEBUG_PREFIX Location '${location.id}' now has ${actions.size} actions.") - } else { - log.debug("$DEBUG_PREFIX No actions met the removal criteria for location '${location.id}'.") - } - } - - override fun registerActionExecListener(listener: ActionExecListener) { - listeners.add(listener) - } - - override fun unregisterActionExecListener(listener: ActionExecListener) { - listeners.remove(listener) - } - - override fun fillMenu(params: FillMenuParams) { - val (data, location, menu, onClickListener) = params - val actions = getActions(location) - - val sortedActions = actions.values.sortedWith(compareBy({ it.order }, { it.id })) - - for (action in sortedActions) { - action.prepare(data) - - if (!action.visible) { - continue - } - addActionToMenu(menu, action, data, onClickListener) - } - } - - private fun addActionToMenu( - menu: Menu, - action: ActionItem, - data: ActionData, - onClickListener: OnActionClickListener - ) { - - val item: MenuItem = if (action is ActionMenu) { - val sub = menu.addSubMenu(Menu.NONE, action.itemId, action.order, action.label) - - var shouldBeEnabled = false - for (subItem in action.children) { - subItem.prepare(data) - if (subItem.visible) { - addActionToMenu(sub, subItem, data, onClickListener) - } - - if (action.enabled && subItem.enabled && !shouldBeEnabled) { - shouldBeEnabled = true - } - } - - action.enabled = shouldBeEnabled - sub.item - } else { - menu.add(Menu.NONE, action.itemId, action.order, action.label) - } - - item.isEnabled = action.enabled - - item.contentDescription = action.label - - item.icon = action.icon?.apply { - colorFilter = action.createColorFilter(data) - alpha = if (action.enabled) 255 else 76 - } - - var showAsAction = action.getShowAsActionFlags(data) - if (showAsAction == -1) { - showAsAction = if (action.icon != null) { - MenuItem.SHOW_AS_ACTION_IF_ROOM - } else { - MenuItem.SHOW_AS_ACTION_NEVER - } - } - - if (!action.enabled) { - showAsAction = MenuItem.SHOW_AS_ACTION_NEVER - } - - item.setShowAsAction(showAsAction) - - action.createActionView(data)?.let { item.actionView = it } - - if (action !is ActionMenu) { - item.setOnMenuItemClickListener { - onClickListener.onClick(this, action, it, data) - } - } - } - - /** Executes the given action item with the given */ - fun executeAction(action: ActionItem, data: ActionData): Job { - val onMainThread = action.requiresUIThread - val context = if (onMainThread) Dispatchers.Main.immediate else Dispatchers.Default - return actionsCoroutineScope.launch(context) { - val result = try { - withStopWatch("Action '${action.id}'") { action.execAction(data) } - } catch (e: IllegalArgumentException) { - log.error("An error occurred when performing action '{}'", action.id, e) - return@launch - } - - val post = fun() = run { - action.postExec(data, result) - notifyActionExec(action, result) - } - - if (onMainThread) { - post() - } else { - withContext(Dispatchers.Main.immediate) { post() } - } - }.also { job -> - job.invokeOnCompletion { cause -> - when (cause) { - null -> log.debug("Action '{}' execution completed.", action.id) - is CancellationException -> log.debug("Action '{}' execution was cancelled.", action.id) - else -> log.debug("Action '{}' execution failed.", action.id, cause) - } - } - } - } - - private fun notifyActionExec(action: ActionItem, result: Any) { - for (listener in listeners) { - listener.onExec(action, result) - } - } -} \ No newline at end of file diff --git a/actions/src/main/java/com/itsaky/androidide/actions/locations/CodeActionsMenu.kt b/actions/src/main/java/com/itsaky/androidide/actions/locations/CodeActionsMenu.kt deleted file mode 100644 index 2915f7db2d..0000000000 --- a/actions/src/main/java/com/itsaky/androidide/actions/locations/CodeActionsMenu.kt +++ /dev/null @@ -1,52 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.actions.locations - -import android.content.Context -import android.graphics.drawable.Drawable -import androidx.core.content.ContextCompat -import com.itsaky.androidide.actions.ActionData -import com.itsaky.androidide.actions.ActionItem -import com.itsaky.androidide.actions.ActionMenu -import com.itsaky.androidide.idetooltips.TooltipTag -import com.itsaky.androidide.resources.R - -/** @author Akash Yadav */ -object CodeActionsMenu : ActionMenu { - - const val ID = "ide.editor.code.actions" - - override val children: MutableSet = mutableSetOf() - override val id: String = ID - - override var label: String = "Code actions" - override var visible = true - override var enabled: Boolean = true - override var icon: Drawable? = null - override fun retrieveTooltipTag(isAlternateContext: Boolean) = - TooltipTag.EDITOR_TOOLBAR_CODE_ACTIONS - override var requiresUIThread: Boolean = false - override var location: ActionItem.Location = ActionItem.Location.EDITOR_TEXT_ACTIONS - - override fun prepare(data: ActionData) { - super.prepare(data) - if (icon == null) { - icon = ContextCompat.getDrawable(data[Context::class.java]!!, R.drawable.ic_code) - } - } -} \ No newline at end of file diff --git a/actions/src/main/java/org/appdevforall/codeonthego/actions/ActionData.java b/actions/src/main/java/org/appdevforall/codeonthego/actions/ActionData.java new file mode 100644 index 0000000000..4c9da98626 --- /dev/null +++ b/actions/src/main/java/org/appdevforall/codeonthego/actions/ActionData.java @@ -0,0 +1,72 @@ +/* + * This file is part of AndroidIDE. + * + * AndroidIDE is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * AndroidIDE is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with AndroidIDE. If not, see . + */ + +package org.appdevforall.codeonthego.actions; + +import android.content.Context; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; + +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; + +/** + * @author Akash Yadav + */ +public class ActionData { + + /** + * Creates a new {@link ActionData} instance. + * + * @param context + * The context to this instance is attached to. + * @return A new {@link ActionData} instance. + */ + @NonNull + public static ActionData create(@NonNull Context context) { + final var data = new ActionData(); + data.put(Context.class, context); + return data; + } + + private final Map, Object> instances = new HashMap<>(); + + private ActionData() {} + + public void clear() { + this.instances.clear(); + } + + @Nullable + public T get(@NonNull Class type) { + Objects.requireNonNull(type); + + final var object = this.instances.get(type); + if (object == null) { + return null; + } + + return type.cast(object); + } + + public void put(@NonNull Class type, @Nullable T object) { + Objects.requireNonNull(type); + this.instances.put(type, object); + } +} diff --git a/actions/src/main/java/com/itsaky/androidide/actions/ActionItem.kt b/actions/src/main/java/org/appdevforall/codeonthego/actions/ActionItem.kt similarity index 96% rename from actions/src/main/java/com/itsaky/androidide/actions/ActionItem.kt rename to actions/src/main/java/org/appdevforall/codeonthego/actions/ActionItem.kt index 82c9f5506d..207f950792 100644 --- a/actions/src/main/java/com/itsaky/androidide/actions/ActionItem.kt +++ b/actions/src/main/java/org/appdevforall/codeonthego/actions/ActionItem.kt @@ -15,7 +15,7 @@ * along with AndroidIDE. If not, see . */ -package com.itsaky.androidide.actions +package org.appdevforall.codeonthego.actions import android.graphics.ColorFilter import android.graphics.PorterDuff @@ -24,12 +24,13 @@ import android.graphics.drawable.Drawable import android.view.Menu import android.view.View import androidx.annotation.CallSuper -import com.itsaky.androidide.idetooltips.TooltipCategory -import com.itsaky.androidide.utils.resolveAttr +import com.itsaky.androidide.actions.R +import org.appdevforall.codeonthego.idetooltips.TooltipCategory +import org.appdevforall.codeonthego.utils.resolveAttr /** * An action that can be registered using the [ActionsRegistry] - * [com.itsaky.androidide.actions.ActionsRegistry] + * [org.appdevforall.codeonthego.actions.ActionsRegistry] * * @author Akash Yadav */ diff --git a/actions/src/main/java/com/itsaky/androidide/actions/ActionMenu.kt b/actions/src/main/java/org/appdevforall/codeonthego/actions/ActionMenu.kt similarity index 97% rename from actions/src/main/java/com/itsaky/androidide/actions/ActionMenu.kt rename to actions/src/main/java/org/appdevforall/codeonthego/actions/ActionMenu.kt index 8b773e5c2f..4e1c816239 100644 --- a/actions/src/main/java/com/itsaky/androidide/actions/ActionMenu.kt +++ b/actions/src/main/java/org/appdevforall/codeonthego/actions/ActionMenu.kt @@ -15,7 +15,7 @@ * along with AndroidIDE. If not, see . */ -package com.itsaky.androidide.actions +package org.appdevforall.codeonthego.actions /** * An action menu is an action which can contain child actions. diff --git a/actions/src/main/java/org/appdevforall/codeonthego/actions/ActionsRegistry.kt b/actions/src/main/java/org/appdevforall/codeonthego/actions/ActionsRegistry.kt new file mode 100644 index 0000000000..f9979e6a38 --- /dev/null +++ b/actions/src/main/java/org/appdevforall/codeonthego/actions/ActionsRegistry.kt @@ -0,0 +1,135 @@ +/* + * This file is part of AndroidIDE. + * + * AndroidIDE is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * AndroidIDE is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with AndroidIDE. If not, see . + */ +package org.appdevforall.codeonthego.actions + +import org.appdevforall.codeonthego.actions.internal.DefaultActionsRegistry +import org.appdevforall.codeonthego.utils.ServiceLoader +import org.appdevforall.codeonthego.utils.VMUtils + +/** @author Akash Yadav */ +abstract class ActionsRegistry { + companion object { + private var instance: ActionsRegistry? = null + + @JvmStatic + fun getInstance(): ActionsRegistry { + if (instance == null) { + instance = + if (VMUtils.isJvm) { + DefaultActionsRegistry() + } else { + ServiceLoader.load(ActionsRegistry::class.java).findFirstOrThrow() + } + } + + return instance as ActionsRegistry + } + } + + /** + * Register the given action. + * + * @param action The action to register. Must not be `null`. + * @return `true` if the action was registered successfully. `false` otherwise. + */ + abstract fun registerAction(action: ActionItem): Boolean + + /** + * Unregister the given action. + * + * @param action The action to unregister. Must not be `null`. + * @return `true` if the action was unregistered successfully. `false` otherwise. + */ + abstract fun unregisterAction(action: ActionItem): Boolean + + /** + * Unregister the action with the given ID. + * + * @param id The ID of action to unregister. Must not be `null`. + * @return `true` if the action was unregistered successfully. `false` otherwise. + */ + abstract fun unregisterAction(id: String): Boolean + + /** + * Find the action with the given ID. + * + * @param id The ID of the action to find. + * @return The found action or `null`. + */ + abstract fun findAction( + location: ActionItem.Location, + id: String, + ): ActionItem? + + /** + * Find the action with the given unique item ID. + * + * @param itemId The ID of the action to find. + * @return The found action or `null`. + */ + abstract fun findAction( + location: ActionItem.Location, + itemId: Int, + ): ActionItem? + + /** + * Fill the given menu with the registered actions. + * + * Subclasses must first call [ActionItem.prepare] to update the action. + */ + abstract fun fillMenu(params: FillMenuParams) + + /** Get all the registered actions at the given location. */ + abstract fun getActions(location: ActionItem.Location): Map + + /** Clear all the registered actions. */ + abstract fun clearActions(location: ActionItem.Location) + + /** Clear all actions at the given location except those matching the predicate. */ + abstract fun clearActionsExceptWhere( + location: ActionItem.Location, + predicate: (ActionItem) -> Boolean, + ) + + /** + * Register a listener that will be called when any action is executed. The callbacks are called + * irrespective of the action's execution result. + * + * @param listener The listener to register. + */ + abstract fun registerActionExecListener(listener: ActionExecListener) + + /** + * Unregister the given listener. + * + * @param listener The listener to unregister. + */ + abstract fun unregisterActionExecListener(listener: ActionExecListener) + + /** Listener for listening to callbacks for action execution. */ + interface ActionExecListener { + /** + * The given action was executed. + * @param action The action that was executed. + * @param result The result of the action execution. + */ + fun onExec( + action: ActionItem, + result: Any, + ) + } +} diff --git a/actions/src/main/java/org/appdevforall/codeonthego/actions/EditTextAdapter.kt b/actions/src/main/java/org/appdevforall/codeonthego/actions/EditTextAdapter.kt new file mode 100644 index 0000000000..699e3795e3 --- /dev/null +++ b/actions/src/main/java/org/appdevforall/codeonthego/actions/EditTextAdapter.kt @@ -0,0 +1,91 @@ +package org.appdevforall.codeonthego.actions + +import android.content.ClipData +import android.content.ClipboardManager +import android.content.Context +import android.view.View +import android.widget.EditText + +class EditTextAdapter( + private val view: EditText, +) : MutableTextTarget { + private val clipboard: ClipboardManager? + get() = view.context.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager + + override fun copyText() { + val start = view.selectionStart + val end = view.selectionEnd + + if (start < 0 || end < 0) return + if (start == end) return + + val content = view.text.subSequence(minOf(start, end), maxOf(start, end)) + val clip = ClipData.newPlainText("Copied Text", content) + clipboard?.setPrimaryClip(clip) + } + + override fun cut() { + val start = view.selectionStart + val end = view.selectionEnd + if (start < 0 || end < 0) return + if (start == end) return + + copyText() + view.text.delete(minOf(start, end), maxOf(start, end)) + view.setSelection(minOf(start, end)) + } + + override fun paste() { + val clip = clipboard?.primaryClip ?: return + if (clip.itemCount <= 0) return + + val pasteText = clip.getItemAt(0).coerceToText(view.context) ?: return + var start = view.selectionStart + var end = view.selectionEnd + + if (start < 0 || end < 0) { + view.requestFocus() + val safePos = view.text?.length ?: 0 + view.setSelection(safePos) + start = view.selectionStart + end = view.selectionEnd + } + val min = minOf(start, end) + val max = maxOf(start, end) + + if (min != max) { + view.text.replace(min, max, pasteText) + view.setSelection(min + pasteText.length) + } else { + view.text.insert(min, pasteText) + view.setSelection(min + pasteText.length) + } + } + + override fun selectAll() { + view.selectAll() + } + + override fun hasSelection() = view.hasSelection() + + override fun isEditable() = view.isEnabled + + override fun getSelectedText(): String? { + val start = view.selectionStart + val end = view.selectionEnd + + if (start < 0 || end < 0 || start == end) { + return null + } + + val min = minOf(start, end) + val max = maxOf(start, end) + + if (max > view.length()) { + return null + } + return view.text.subSequence(min, max).toString() + } + + override fun getAnchorView(): View = view +} diff --git a/actions/src/main/java/com/itsaky/androidide/actions/EditorActionItem.kt b/actions/src/main/java/org/appdevforall/codeonthego/actions/EditorActionItem.kt similarity index 77% rename from actions/src/main/java/com/itsaky/androidide/actions/EditorActionItem.kt rename to actions/src/main/java/org/appdevforall/codeonthego/actions/EditorActionItem.kt index a2f68c43dd..6b74fbfd09 100644 --- a/actions/src/main/java/com/itsaky/androidide/actions/EditorActionItem.kt +++ b/actions/src/main/java/org/appdevforall/codeonthego/actions/EditorActionItem.kt @@ -15,7 +15,7 @@ * along with AndroidIDE. If not, see . */ -package com.itsaky.androidide.actions +package org.appdevforall.codeonthego.actions /** * A [ActionItem] related to the code editor. Subclasses can choose whether to dismiss the actions @@ -24,11 +24,10 @@ package com.itsaky.androidide.actions * @author Akash Yadav */ interface EditorActionItem : ActionItem { - - /** - * Whether the actions window should be dismissed or not once this action is performed. - * - * @return `true` if the actions window must be dismissed, `false` otherwise. - */ - fun dismissOnAction(): Boolean = true + /** + * Whether the actions window should be dismissed or not once this action is performed. + * + * @return `true` if the actions window must be dismissed, `false` otherwise. + */ + fun dismissOnAction(): Boolean = true } diff --git a/actions/src/main/java/org/appdevforall/codeonthego/actions/FillMenuParams.kt b/actions/src/main/java/org/appdevforall/codeonthego/actions/FillMenuParams.kt new file mode 100644 index 0000000000..6f27654e87 --- /dev/null +++ b/actions/src/main/java/org/appdevforall/codeonthego/actions/FillMenuParams.kt @@ -0,0 +1,37 @@ +/* + * This file is part of AndroidIDE. + * + * AndroidIDE is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * AndroidIDE is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with AndroidIDE. If not, see . + */ + +package org.appdevforall.codeonthego.actions + +import android.view.Menu +import org.appdevforall.codeonthego.actions.internal.DefaultActionsRegistry + +/** + * Parameters required by [ActionsRegistry] to fill a menu. + * + * @author Akash Yadav + */ +data class FillMenuParams( + val data: ActionData, + val location: ActionItem.Location, + val menu: Menu, + val onMenuItemClick: OnActionClickListener = + OnActionClickListener { registry, action, _, actionData -> + (registry as DefaultActionsRegistry).executeAction(action, actionData) + true + }, +) diff --git a/actions/src/main/java/org/appdevforall/codeonthego/actions/OnActionClickListener.kt b/actions/src/main/java/org/appdevforall/codeonthego/actions/OnActionClickListener.kt new file mode 100644 index 0000000000..990d14a0e4 --- /dev/null +++ b/actions/src/main/java/org/appdevforall/codeonthego/actions/OnActionClickListener.kt @@ -0,0 +1,42 @@ +/* + * This file is part of AndroidIDE. + * + * AndroidIDE is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * AndroidIDE is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with AndroidIDE. If not, see . + */ + +package org.appdevforall.codeonthego.actions + +import android.view.MenuItem + +/** + * Listener for listening to click events on [ActionItem]. + * + * @author Akash Yadav + */ +fun interface OnActionClickListener { + /** + * Called when the given [action] is clicked. + * + * @param registry The [ActionsRegistry]. + * @param action The action that was clicked. + * @param data The action data associated with the action. + * @return Whether the click event was consumed. + */ + fun onClick( + registry: ActionsRegistry, + action: ActionItem, + item: MenuItem, + data: ActionData, + ): Boolean +} diff --git a/actions/src/main/java/org/appdevforall/codeonthego/actions/SidebarActionItem.kt b/actions/src/main/java/org/appdevforall/codeonthego/actions/SidebarActionItem.kt new file mode 100644 index 0000000000..ba002e0716 --- /dev/null +++ b/actions/src/main/java/org/appdevforall/codeonthego/actions/SidebarActionItem.kt @@ -0,0 +1,44 @@ +/* + * This file is part of AndroidIDE. + * + * AndroidIDE is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * AndroidIDE is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with AndroidIDE. If not, see . + */ + +package org.appdevforall.codeonthego.actions + +import androidx.fragment.app.Fragment +import androidx.navigation.fragment.FragmentNavigatorDestinationBuilder +import kotlin.reflect.KClass + +/** + * An [ActionItem] that is shown in the editor activity's sidebar. If the action's [fragmentClass] is null, + * the [ActionItem.execAction] is called when the user clicks on the navigation item in the navigation rail. + * + * The [id] property of the action is used as the route for the navigation graph. + * + * @author Akash Yadav + */ +interface SidebarActionItem : ActionItem { + /** + * The fragment class for this action item. Implementations can provide a fragment class which + * will be shown when this action item is selected. + */ + val fragmentClass: KClass? + + /** + * Build/setup the fragment navigation for this action item. This method is called only if the [fragmentClass] property + * is non-null. + */ + fun FragmentNavigatorDestinationBuilder.buildNavigation() {} +} diff --git a/actions/src/main/java/com/itsaky/androidide/actions/SidebarSlotManager.kt b/actions/src/main/java/org/appdevforall/codeonthego/actions/SidebarSlotManager.kt similarity index 95% rename from actions/src/main/java/com/itsaky/androidide/actions/SidebarSlotManager.kt rename to actions/src/main/java/org/appdevforall/codeonthego/actions/SidebarSlotManager.kt index c4837525ee..a6574bcefd 100644 --- a/actions/src/main/java/com/itsaky/androidide/actions/SidebarSlotManager.kt +++ b/actions/src/main/java/org/appdevforall/codeonthego/actions/SidebarSlotManager.kt @@ -1,5 +1,5 @@ -package com.itsaky.androidide.actions +package org.appdevforall.codeonthego.actions import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.atomic.AtomicInteger diff --git a/actions/src/main/java/org/appdevforall/codeonthego/actions/TextTarget.kt b/actions/src/main/java/org/appdevforall/codeonthego/actions/TextTarget.kt new file mode 100644 index 0000000000..826f13bde9 --- /dev/null +++ b/actions/src/main/java/org/appdevforall/codeonthego/actions/TextTarget.kt @@ -0,0 +1,23 @@ +package org.appdevforall.codeonthego.actions + +import android.view.View + +interface TextTarget { + fun copyText() + + fun selectAll() + + fun hasSelection(): Boolean + + fun getSelectedText(): String? + + fun getAnchorView(): View? +} + +interface MutableTextTarget : TextTarget { + fun cut() + + fun paste() + + fun isEditable(): Boolean +} diff --git a/actions/src/main/java/com/itsaky/androidide/actions/actionUtils.kt b/actions/src/main/java/org/appdevforall/codeonthego/actions/actionUtils.kt similarity index 79% rename from actions/src/main/java/com/itsaky/androidide/actions/actionUtils.kt rename to actions/src/main/java/org/appdevforall/codeonthego/actions/actionUtils.kt index 1254e58746..12949c725f 100644 --- a/actions/src/main/java/com/itsaky/androidide/actions/actionUtils.kt +++ b/actions/src/main/java/org/appdevforall/codeonthego/actions/actionUtils.kt @@ -15,11 +15,11 @@ * along with AndroidIDE. If not, see . */ -package com.itsaky.androidide.actions +package org.appdevforall.codeonthego.actions import android.content.Context import com.google.android.material.dialog.MaterialAlertDialogBuilder -import com.itsaky.androidide.utils.DialogUtils +import org.appdevforall.codeonthego.utils.DialogUtils import io.github.rosemoe.sora.widget.CodeEditor import java.io.File import java.nio.file.Path @@ -43,17 +43,17 @@ fun ActionData.requireFile(): File = require() fun ActionData.requirePath(): Path { - return requireFile().toPath() +return requireFile().toPath() } fun ActionData.requireEditor(): CodeEditor { - return get(CodeEditor::class.java) - ?: throw IllegalArgumentException("An editor instance is required but none was provided") +return get(CodeEditor::class.java) + ?: throw IllegalArgumentException("An editor instance is required but none was provided") } fun newDialogBuilder(data: ActionData): MaterialAlertDialogBuilder { - val context = data.get(Context::class.java)!! - return DialogUtils.newMaterialDialogBuilder(context) +val context = data.get(Context::class.java)!! +return DialogUtils.newMaterialDialogBuilder(context) } /** @@ -63,15 +63,15 @@ fun newDialogBuilder(data: ActionData): MaterialAlertDialogBuilder { * @return `true` if this [ActionData] has the given [types], `false` otherwise. */ fun ActionData.hasRequiredData(vararg types: Class<*>): Boolean { - for (type in types) { - get(type) ?: return false - } +for (type in types) { + get(type) ?: return false +} - return true +return true } /** Marks this action item as invisible. */ fun ActionItem.markInvisible() { - visible = false - enabled = false +visible = false +enabled = false } diff --git a/actions/src/main/java/org/appdevforall/codeonthego/actions/internal/DefaultActionsRegistry.kt b/actions/src/main/java/org/appdevforall/codeonthego/actions/internal/DefaultActionsRegistry.kt new file mode 100644 index 0000000000..722313bc81 --- /dev/null +++ b/actions/src/main/java/org/appdevforall/codeonthego/actions/internal/DefaultActionsRegistry.kt @@ -0,0 +1,304 @@ +@file:Suppress("ktlint:standard:max-line-length") + +/* + * This file is part of AndroidIDE. + * + * AndroidIDE is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * AndroidIDE is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with AndroidIDE. If not, see . + */ + +package org.appdevforall.codeonthego.actions.internal + +import android.view.Menu +import android.view.MenuItem +import com.google.auto.service.AutoService +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineName +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.launch +import kotlinx.coroutines.plus +import kotlinx.coroutines.withContext +import org.appdevforall.codeonthego.actions.ActionData +import org.appdevforall.codeonthego.actions.ActionItem +import org.appdevforall.codeonthego.actions.ActionMenu +import org.appdevforall.codeonthego.actions.ActionsRegistry +import org.appdevforall.codeonthego.actions.FillMenuParams +import org.appdevforall.codeonthego.actions.OnActionClickListener +import org.appdevforall.codeonthego.actions.locations.CodeActionsMenu +import org.appdevforall.codeonthego.utils.withStopWatch +import org.slf4j.LoggerFactory +import java.util.concurrent.ConcurrentHashMap + +/** + * Default implementation for the [ActionsRegistry] + * + * @author Akash Yadav + */ +@AutoService(ActionsRegistry::class) +class DefaultActionsRegistry : ActionsRegistry() { + private val actions = ConcurrentHashMap>() + private val listeners = HashSet() + + private val actionsCoroutineScope = + CoroutineScope(Dispatchers.Default) + + CoroutineName("DefaultActionsRegistry") + + companion object { + private val log = LoggerFactory.getLogger(DefaultActionsRegistry::class.java) + private const val DEBUG_PREFIX = "ACTION_DEBUG: " + } + + init { + registerAction(CodeActionsMenu) + } + + override fun getActions(location: ActionItem.Location): MutableMap = + actions.getOrPut(location.id) { LinkedHashMap() } + + override fun registerAction(action: ActionItem): Boolean { + val actions = getActions(action.location) + val isUpdating = actions.containsKey(action.id) + log.debug( + "$DEBUG_PREFIX ${if (isUpdating) "Updating" else "Registering"} action '${action.id}' at location '${action.location.id}'. " + + "Current count: ${actions.size}.", + ) + actions.remove(action.id) + actions[action.id] = action + log.debug("$DEBUG_PREFIX Location '${action.location.id}' now has ${actions.size} actions.") + if (actions.size == 3) { + log.debug("$DEBUG_PREFIX readhed the 3 target") + } + return true + } + + override fun unregisterAction(action: ActionItem): Boolean { + val actions = getActions(action.location) + log.debug( + "$DEBUG_PREFIX Unregistering action '${action.id}' from location '${action.location.id}'. " + + "Current count: ${actions.size}.", + ) + val older = actions.remove(action.id) + if (older != null) { + older.destroy() + log.debug("$DEBUG_PREFIX Unregistered '${action.id}'. Location '${action.location.id}' now has ${actions.size} actions.") + return true + } + log.debug("$DEBUG_PREFIX Action '${action.id}' not found at location '${action.location.id}'.") + return false + } + + override fun unregisterAction(id: String): Boolean { + log.debug("$DEBUG_PREFIX Attempting to unregister action with id '$id' from all locations.") + for ((locationId, locations) in this.actions) { + val older = locations.remove(id) + if (older != null) { + older.destroy() + log.debug("$DEBUG_PREFIX Removed action '$id' from location '$locationId'. New count: ${locations.size}.") + return true + } + } + log.debug("$DEBUG_PREFIX Action with id '$id' not found in any location.") + return false + } + + override fun findAction( + location: ActionItem.Location, + id: String, + ): ActionItem? = getActions(location)[id] + + override fun findAction( + location: ActionItem.Location, + itemId: Int, + ): ActionItem? { + for (action in getActions(location)) { + if (action.value.itemId == itemId) { + return action.value + } + } + + return null + } + + override fun clearActions(location: ActionItem.Location) { + val actions = getActions(location) + log.debug("$DEBUG_PREFIX Clearing all ${actions.size} actions from location '${location.id}'.") + actions.forEach { it.value.destroy() } + actions.clear() + log.debug("$DEBUG_PREFIX Location '${location.id}' is now empty.") + } + + override fun clearActionsExceptWhere( + location: ActionItem.Location, + predicate: (ActionItem) -> Boolean, + ) { + val actions = getActions(location) + val initialCount = actions.size + val toRemove = mutableListOf() + + log.debug("$DEBUG_PREFIX Conditionally clearing actions from location '${location.id}'. Initial count: $initialCount.") + + actions.forEach { (key, action) -> + if (!predicate(action)) { + toRemove.add(key) + } + } + + if (toRemove.isNotEmpty()) { + log.debug("$DEBUG_PREFIX Removing ${toRemove.size} actions from location '${location.id}': $toRemove") + toRemove.forEach { key -> + actions[key]?.destroy() + actions.remove(key) + } + log.debug("$DEBUG_PREFIX Location '${location.id}' now has ${actions.size} actions.") + } else { + log.debug("$DEBUG_PREFIX No actions met the removal criteria for location '${location.id}'.") + } + } + + override fun registerActionExecListener(listener: ActionExecListener) { + listeners.add(listener) + } + + override fun unregisterActionExecListener(listener: ActionExecListener) { + listeners.remove(listener) + } + + override fun fillMenu(params: FillMenuParams) { + val (data, location, menu, onClickListener) = params + val actions = getActions(location) + + val sortedActions = actions.values.sortedWith(compareBy({ it.order }, { it.id })) + + for (action in sortedActions) { + action.prepare(data) + + if (!action.visible) { + continue + } + addActionToMenu(menu, action, data, onClickListener) + } + } + + private fun addActionToMenu( + menu: Menu, + action: ActionItem, + data: ActionData, + onClickListener: OnActionClickListener, + ) { + val item: MenuItem = + if (action is ActionMenu) { + val sub = menu.addSubMenu(Menu.NONE, action.itemId, action.order, action.label) + + var shouldBeEnabled = false + for (subItem in action.children) { + subItem.prepare(data) + if (subItem.visible) { + addActionToMenu(sub, subItem, data, onClickListener) + } + + if (action.enabled && subItem.enabled && !shouldBeEnabled) { + shouldBeEnabled = true + } + } + + action.enabled = shouldBeEnabled + sub.item + } else { + menu.add(Menu.NONE, action.itemId, action.order, action.label) + } + + item.isEnabled = action.enabled + + item.contentDescription = action.label + + item.icon = + action.icon?.apply { + colorFilter = action.createColorFilter(data) + alpha = if (action.enabled) 255 else 76 + } + + var showAsAction = action.getShowAsActionFlags(data) + if (showAsAction == -1) { + showAsAction = + if (action.icon != null) { + MenuItem.SHOW_AS_ACTION_IF_ROOM + } else { + MenuItem.SHOW_AS_ACTION_NEVER + } + } + + if (!action.enabled) { + showAsAction = MenuItem.SHOW_AS_ACTION_NEVER + } + + item.setShowAsAction(showAsAction) + + action.createActionView(data)?.let { item.actionView = it } + + if (action !is ActionMenu) { + item.setOnMenuItemClickListener { + onClickListener.onClick(this, action, it, data) + } + } + } + + /** Executes the given action item with the given */ + fun executeAction( + action: ActionItem, + data: ActionData, + ): Job { + val onMainThread = action.requiresUIThread + val context = if (onMainThread) Dispatchers.Main.immediate else Dispatchers.Default + return actionsCoroutineScope + .launch(context) { + val result = + try { + withStopWatch("Action '${action.id}'") { action.execAction(data) } + } catch (e: IllegalArgumentException) { + log.error("An error occurred when performing action '{}'", action.id, e) + return@launch + } + + val post = fun() = + run { + action.postExec(data, result) + notifyActionExec(action, result) + } + + if (onMainThread) { + post() + } else { + withContext(Dispatchers.Main.immediate) { post() } + } + }.also { job -> + job.invokeOnCompletion { cause -> + when (cause) { + null -> log.debug("Action '{}' execution completed.", action.id) + is CancellationException -> log.debug("Action '{}' execution was cancelled.", action.id) + else -> log.debug("Action '{}' execution failed.", action.id, cause) + } + } + } + } + + private fun notifyActionExec( + action: ActionItem, + result: Any, + ) { + for (listener in listeners) { + listener.onExec(action, result) + } + } +} diff --git a/actions/src/main/java/org/appdevforall/codeonthego/actions/locations/CodeActionsMenu.kt b/actions/src/main/java/org/appdevforall/codeonthego/actions/locations/CodeActionsMenu.kt new file mode 100644 index 0000000000..78d6e37536 --- /dev/null +++ b/actions/src/main/java/org/appdevforall/codeonthego/actions/locations/CodeActionsMenu.kt @@ -0,0 +1,52 @@ +/* + * This file is part of AndroidIDE. + * + * AndroidIDE is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * AndroidIDE is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with AndroidIDE. If not, see . + */ + +package org.appdevforall.codeonthego.actions.locations + +import android.content.Context +import android.graphics.drawable.Drawable +import androidx.core.content.ContextCompat +import com.itsaky.androidide.resources.R +import org.appdevforall.codeonthego.actions.ActionData +import org.appdevforall.codeonthego.actions.ActionItem +import org.appdevforall.codeonthego.actions.ActionMenu +import org.appdevforall.codeonthego.idetooltips.TooltipTag + +/** @author Akash Yadav */ +object CodeActionsMenu : ActionMenu { + const val ID = "ide.editor.code.actions" + + override val children: MutableSet = mutableSetOf() + override val id: String = ID + + override var label: String = "Code actions" + override var visible = true + override var enabled: Boolean = true + override var icon: Drawable? = null + + override fun retrieveTooltipTag(isAlternateContext: Boolean) = TooltipTag.EDITOR_TOOLBAR_CODE_ACTIONS + + override var requiresUIThread: Boolean = false + override var location: ActionItem.Location = ActionItem.Location.EDITOR_TEXT_ACTIONS + + override fun prepare(data: ActionData) { + super.prepare(data) + if (icon == null) { + icon = ContextCompat.getDrawable(data[Context::class.java]!!, R.drawable.ic_code) + } + } +} diff --git a/actions/src/test/java/com/itsaky/androidide/actions/ActionTooltipResolutionTest.kt b/actions/src/test/java/org/appdevforall/codeonthego/actions/ActionTooltipResolutionTest.kt similarity index 98% rename from actions/src/test/java/com/itsaky/androidide/actions/ActionTooltipResolutionTest.kt rename to actions/src/test/java/org/appdevforall/codeonthego/actions/ActionTooltipResolutionTest.kt index b1340fbc4b..b21a4a8140 100644 --- a/actions/src/test/java/com/itsaky/androidide/actions/ActionTooltipResolutionTest.kt +++ b/actions/src/test/java/org/appdevforall/codeonthego/actions/ActionTooltipResolutionTest.kt @@ -14,7 +14,7 @@ * You should have received a copy of the GNU General Public License * along with AndroidIDE. If not, see . */ -package com.itsaky.androidide.actions +package org.appdevforall.codeonthego.actions import android.graphics.drawable.Drawable import com.google.common.truth.Truth.assertThat diff --git a/actions/src/test/java/com/itsaky/androidide/actions/SidebarSlotManagerTest.kt b/actions/src/test/java/org/appdevforall/codeonthego/actions/SidebarSlotManagerTest.kt similarity index 92% rename from actions/src/test/java/com/itsaky/androidide/actions/SidebarSlotManagerTest.kt rename to actions/src/test/java/org/appdevforall/codeonthego/actions/SidebarSlotManagerTest.kt index b8c151d309..0c1c4e3aa1 100644 --- a/actions/src/test/java/com/itsaky/androidide/actions/SidebarSlotManagerTest.kt +++ b/actions/src/test/java/org/appdevforall/codeonthego/actions/SidebarSlotManagerTest.kt @@ -1,4 +1,4 @@ -package com.itsaky.androidide.actions +package org.appdevforall.codeonthego.actions import com.google.common.truth.Truth.assertThat import org.junit.After diff --git a/annotation-processors-ksp/src/main/kotlin/com/itsaky/androidide/annotations/ksp/inflater/ViewAdapterIndexGenerator.kt b/annotation-processors-ksp/src/main/kotlin/com/itsaky/androidide/annotations/ksp/inflater/ViewAdapterIndexGenerator.kt deleted file mode 100644 index 261a8b9084..0000000000 --- a/annotation-processors-ksp/src/main/kotlin/com/itsaky/androidide/annotations/ksp/inflater/ViewAdapterIndexGenerator.kt +++ /dev/null @@ -1,280 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.annotations.ksp.inflater - -import androidx.annotation.RequiresApi -import com.google.devtools.ksp.KspExperimental -import com.google.devtools.ksp.getAnnotationsByType -import com.google.devtools.ksp.isAnnotationPresent -import com.google.devtools.ksp.processing.KSPLogger -import com.google.devtools.ksp.symbol.KSAnnotation -import com.google.devtools.ksp.symbol.KSClassDeclaration -import com.google.devtools.ksp.symbol.KSFunctionDeclaration -import com.google.devtools.ksp.symbol.KSType -import com.itsaky.androidide.annotations.inflater.ViewAdapter -import com.itsaky.androidide.annotations.uidesigner.IncludeInDesigner -import com.squareup.javapoet.ClassName -import com.squareup.javapoet.CodeBlock -import com.squareup.javapoet.FieldSpec -import com.squareup.javapoet.JavaFile -import com.squareup.javapoet.MethodSpec -import com.squareup.javapoet.ParameterSpec -import com.squareup.javapoet.ParameterizedTypeName -import com.squareup.javapoet.TypeSpec -import com.squareup.javapoet.WildcardTypeName -import java.io.OutputStream -import java.io.OutputStreamWriter -import java.util.Collections -import javax.lang.model.element.Modifier.FINAL -import javax.lang.model.element.Modifier.PRIVATE -import javax.lang.model.element.Modifier.PUBLIC -import javax.lang.model.element.Modifier.STATIC - -/** - * Generates the ViewAdapterIndex class. - * - * @author Akash Yadav - */ -class ViewAdapterIndexGenerator(private val logger: KSPLogger) { - - private val indexClassBuilder = - TypeSpec.classBuilder(INDEX_CLASS_NAME) - .addModifiers(PUBLIC, FINAL) - .addSuperinterface(viewAdapterInterface) - private val indexAddStatements = CodeBlock.builder() - - fun init() { - val adapterType = - ParameterizedTypeName.get( - ClassName.get(ADAPTER_BASE_CLASS_PCK, ADAPTER_BASE_CLASS_NAME), - WildcardTypeName.subtypeOf(viewClass) - ) - val mapOfStringToViewAdapter = - ParameterizedTypeName.get( - ClassName.get(Map::class.java), - ClassName.get(String::class.java), - adapterType - ) - indexClassBuilder.addField( - FieldSpec.builder(mapOfStringToViewAdapter, INDEX_MAP_FIELD, PRIVATE, STATIC, FINAL).build() - ) - - indexAddStatements.addStatement( - "final var adapters = new \$T()", - ParameterizedTypeName.get( - ClassName.get(HashMap::class.java), - ClassName.get(String::class.java), - adapterType - ) - ) - - // addPrivateConstructor(indexClassBuilder) - - val indexImpl = ClassName.get(INDEX_PACKAGE_NAME, INDEX_CLASS_NAME) - indexClassBuilder.addField( - FieldSpec.builder(indexImpl, "INSTANCE", PUBLIC, STATIC, FINAL) - .initializer("new \$T()", indexImpl) - .build() - ) - - indexClassBuilder.addMethod( - MethodSpec.methodBuilder("getAdapter") - .addAnnotation(Override::class.java) - .addAnnotation(ClassName.get("androidx.annotation", "Nullable")) - .addModifiers(PUBLIC) - .addParameter(String::class.java, "view", FINAL) - .returns(adapterType) - .addStatement("var adapter = \$L.get(\$L)", INDEX_MAP_FIELD, "view") - .beginControlFlow("if (adapter == null)") - .addStatement("adapter = \$L.get(\$S)", INDEX_MAP_FIELD, VIEW_CLASS) - .endControlFlow() - .addStatement("return adapter") - .build() - ) - - indexClassBuilder.addMethod( - MethodSpec.methodBuilder("getViewAdapter") - .addAnnotation(Override::class.java) - .addAnnotation(ClassName.get("androidx.annotation", "Nullable")) - .addModifiers(PUBLIC) - .addParameter(String::class.java, "view", FINAL) - .returns(adapterType) - .addStatement("return \$L.get(\$L)", INDEX_MAP_FIELD, "view") - .build() - ) - - val listOfViewAdapters = - ParameterizedTypeName.get(ClassName.get(java.util.List::class.java), adapterType) - val mapOfGroupToListOfViewAdapter = - ParameterizedTypeName.get( - ClassName.get(Map::class.java), - ClassName.get(IncludeInDesigner.Group::class.java), - listOfViewAdapters - ) - - indexClassBuilder.addField( - FieldSpec.builder( - mapOfGroupToListOfViewAdapter, - INDEX_PROVIDER_MAP_FIELD, - PRIVATE, - STATIC, - FINAL - ) - .build() - ) - - indexAddStatements.addStatement( - "final var providers = new \$T()", - ParameterizedTypeName.get( - ClassName.get(HashMap::class.java), - ClassName.get(IncludeInDesigner.Group::class.java), - listOfViewAdapters - ) - ) - - val nonNull = ClassName.get("androidx.annotation", "NonNull") - val groupParam = - ParameterSpec.builder(IncludeInDesigner.Group::class.java, "group", FINAL).build() - - indexClassBuilder.addMethod( - MethodSpec.methodBuilder("getWidgetProviders") - .addAnnotation(Override::class.java) - .addAnnotation(nonNull) - .addModifiers(PUBLIC) - .returns(listOfViewAdapters) - .addParameter(groupParam) - .addStatement("return \$L.get(group)", INDEX_PROVIDER_MAP_FIELD) - .build() - ) - } - - @OptIn(KspExperimental::class) - fun addViewAdapter(sym: KSClassDeclaration): Boolean { - val block = CodeBlock.builder() - - val viewAdapter = - sym.getKSAnnotationsByType(ViewAdapter::class).iterator().run { - val result = next() - if (hasNext()) { - logger.error("${ViewAdapter::class.simpleName} can only be applied once.", sym) - return false - } - result - } - - val includeInDesigner = - if (sym.isAnnotationPresent(IncludeInDesigner::class)) { - sym.getAnnotationsByType(IncludeInDesigner::class).iterator().run { - val result = next() - if (hasNext()) { - logger.error("${IncludeInDesigner::class.simpleName} can only be applied once.", sym) - return false - } - result - } - } else null - - val requiresApi = - if (sym.isAnnotationPresent(RequiresApi::class)) - sym.getAnnotationsByType(RequiresApi::class).iterator().next() - else null - - val viewName = getViewName(viewAdapter) - val moduleNs = getModuleNs(viewAdapter) - - val adapterTypeName = ClassName.get(sym.packageName.asString(), sym.simpleName.asString()) - val viewTypeName = - ClassName.get(viewName.substringBeforeLast('.'), viewName.substringAfterLast('.')) - - requiresApi?.let { annotation -> - val api = if (annotation.value == 1) annotation.api else annotation.value - val androidBuild = ClassName.get("android.os", "Build") - block.beginControlFlow("if(\$T.VERSION.SDK_INT >= \$L)", androidBuild, api) - } - - block.addStatement( - "final var adapter = new \$T()", - ParameterizedTypeName.get(adapterTypeName, viewTypeName) - ) - - block.addStatement("adapter.\$L(\$S)", METHOD_SET_MODULE, moduleNs) - block.addStatement("adapters.put(\$S, adapter)", viewName) - - if (includeInDesigner != null) { - assertOverridesCreateWidget(sym) - block.addStatement( - "providers.computeIfAbsent(\$T.\$L, g -> new \$T<>()).add(adapter)", - ClassName.get(IncludeInDesigner.Group::class.java), - includeInDesigner.group, - ClassName.get(java.util.ArrayList::class.java) - ) - } - - requiresApi?.let { block.endControlFlow() } - - indexAddStatements.add("{\n") - indexAddStatements.indent() - indexAddStatements.add(block.build()) - indexAddStatements.unindent() - indexAddStatements.add("}\n") - - return true - } - - fun generate(out: OutputStream) { - val javaCollections = ClassName.get(Collections::class.java) - - indexAddStatements.addStatement( - "\$L = \$T.unmodifiableMap(adapters)", - INDEX_MAP_FIELD, - javaCollections - ) - - indexAddStatements.addStatement( - "\$L = \$T.unmodifiableMap(providers)", - INDEX_PROVIDER_MAP_FIELD, - javaCollections - ) - - indexClassBuilder.addStaticBlock(indexAddStatements.build()) - - OutputStreamWriter(out).use { - val file = JavaFile.builder(INDEX_PACKAGE_NAME, indexClassBuilder.build()) - file.build().writeTo(it) - } - } - - private fun assertOverridesCreateWidget(sym: KSClassDeclaration): Boolean { - return sym.declarations - .filter { it is KSFunctionDeclaration } - .find { ADAPTER_FUNC_CREATE_WIDGET == it.simpleName.asString() } != null - } - - private fun getViewName(viewAdapter: KSAnnotation): String { - return getViewType(viewAdapter).declaration.qualifiedName!!.asString() - } - - private fun getViewType(viewAdapter: KSAnnotation) = - (getAnnotationArg(viewAdapter, "forView") as KSType) - - private fun getModuleNs(viewAdapter: KSAnnotation) = - (getAnnotationArg(viewAdapter, "moduleNamespace") as String) - - private fun getAnnotationArg(viewAdapter: KSAnnotation, arg: String) = - viewAdapter.arguments.first { it.name!!.asString() == arg }.value -} diff --git a/annotation-processors-ksp/src/main/kotlin/com/itsaky/androidide/annotations/ksp/inflater/ViewAdapterSymbolProcessor.kt b/annotation-processors-ksp/src/main/kotlin/com/itsaky/androidide/annotations/ksp/inflater/ViewAdapterSymbolProcessor.kt deleted file mode 100644 index 18cd3676e3..0000000000 --- a/annotation-processors-ksp/src/main/kotlin/com/itsaky/androidide/annotations/ksp/inflater/ViewAdapterSymbolProcessor.kt +++ /dev/null @@ -1,111 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.annotations.ksp.inflater - -import com.google.devtools.ksp.containingFile -import com.google.devtools.ksp.isOpen -import com.google.devtools.ksp.processing.CodeGenerator -import com.google.devtools.ksp.processing.Dependencies -import com.google.devtools.ksp.processing.KSPLogger -import com.google.devtools.ksp.processing.Resolver -import com.google.devtools.ksp.processing.SymbolProcessor -import com.google.devtools.ksp.symbol.KSAnnotated -import com.google.devtools.ksp.symbol.KSClassDeclaration -import com.google.devtools.ksp.symbol.KSFile -import com.itsaky.androidide.annotations.inflater.ViewAdapter - -/** - * [SymbolProcessor] for [ViewAdapter] annotations. - * - * @author Akash Yadav - */ -class ViewAdapterSymbolProcessor( - private val codeGenerator: CodeGenerator, - private val logger: KSPLogger -) : SymbolProcessor { - - private val generator = ViewAdapterIndexGenerator(logger) - - init { - generator.init() - } - - override fun process(resolver: Resolver): List { - val symbols = resolver.getSymbolsWithAnnotation(ViewAdapter::class.java.name) - - if (!symbols.iterator().hasNext()) { - return emptyList() - } - - val unprocessed = mutableListOf() - val files = mutableListOf() - symbols.forEach { - it.containingFile?.also { file -> files.add(file) } - if (!process(it)) { - unprocessed.add(it) - } - } - - val file = - codeGenerator.createNewFile( - Dependencies(true, *files.toTypedArray()), - INDEX_PACKAGE_NAME, - INDEX_CLASS_NAME, - "java" - ) - - generator.generate(file) - - file.flush() - file.close() - - return unprocessed - } - - private fun process(sym: KSAnnotated): Boolean { - if (sym !is KSClassDeclaration) { - logger.error("${ViewAdapter::class} must be applied to a class.", sym) - return false - } - - if (sym.parent !is KSFile) { - logger.error( - "${ViewAdapter::class} must be applied to a top level class. (${sym.parent})", - sym - ) - return false - } - - if (sym.primaryConstructor?.parameters?.size != 0) { - logger.error("A view adapter must have a single primary constructor", sym) - return false - } - - if (sym.typeParameters.size != 1) { - logger.error("A view adapter must have exactly one type parameter", sym) - return false - } - - if (!sym.isOpen()) { - logger.error("A view adapter implementation must be open.", sym) - return false - } - - return generator.addViewAdapter(sym) - } -} diff --git a/annotation-processors-ksp/src/main/kotlin/com/itsaky/androidide/annotations/ksp/inflater/utils.kt b/annotation-processors-ksp/src/main/kotlin/com/itsaky/androidide/annotations/ksp/inflater/utils.kt deleted file mode 100644 index bfe69e595d..0000000000 --- a/annotation-processors-ksp/src/main/kotlin/com/itsaky/androidide/annotations/ksp/inflater/utils.kt +++ /dev/null @@ -1,42 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.annotations.ksp.inflater - -import com.squareup.javapoet.ClassName - -val ANDROID_VIEW_PCK = "android.view" -val ANDROID_VIEW_CLASS = "View" -val VIEW_CLASS = "$ANDROID_VIEW_PCK.$ANDROID_VIEW_CLASS" - -const val ADAPTER_BASE_CLASS_PCK = "com.itsaky.androidide.inflater" -const val ADAPTER_BASE_CLASS_NAME = "IViewAdapter" -const val ADAPTER_BASE_CLASS = "$ADAPTER_BASE_CLASS_PCK.$ADAPTER_BASE_CLASS_NAME" -const val ADAPTER_FUNC_CREATE_WIDGET = "createUiWidgets" - -const val INDEX_PACKAGE_NAME = "com.itsaky.androidide.inflater.internal" -const val INDEX_CLASS_NAME = "ViewAdapterIndexImpl" -const val INDEX_MAP_FIELD = "adapterMap" -const val INDEX_PROVIDER_MAP_FIELD = "widgetProviders" - -const val METHOD_SET_SUPERCLASS_HIERARCHY = "setSuperclassHierarchy" -const val METHOD_SET_MODULE = "setModuleNamespace" - -val viewAdapter = ClassName.get(ADAPTER_BASE_CLASS_PCK, ADAPTER_BASE_CLASS_NAME) -val viewAdapterInterface: ClassName = - ClassName.get("com.itsaky.androidide.inflater", "IViewAdapterIndex") -val viewClass = ClassName.get(ANDROID_VIEW_PCK, ANDROID_VIEW_CLASS) \ No newline at end of file diff --git a/annotation-processors-ksp/src/main/kotlin/org/appdevforall/codeonthego/annotations/ksp/inflater/ViewAdapterIndexGenerator.kt b/annotation-processors-ksp/src/main/kotlin/org/appdevforall/codeonthego/annotations/ksp/inflater/ViewAdapterIndexGenerator.kt new file mode 100644 index 0000000000..ebf78e68b7 --- /dev/null +++ b/annotation-processors-ksp/src/main/kotlin/org/appdevforall/codeonthego/annotations/ksp/inflater/ViewAdapterIndexGenerator.kt @@ -0,0 +1,287 @@ +/* + * This file is part of AndroidIDE. + * + * AndroidIDE is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * AndroidIDE is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with AndroidIDE. If not, see . + */ + +package org.appdevforall.codeonthego.annotations.ksp.inflater + +import androidx.annotation.RequiresApi +import com.google.devtools.ksp.KspExperimental +import com.google.devtools.ksp.getAnnotationsByType +import com.google.devtools.ksp.isAnnotationPresent +import com.google.devtools.ksp.processing.KSPLogger +import com.google.devtools.ksp.symbol.KSAnnotation +import com.google.devtools.ksp.symbol.KSClassDeclaration +import com.google.devtools.ksp.symbol.KSFunctionDeclaration +import com.google.devtools.ksp.symbol.KSType +import com.squareup.javapoet.ClassName +import com.squareup.javapoet.CodeBlock +import com.squareup.javapoet.FieldSpec +import com.squareup.javapoet.JavaFile +import com.squareup.javapoet.MethodSpec +import com.squareup.javapoet.ParameterSpec +import com.squareup.javapoet.ParameterizedTypeName +import com.squareup.javapoet.TypeSpec +import com.squareup.javapoet.WildcardTypeName +import org.appdevforall.codeonthego.annotations.inflater.ViewAdapter +import org.appdevforall.codeonthego.annotations.uidesigner.IncludeInDesigner +import java.io.OutputStream +import java.io.OutputStreamWriter +import java.util.Collections +import javax.lang.model.element.Modifier.FINAL +import javax.lang.model.element.Modifier.PRIVATE +import javax.lang.model.element.Modifier.PUBLIC +import javax.lang.model.element.Modifier.STATIC + +/** + * Generates the ViewAdapterIndex class. + * + * @author Akash Yadav + */ +class ViewAdapterIndexGenerator( + private val logger: KSPLogger, +) { + private val indexClassBuilder = + TypeSpec + .classBuilder(INDEX_CLASS_NAME) + .addModifiers(PUBLIC, FINAL) + .addSuperinterface(viewAdapterInterface) + private val indexAddStatements = CodeBlock.builder() + + fun init() { + val adapterType = + ParameterizedTypeName.get( + ClassName.get(ADAPTER_BASE_CLASS_PCK, ADAPTER_BASE_CLASS_NAME), + WildcardTypeName.subtypeOf(viewClass), + ) + val mapOfStringToViewAdapter = + ParameterizedTypeName.get( + ClassName.get(Map::class.java), + ClassName.get(String::class.java), + adapterType, + ) + indexClassBuilder.addField( + FieldSpec.builder(mapOfStringToViewAdapter, INDEX_MAP_FIELD, PRIVATE, STATIC, FINAL).build(), + ) + + indexAddStatements.addStatement( + "final var adapters = new \$T()", + ParameterizedTypeName.get( + ClassName.get(HashMap::class.java), + ClassName.get(String::class.java), + adapterType, + ), + ) + + // addPrivateConstructor(indexClassBuilder) + + val indexImpl = ClassName.get(INDEX_PACKAGE_NAME, INDEX_CLASS_NAME) + indexClassBuilder.addField( + FieldSpec + .builder(indexImpl, "INSTANCE", PUBLIC, STATIC, FINAL) + .initializer("new \$T()", indexImpl) + .build(), + ) + + indexClassBuilder.addMethod( + MethodSpec + .methodBuilder("getAdapter") + .addAnnotation(Override::class.java) + .addAnnotation(ClassName.get("androidx.annotation", "Nullable")) + .addModifiers(PUBLIC) + .addParameter(String::class.java, "view", FINAL) + .returns(adapterType) + .addStatement("var adapter = \$L.get(\$L)", INDEX_MAP_FIELD, "view") + .beginControlFlow("if (adapter == null)") + .addStatement("adapter = \$L.get(\$S)", INDEX_MAP_FIELD, VIEW_CLASS) + .endControlFlow() + .addStatement("return adapter") + .build(), + ) + + indexClassBuilder.addMethod( + MethodSpec + .methodBuilder("getViewAdapter") + .addAnnotation(Override::class.java) + .addAnnotation(ClassName.get("androidx.annotation", "Nullable")) + .addModifiers(PUBLIC) + .addParameter(String::class.java, "view", FINAL) + .returns(adapterType) + .addStatement("return \$L.get(\$L)", INDEX_MAP_FIELD, "view") + .build(), + ) + + val listOfViewAdapters = + ParameterizedTypeName.get(ClassName.get(java.util.List::class.java), adapterType) + val mapOfGroupToListOfViewAdapter = + ParameterizedTypeName.get( + ClassName.get(Map::class.java), + ClassName.get(IncludeInDesigner.Group::class.java), + listOfViewAdapters, + ) + + indexClassBuilder.addField( + FieldSpec + .builder( + mapOfGroupToListOfViewAdapter, + INDEX_PROVIDER_MAP_FIELD, + PRIVATE, + STATIC, + FINAL, + ).build(), + ) + + indexAddStatements.addStatement( + "final var providers = new \$T()", + ParameterizedTypeName.get( + ClassName.get(HashMap::class.java), + ClassName.get(IncludeInDesigner.Group::class.java), + listOfViewAdapters, + ), + ) + + val nonNull = ClassName.get("androidx.annotation", "NonNull") + val groupParam = + ParameterSpec.builder(IncludeInDesigner.Group::class.java, "group", FINAL).build() + + indexClassBuilder.addMethod( + MethodSpec + .methodBuilder("getWidgetProviders") + .addAnnotation(Override::class.java) + .addAnnotation(nonNull) + .addModifiers(PUBLIC) + .returns(listOfViewAdapters) + .addParameter(groupParam) + .addStatement("return \$L.get(group)", INDEX_PROVIDER_MAP_FIELD) + .build(), + ) + } + + @OptIn(KspExperimental::class) + fun addViewAdapter(sym: KSClassDeclaration): Boolean { + val block = CodeBlock.builder() + + val viewAdapter = + sym.getKSAnnotationsByType(ViewAdapter::class).iterator().run { + val result = next() + if (hasNext()) { + logger.error("${ViewAdapter::class.simpleName} can only be applied once.", sym) + return false + } + result + } + + val includeInDesigner = + if (sym.isAnnotationPresent(IncludeInDesigner::class)) { + sym.getAnnotationsByType(IncludeInDesigner::class).iterator().run { + val result = next() + if (hasNext()) { + logger.error("${IncludeInDesigner::class.simpleName} can only be applied once.", sym) + return false + } + result + } + } else { + null + } + + val requiresApi = + if (sym.isAnnotationPresent(RequiresApi::class)) { + sym.getAnnotationsByType(RequiresApi::class).iterator().next() + } else { + null + } + + val viewName = getViewName(viewAdapter) + val moduleNs = getModuleNs(viewAdapter) + + val adapterTypeName = ClassName.get(sym.packageName.asString(), sym.simpleName.asString()) + val viewTypeName = + ClassName.get(viewName.substringBeforeLast('.'), viewName.substringAfterLast('.')) + + requiresApi?.let { annotation -> + val api = if (annotation.value == 1) annotation.api else annotation.value + val androidBuild = ClassName.get("android.os", "Build") + block.beginControlFlow("if(\$T.VERSION.SDK_INT >= \$L)", androidBuild, api) + } + + block.addStatement( + "final var adapter = new \$T()", + ParameterizedTypeName.get(adapterTypeName, viewTypeName), + ) + + block.addStatement("adapter.\$L(\$S)", METHOD_SET_MODULE, moduleNs) + block.addStatement("adapters.put(\$S, adapter)", viewName) + + if (includeInDesigner != null) { + assertOverridesCreateWidget(sym) + block.addStatement( + "providers.computeIfAbsent(\$T.\$L, g -> new \$T<>()).add(adapter)", + ClassName.get(IncludeInDesigner.Group::class.java), + includeInDesigner.group, + ClassName.get(java.util.ArrayList::class.java), + ) + } + + requiresApi?.let { block.endControlFlow() } + + indexAddStatements.add("{\n") + indexAddStatements.indent() + indexAddStatements.add(block.build()) + indexAddStatements.unindent() + indexAddStatements.add("}\n") + + return true + } + + fun generate(out: OutputStream) { + val javaCollections = ClassName.get(Collections::class.java) + + indexAddStatements.addStatement( + "\$L = \$T.unmodifiableMap(adapters)", + INDEX_MAP_FIELD, + javaCollections, + ) + + indexAddStatements.addStatement( + "\$L = \$T.unmodifiableMap(providers)", + INDEX_PROVIDER_MAP_FIELD, + javaCollections, + ) + + indexClassBuilder.addStaticBlock(indexAddStatements.build()) + + OutputStreamWriter(out).use { + val file = JavaFile.builder(INDEX_PACKAGE_NAME, indexClassBuilder.build()) + file.build().writeTo(it) + } + } + + private fun assertOverridesCreateWidget(sym: KSClassDeclaration): Boolean = + sym.declarations + .filter { it is KSFunctionDeclaration } + .find { ADAPTER_FUNC_CREATE_WIDGET == it.simpleName.asString() } != null + + private fun getViewName(viewAdapter: KSAnnotation): String = getViewType(viewAdapter).declaration.qualifiedName!!.asString() + + private fun getViewType(viewAdapter: KSAnnotation) = (getAnnotationArg(viewAdapter, "forView") as KSType) + + private fun getModuleNs(viewAdapter: KSAnnotation) = (getAnnotationArg(viewAdapter, "moduleNamespace") as String) + + private fun getAnnotationArg( + viewAdapter: KSAnnotation, + arg: String, + ) = viewAdapter.arguments.first { it.name!!.asString() == arg }.value +} diff --git a/annotation-processors-ksp/src/main/kotlin/org/appdevforall/codeonthego/annotations/ksp/inflater/ViewAdapterSymbolProcessor.kt b/annotation-processors-ksp/src/main/kotlin/org/appdevforall/codeonthego/annotations/ksp/inflater/ViewAdapterSymbolProcessor.kt new file mode 100644 index 0000000000..24ffb5511c --- /dev/null +++ b/annotation-processors-ksp/src/main/kotlin/org/appdevforall/codeonthego/annotations/ksp/inflater/ViewAdapterSymbolProcessor.kt @@ -0,0 +1,110 @@ +/* + * This file is part of AndroidIDE. + * + * AndroidIDE is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * AndroidIDE is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with AndroidIDE. If not, see . + */ + +package org.appdevforall.codeonthego.annotations.ksp.inflater + +import com.google.devtools.ksp.containingFile +import com.google.devtools.ksp.isOpen +import com.google.devtools.ksp.processing.CodeGenerator +import com.google.devtools.ksp.processing.Dependencies +import com.google.devtools.ksp.processing.KSPLogger +import com.google.devtools.ksp.processing.Resolver +import com.google.devtools.ksp.processing.SymbolProcessor +import com.google.devtools.ksp.symbol.KSAnnotated +import com.google.devtools.ksp.symbol.KSClassDeclaration +import com.google.devtools.ksp.symbol.KSFile +import org.appdevforall.codeonthego.annotations.inflater.ViewAdapter + +/** + * [SymbolProcessor] for [ViewAdapter] annotations. + * + * @author Akash Yadav + */ +class ViewAdapterSymbolProcessor( + private val codeGenerator: CodeGenerator, + private val logger: KSPLogger, +) : SymbolProcessor { + private val generator = ViewAdapterIndexGenerator(logger) + + init { + generator.init() + } + + override fun process(resolver: Resolver): List { + val symbols = resolver.getSymbolsWithAnnotation(ViewAdapter::class.java.name) + + if (!symbols.iterator().hasNext()) { + return emptyList() + } + + val unprocessed = mutableListOf() + val files = mutableListOf() + symbols.forEach { + it.containingFile?.also { file -> files.add(file) } + if (!process(it)) { + unprocessed.add(it) + } + } + + val file = + codeGenerator.createNewFile( + Dependencies(true, *files.toTypedArray()), + INDEX_PACKAGE_NAME, + INDEX_CLASS_NAME, + "java", + ) + + generator.generate(file) + + file.flush() + file.close() + + return unprocessed + } + + private fun process(sym: KSAnnotated): Boolean { + if (sym !is KSClassDeclaration) { + logger.error("${ViewAdapter::class} must be applied to a class.", sym) + return false + } + + if (sym.parent !is KSFile) { + logger.error( + "${ViewAdapter::class} must be applied to a top level class. (${sym.parent})", + sym, + ) + return false + } + + if (sym.primaryConstructor?.parameters?.size != 0) { + logger.error("A view adapter must have a single primary constructor", sym) + return false + } + + if (sym.typeParameters.size != 1) { + logger.error("A view adapter must have exactly one type parameter", sym) + return false + } + + if (!sym.isOpen()) { + logger.error("A view adapter implementation must be open.", sym) + return false + } + + return generator.addViewAdapter(sym) + } +} diff --git a/annotation-processors-ksp/src/main/kotlin/com/itsaky/androidide/annotations/ksp/inflater/ViewAdapterSymbolProcessorProvider.kt b/annotation-processors-ksp/src/main/kotlin/org/appdevforall/codeonthego/annotations/ksp/inflater/ViewAdapterSymbolProcessorProvider.kt similarity index 77% rename from annotation-processors-ksp/src/main/kotlin/com/itsaky/androidide/annotations/ksp/inflater/ViewAdapterSymbolProcessorProvider.kt rename to annotation-processors-ksp/src/main/kotlin/org/appdevforall/codeonthego/annotations/ksp/inflater/ViewAdapterSymbolProcessorProvider.kt index c29c00c057..d27cb74b84 100644 --- a/annotation-processors-ksp/src/main/kotlin/com/itsaky/androidide/annotations/ksp/inflater/ViewAdapterSymbolProcessorProvider.kt +++ b/annotation-processors-ksp/src/main/kotlin/org/appdevforall/codeonthego/annotations/ksp/inflater/ViewAdapterSymbolProcessorProvider.kt @@ -15,7 +15,7 @@ * along with AndroidIDE. If not, see . */ -package com.itsaky.androidide.annotations.ksp.inflater +package org.appdevforall.codeonthego.annotations.ksp.inflater import com.google.devtools.ksp.processing.SymbolProcessor import com.google.devtools.ksp.processing.SymbolProcessorEnvironment @@ -23,13 +23,11 @@ import com.google.devtools.ksp.processing.SymbolProcessorProvider /** * [SymbolProcessorProvider] implementation for - * [ViewAdapter][com.itsaky.androidide.annotations.inflater.ViewAdapter] annotation. + * [ViewAdapter][org.appdevforall.codeonthego.annotations.inflater.ViewAdapter] annotation. * * @author Akash Yadav */ class ViewAdapterSymbolProcessorProvider : SymbolProcessorProvider { - - override fun create(environment: SymbolProcessorEnvironment): SymbolProcessor { - return ViewAdapterSymbolProcessor(environment.codeGenerator, environment.logger) - } + override fun create(environment: SymbolProcessorEnvironment): SymbolProcessor = + ViewAdapterSymbolProcessor(environment.codeGenerator, environment.logger) } diff --git a/annotation-processors-ksp/src/main/kotlin/com/itsaky/androidide/annotations/ksp/inflater/kspUtils.kt b/annotation-processors-ksp/src/main/kotlin/org/appdevforall/codeonthego/annotations/ksp/inflater/kspUtils.kt similarity index 77% rename from annotation-processors-ksp/src/main/kotlin/com/itsaky/androidide/annotations/ksp/inflater/kspUtils.kt rename to annotation-processors-ksp/src/main/kotlin/org/appdevforall/codeonthego/annotations/ksp/inflater/kspUtils.kt index 7d5100273d..7d9f93c354 100644 --- a/annotation-processors-ksp/src/main/kotlin/com/itsaky/androidide/annotations/ksp/inflater/kspUtils.kt +++ b/annotation-processors-ksp/src/main/kotlin/org/appdevforall/codeonthego/annotations/ksp/inflater/kspUtils.kt @@ -15,15 +15,15 @@ * along with AndroidIDE. If not, see . */ -package com.itsaky.androidide.annotations.ksp.inflater +package org.appdevforall.codeonthego.annotations.ksp.inflater import com.google.devtools.ksp.symbol.KSAnnotated import com.google.devtools.ksp.symbol.KSAnnotation import kotlin.reflect.KClass fun KSAnnotated.getKSAnnotationsByType(annotationKClass: KClass): Sequence { - return this.annotations.filter { - it.shortName.getShortName() == annotationKClass.simpleName && it.annotationType.resolve().declaration - .qualifiedName?.asString() == annotationKClass.qualifiedName - } -} \ No newline at end of file +return this.annotations.filter { + it.shortName.getShortName() == annotationKClass.simpleName && it.annotationType.resolve().declaration + .qualifiedName?.asString() == annotationKClass.qualifiedName +} +} diff --git a/annotation-processors-ksp/src/main/kotlin/org/appdevforall/codeonthego/annotations/ksp/inflater/utils.kt b/annotation-processors-ksp/src/main/kotlin/org/appdevforall/codeonthego/annotations/ksp/inflater/utils.kt new file mode 100644 index 0000000000..003f557839 --- /dev/null +++ b/annotation-processors-ksp/src/main/kotlin/org/appdevforall/codeonthego/annotations/ksp/inflater/utils.kt @@ -0,0 +1,42 @@ +/* + * This file is part of AndroidIDE. + * + * AndroidIDE is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * AndroidIDE is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with AndroidIDE. If not, see . + */ + +package org.appdevforall.codeonthego.annotations.ksp.inflater + +import com.squareup.javapoet.ClassName + +val ANDROID_VIEW_PCK = "android.view" +val ANDROID_VIEW_CLASS = "View" +val VIEW_CLASS = "$ANDROID_VIEW_PCK.$ANDROID_VIEW_CLASS" + +const val ADAPTER_BASE_CLASS_PCK = "org.appdevforall.codeonthego.inflater" +const val ADAPTER_BASE_CLASS_NAME = "IViewAdapter" +const val ADAPTER_BASE_CLASS = "$ADAPTER_BASE_CLASS_PCK.$ADAPTER_BASE_CLASS_NAME" +const val ADAPTER_FUNC_CREATE_WIDGET = "createUiWidgets" + +const val INDEX_PACKAGE_NAME = "org.appdevforall.codeonthego.inflater.internal" +const val INDEX_CLASS_NAME = "ViewAdapterIndexImpl" +const val INDEX_MAP_FIELD = "adapterMap" +const val INDEX_PROVIDER_MAP_FIELD = "widgetProviders" + +const val METHOD_SET_SUPERCLASS_HIERARCHY = "setSuperclassHierarchy" +const val METHOD_SET_MODULE = "setModuleNamespace" + +val viewAdapter = ClassName.get(ADAPTER_BASE_CLASS_PCK, ADAPTER_BASE_CLASS_NAME) +val viewAdapterInterface: ClassName = +ClassName.get("org.appdevforall.codeonthego.inflater", "IViewAdapterIndex") +val viewClass = ClassName.get(ANDROID_VIEW_PCK, ANDROID_VIEW_CLASS) diff --git a/annotation-processors-ksp/src/main/resources/META-INF/services/com.google.devtools.ksp.processing.SymbolProcessorProvider b/annotation-processors-ksp/src/main/resources/META-INF/services/com.google.devtools.ksp.processing.SymbolProcessorProvider index 004759fc87..678dbaf660 100644 --- a/annotation-processors-ksp/src/main/resources/META-INF/services/com.google.devtools.ksp.processing.SymbolProcessorProvider +++ b/annotation-processors-ksp/src/main/resources/META-INF/services/com.google.devtools.ksp.processing.SymbolProcessorProvider @@ -15,4 +15,4 @@ # along with AndroidIDE. If not, see . # -com.itsaky.androidide.annotations.ksp.inflater.ViewAdapterSymbolProcessorProvider \ No newline at end of file +org.appdevforall.codeonthego.annotations.ksp.inflater.ViewAdapterSymbolProcessorProvider \ No newline at end of file diff --git a/annotation-processors/src/main/java/com/itsaky/androidide/annotations/EventBusAnnotationProcessor.java b/annotation-processors/src/main/java/com/itsaky/androidide/annotations/EventBusAnnotationProcessor.java deleted file mode 100644 index 7504108bbe..0000000000 --- a/annotation-processors/src/main/java/com/itsaky/androidide/annotations/EventBusAnnotationProcessor.java +++ /dev/null @@ -1,446 +0,0 @@ -/* - * Copyright (C) 2012-2016 Markus Junginger, greenrobot (http://greenrobot.org) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.itsaky.androidide.annotations; - -import com.google.auto.service.AutoService; -import javax.annotation.processing.Processor; -import net.ltgt.gradle.incap.IncrementalAnnotationProcessor; - -import org.greenrobot.eventbus.Subscribe; -import org.greenrobot.eventbus.ThreadMode; - -import java.io.BufferedWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import javax.annotation.processing.AbstractProcessor; -import javax.annotation.processing.Messager; -import javax.annotation.processing.RoundEnvironment; -import javax.annotation.processing.SupportedAnnotationTypes; -import javax.annotation.processing.SupportedOptions; -import javax.lang.model.SourceVersion; -import javax.lang.model.element.Element; -import javax.lang.model.element.ExecutableElement; -import javax.lang.model.element.Modifier; -import javax.lang.model.element.PackageElement; -import javax.lang.model.element.TypeElement; -import javax.lang.model.element.VariableElement; -import javax.lang.model.type.DeclaredType; -import javax.lang.model.type.TypeKind; -import javax.lang.model.type.TypeMirror; -import javax.lang.model.type.TypeVariable; -import javax.tools.Diagnostic; -import javax.tools.JavaFileObject; - -import de.greenrobot.common.ListMap; - - -import static net.ltgt.gradle.incap.IncrementalAnnotationProcessorType.AGGREGATING; - -/** - * Is an aggregating processor as it writes a single file, the subscriber index file, - * based on found elements with the @Subscriber annotation. - */ -@SupportedAnnotationTypes("org.greenrobot.eventbus.Subscribe") -@SupportedOptions(value = {"eventBusIndex", "verbose"}) -@IncrementalAnnotationProcessor(AGGREGATING) -@AutoService(Processor.class) -public class EventBusAnnotationProcessor extends AbstractProcessor { - public static final String OPTION_EVENT_BUS_INDEX = "eventBusIndex"; - public static final String OPTION_VERBOSE = "verbose"; - - /** Found subscriber methods for a class (without superclasses). */ - private final ListMap methodsByClass = new ListMap<>(); - private final Set classesToSkip = new HashSet<>(); - - private boolean writerRoundDone; - private int round; - private boolean verbose; - - @Override - public SourceVersion getSupportedSourceVersion() { - return SourceVersion.latest(); - } - - @Override - public boolean process(Set annotations, RoundEnvironment env) { - Messager messager = processingEnv.getMessager(); - try { - String index = processingEnv.getOptions().get(OPTION_EVENT_BUS_INDEX); - if (index == null) { - messager.printMessage(Diagnostic.Kind.ERROR, "No option " + OPTION_EVENT_BUS_INDEX + - " passed to annotation processor"); - return false; - } - verbose = Boolean.parseBoolean(processingEnv.getOptions().get(OPTION_VERBOSE)); - int lastPeriod = index.lastIndexOf('.'); - String indexPackage = lastPeriod != -1 ? index.substring(0, lastPeriod) : null; - - round++; - if (verbose) { - messager.printMessage(Diagnostic.Kind.NOTE, "Processing round " + round + ", new annotations: " + - !annotations.isEmpty() + ", processingOver: " + env.processingOver()); - } - if (env.processingOver()) { - if (!annotations.isEmpty()) { - messager.printMessage(Diagnostic.Kind.ERROR, - "Unexpected processing state: annotations still available after processing over"); - return false; - } - } - if (annotations.isEmpty()) { - return false; - } - - if (writerRoundDone) { - messager.printMessage(Diagnostic.Kind.ERROR, - "Unexpected processing state: annotations still available after writing."); - } - collectSubscribers(annotations, env, messager); - checkForSubscribersToSkip(messager, indexPackage); - - if (!methodsByClass.isEmpty()) { - createInfoIndexFile(index); - } else { - messager.printMessage(Diagnostic.Kind.WARNING, "No @Subscribe annotations found"); - } - writerRoundDone = true; - } catch (RuntimeException e) { - // IntelliJ does not handle exceptions nicely, so log and print a message - e.printStackTrace(); - messager.printMessage(Diagnostic.Kind.ERROR, "Unexpected error in EventBusAnnotationProcessor: " + e); - } - return true; - } - - private void collectSubscribers(Set annotations, RoundEnvironment env, Messager messager) { - for (TypeElement annotation : annotations) { - Set elements = env.getElementsAnnotatedWith(annotation); - for (Element element : elements) { - if (element instanceof ExecutableElement) { - ExecutableElement method = (ExecutableElement) element; - if (checkHasNoErrors(method, messager)) { - TypeElement classElement = (TypeElement) method.getEnclosingElement(); - methodsByClass.putElement(classElement, method); - } - } else { - messager.printMessage(Diagnostic.Kind.ERROR, "@Subscribe is only valid for methods", element); - } - } - } - } - - private boolean checkHasNoErrors(ExecutableElement element, Messager messager) { - if (element.getModifiers().contains(Modifier.STATIC)) { - messager.printMessage(Diagnostic.Kind.ERROR, "Subscriber method must not be static", element); - return false; - } - - if (!element.getModifiers().contains(Modifier.PUBLIC)) { - messager.printMessage(Diagnostic.Kind.ERROR, "Subscriber method must be public", element); - return false; - } - - List parameters = ((ExecutableElement) element).getParameters(); - if (parameters.size() != 1) { - messager.printMessage(Diagnostic.Kind.ERROR, "Subscriber method must have exactly 1 parameter", element); - return false; - } - return true; - } - - /** - * Subscriber classes should be skipped if their class or any involved event class are not visible to the index. - */ - private void checkForSubscribersToSkip(Messager messager, String myPackage) { - for (TypeElement skipCandidate : methodsByClass.keySet()) { - TypeElement subscriberClass = skipCandidate; - while (subscriberClass != null) { - if (!isVisible(myPackage, subscriberClass)) { - boolean added = classesToSkip.add(skipCandidate); - if (added) { - String msg; - if (subscriberClass.equals(skipCandidate)) { - msg = "Falling back to reflection because class is not public"; - } else { - msg = "Falling back to reflection because " + skipCandidate + - " has a non-public super class"; - } - messager.printMessage(Diagnostic.Kind.NOTE, msg, subscriberClass); - } - break; - } - List methods = methodsByClass.get(subscriberClass); - if (methods != null) { - for (ExecutableElement method : methods) { - String skipReason = null; - VariableElement param = method.getParameters().get(0); - TypeMirror typeMirror = getParamTypeMirror(param, messager); - if (!(typeMirror instanceof DeclaredType) || - !(((DeclaredType) typeMirror).asElement() instanceof TypeElement)) { - skipReason = "event type cannot be processed"; - } - if (skipReason == null) { - TypeElement eventTypeElement = (TypeElement) ((DeclaredType) typeMirror).asElement(); - if (!isVisible(myPackage, eventTypeElement)) { - skipReason = "event type is not public"; - } - } - if (skipReason != null) { - boolean added = classesToSkip.add(skipCandidate); - if (added) { - String msg = "Falling back to reflection because " + skipReason; - if (!subscriberClass.equals(skipCandidate)) { - msg += " (found in super class for " + skipCandidate + ")"; - } - messager.printMessage(Diagnostic.Kind.NOTE, msg, param); - } - break; - } - } - } - subscriberClass = getSuperclass(subscriberClass); - } - } - } - - private TypeMirror getParamTypeMirror(VariableElement param, Messager messager) { - TypeMirror typeMirror = param.asType(); - // Check for generic type - if (typeMirror instanceof TypeVariable) { - TypeMirror upperBound = ((TypeVariable) typeMirror).getUpperBound(); - if (upperBound instanceof DeclaredType) { - if (messager != null) { - messager.printMessage(Diagnostic.Kind.NOTE, "Using upper bound type " + upperBound + - " for generic parameter", param); - } - typeMirror = upperBound; - } - } - return typeMirror; - } - - private TypeElement getSuperclass(TypeElement type) { - if (type.getSuperclass().getKind() == TypeKind.DECLARED) { - TypeElement superclass = (TypeElement) processingEnv.getTypeUtils().asElement(type.getSuperclass()); - String name = superclass.getQualifiedName().toString(); - if (name.startsWith("java.") || name.startsWith("javax.") || name.startsWith("android.")) { - // Skip system classes, this just degrades performance - return null; - } else { - return superclass; - } - } else { - return null; - } - } - - private String getClassString(TypeElement typeElement, String myPackage) { - PackageElement packageElement = getPackageElement(typeElement); - String packageString = packageElement.getQualifiedName().toString(); - String className = typeElement.getQualifiedName().toString(); - if (packageString != null && !packageString.isEmpty()) { - if (packageString.equals(myPackage)) { - className = cutPackage(myPackage, className); - } else if (packageString.equals("java.lang")) { - className = typeElement.getSimpleName().toString(); - } - } - return className; - } - - private String cutPackage(String paket, String className) { - if (className.startsWith(paket + '.')) { - // Don't use TypeElement.getSimpleName, it doesn't work for us with inner classes - return className.substring(paket.length() + 1); - } else { - // Paranoia - throw new IllegalStateException("Mismatching " + paket + " vs. " + className); - } - } - - private PackageElement getPackageElement(TypeElement subscriberClass) { - Element candidate = subscriberClass.getEnclosingElement(); - while (!(candidate instanceof PackageElement)) { - candidate = candidate.getEnclosingElement(); - } - return (PackageElement) candidate; - } - - private void writeCreateSubscriberMethods(BufferedWriter writer, List methods, - String callPrefix, String myPackage) throws IOException { - for (ExecutableElement method : methods) { - List parameters = method.getParameters(); - TypeMirror paramType = getParamTypeMirror(parameters.get(0), null); - TypeElement paramElement = (TypeElement) processingEnv.getTypeUtils().asElement(paramType); - String methodName = method.getSimpleName().toString(); - String eventClass = getClassString(paramElement, myPackage) + ".class"; - - Subscribe subscribe = method.getAnnotation(Subscribe.class); - List parts = new ArrayList<>(); - parts.add(callPrefix + "(\"" + methodName + "\","); - String lineEnd = "),"; - if (subscribe.priority() == 0 && !subscribe.sticky()) { - if (subscribe.threadMode() == ThreadMode.POSTING) { - parts.add(eventClass + lineEnd); - } else { - parts.add(eventClass + ","); - parts.add("ThreadMode." + subscribe.threadMode().name() + lineEnd); - } - } else { - parts.add(eventClass + ","); - parts.add("ThreadMode." + subscribe.threadMode().name() + ","); - parts.add(subscribe.priority() + ","); - parts.add(subscribe.sticky() + lineEnd); - } - writeLine(writer, 3, parts.toArray(new String[parts.size()])); - - if (verbose) { - processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "Indexed @Subscribe at " + - method.getEnclosingElement().getSimpleName() + "." + methodName + - "(" + paramElement.getSimpleName() + ")"); - } - - } - } - - private void createInfoIndexFile(String index) { - BufferedWriter writer = null; - try { - JavaFileObject sourceFile = processingEnv.getFiler().createSourceFile(index); - int period = index.lastIndexOf('.'); - String myPackage = period > 0 ? index.substring(0, period) : null; - String clazz = index.substring(period + 1); - writer = new BufferedWriter(sourceFile.openWriter()); - if (myPackage != null) { - writer.write("package " + myPackage + ";\n\n"); - } - writer.write("import org.greenrobot.eventbus.meta.SimpleSubscriberInfo;\n"); - writer.write("import org.greenrobot.eventbus.meta.SubscriberMethodInfo;\n"); - writer.write("import org.greenrobot.eventbus.meta.SubscriberInfo;\n"); - writer.write("import org.greenrobot.eventbus.meta.SubscriberInfoIndex;\n\n"); - writer.write("import org.greenrobot.eventbus.ThreadMode;\n\n"); - writer.write("import java.util.HashMap;\n"); - writer.write("import java.util.Map;\n\n"); - writer.write("/** This class is generated by EventBus, do not edit. */\n"); - writer.write("public class " + clazz + " implements SubscriberInfoIndex {\n"); - writer.write(" private static final Map, SubscriberInfo> SUBSCRIBER_INDEX;\n\n"); - writer.write(" static {\n"); - writer.write(" SUBSCRIBER_INDEX = new HashMap, SubscriberInfo>();\n\n"); - writeIndexLines(writer, myPackage); - writer.write(" }\n\n"); - writer.write(" private static void putIndex(SubscriberInfo info) {\n"); - writer.write(" SUBSCRIBER_INDEX.put(info.getSubscriberClass(), info);\n"); - writer.write(" }\n\n"); - writer.write(" @Override\n"); - writer.write(" public SubscriberInfo getSubscriberInfo(Class subscriberClass) {\n"); - writer.write(" SubscriberInfo info = SUBSCRIBER_INDEX.get(subscriberClass);\n"); - writer.write(" if (info != null) {\n"); - writer.write(" return info;\n"); - writer.write(" } else {\n"); - writer.write(" return null;\n"); - writer.write(" }\n"); - writer.write(" }\n"); - writer.write("}\n"); - } catch (IOException e) { - throw new RuntimeException("Could not write source for " + index, e); - } finally { - if (writer != null) { - try { - writer.close(); - } catch (IOException e) { - //Silent - } - } - } - } - - private void writeIndexLines(BufferedWriter writer, String myPackage) throws IOException { - for (TypeElement subscriberTypeElement : methodsByClass.keySet()) { - if (classesToSkip.contains(subscriberTypeElement)) { - continue; - } - - String subscriberClass = getClassString(subscriberTypeElement, myPackage); - if (isVisible(myPackage, subscriberTypeElement)) { - writeLine(writer, 2, - "putIndex(new SimpleSubscriberInfo(" + subscriberClass + ".class,", - "true,", "new SubscriberMethodInfo[] {"); - List methods = methodsByClass.get(subscriberTypeElement); - writeCreateSubscriberMethods(writer, methods, "new SubscriberMethodInfo", myPackage); - writer.write(" }));\n\n"); - } else { - writer.write(" // Subscriber not visible to index: " + subscriberClass + "\n"); - } - } - } - - private boolean isVisible(String myPackage, TypeElement typeElement) { - Set modifiers = typeElement.getModifiers(); - boolean visible; - if (modifiers.contains(Modifier.PUBLIC)) { - visible = true; - } else if (modifiers.contains(Modifier.PRIVATE) || modifiers.contains(Modifier.PROTECTED)) { - visible = false; - } else { - String subscriberPackage = getPackageElement(typeElement).getQualifiedName().toString(); - if (myPackage == null) { - visible = subscriberPackage.length() == 0; - } else { - visible = myPackage.equals(subscriberPackage); - } - } - return visible; - } - - private void writeLine(BufferedWriter writer, int indentLevel, String... parts) throws IOException { - writeLine(writer, indentLevel, 2, parts); - } - - private void writeLine(BufferedWriter writer, int indentLevel, int indentLevelIncrease, String... parts) - throws IOException { - writeIndent(writer, indentLevel); - int len = indentLevel * 4; - for (int i = 0; i < parts.length; i++) { - String part = parts[i]; - if (i != 0) { - if (len + part.length() > 118) { - writer.write("\n"); - if (indentLevel < 12) { - indentLevel += indentLevelIncrease; - } - writeIndent(writer, indentLevel); - len = indentLevel * 4; - } else { - writer.write(" "); - } - } - writer.write(part); - len += part.length(); - } - writer.write("\n"); - } - - private void writeIndent(BufferedWriter writer, int indentLevel) throws IOException { - for (int i = 0; i < indentLevel; i++) { - writer.write(" "); - } - } -} \ No newline at end of file diff --git a/annotation-processors/src/main/java/org/appdevforall/codeonthego/annotations/EventBusAnnotationProcessor.java b/annotation-processors/src/main/java/org/appdevforall/codeonthego/annotations/EventBusAnnotationProcessor.java new file mode 100644 index 0000000000..9b12dd68de --- /dev/null +++ b/annotation-processors/src/main/java/org/appdevforall/codeonthego/annotations/EventBusAnnotationProcessor.java @@ -0,0 +1,440 @@ +/* + * Copyright (C) 2012-2016 Markus Junginger, greenrobot (http://greenrobot.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.appdevforall.codeonthego.annotations; + +import static net.ltgt.gradle.incap.IncrementalAnnotationProcessorType.AGGREGATING; + +import com.google.auto.service.AutoService; +import de.greenrobot.common.ListMap; +import java.io.BufferedWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import javax.annotation.processing.AbstractProcessor; +import javax.annotation.processing.Messager; +import javax.annotation.processing.Processor; +import javax.annotation.processing.RoundEnvironment; +import javax.annotation.processing.SupportedAnnotationTypes; +import javax.annotation.processing.SupportedOptions; +import javax.lang.model.SourceVersion; +import javax.lang.model.element.Element; +import javax.lang.model.element.ExecutableElement; +import javax.lang.model.element.Modifier; +import javax.lang.model.element.PackageElement; +import javax.lang.model.element.TypeElement; +import javax.lang.model.element.VariableElement; +import javax.lang.model.type.DeclaredType; +import javax.lang.model.type.TypeKind; +import javax.lang.model.type.TypeMirror; +import javax.lang.model.type.TypeVariable; +import javax.tools.Diagnostic; +import javax.tools.JavaFileObject; +import net.ltgt.gradle.incap.IncrementalAnnotationProcessor; +import org.greenrobot.eventbus.Subscribe; +import org.greenrobot.eventbus.ThreadMode; + +/** + * Is an aggregating processor as it writes a single file, the subscriber index file, based on found elements with the @Subscriber annotation. + */ +@SupportedAnnotationTypes("org.greenrobot.eventbus.Subscribe") +@SupportedOptions(value = {"eventBusIndex", "verbose"}) +@IncrementalAnnotationProcessor(AGGREGATING) +@AutoService(Processor.class) +public class EventBusAnnotationProcessor extends AbstractProcessor { + public static final String OPTION_EVENT_BUS_INDEX = "eventBusIndex"; + public static final String OPTION_VERBOSE = "verbose"; + + /** Found subscriber methods for a class (without superclasses). */ + private final ListMap methodsByClass = new ListMap<>(); + private final Set classesToSkip = new HashSet<>(); + + private boolean writerRoundDone; + private int round; + private boolean verbose; + + @Override + public SourceVersion getSupportedSourceVersion() { + return SourceVersion.latest(); + } + + @Override + public boolean process(Set annotations, RoundEnvironment env) { + Messager messager = processingEnv.getMessager(); + try { + String index = processingEnv.getOptions().get(OPTION_EVENT_BUS_INDEX); + if (index == null) { + messager.printMessage(Diagnostic.Kind.ERROR, "No option " + OPTION_EVENT_BUS_INDEX + + " passed to annotation processor"); + return false; + } + verbose = Boolean.parseBoolean(processingEnv.getOptions().get(OPTION_VERBOSE)); + int lastPeriod = index.lastIndexOf('.'); + String indexPackage = lastPeriod != -1 ? index.substring(0, lastPeriod) : null; + + round++; + if (verbose) { + messager.printMessage(Diagnostic.Kind.NOTE, "Processing round " + round + ", new annotations: " + + !annotations.isEmpty() + ", processingOver: " + env.processingOver()); + } + if (env.processingOver()) { + if (!annotations.isEmpty()) { + messager.printMessage(Diagnostic.Kind.ERROR, + "Unexpected processing state: annotations still available after processing over"); + return false; + } + } + if (annotations.isEmpty()) { + return false; + } + + if (writerRoundDone) { + messager.printMessage(Diagnostic.Kind.ERROR, + "Unexpected processing state: annotations still available after writing."); + } + collectSubscribers(annotations, env, messager); + checkForSubscribersToSkip(messager, indexPackage); + + if (!methodsByClass.isEmpty()) { + createInfoIndexFile(index); + } else { + messager.printMessage(Diagnostic.Kind.WARNING, "No @Subscribe annotations found"); + } + writerRoundDone = true; + } catch (RuntimeException e) { + // IntelliJ does not handle exceptions nicely, so log and print a message + e.printStackTrace(); + messager.printMessage(Diagnostic.Kind.ERROR, "Unexpected error in EventBusAnnotationProcessor: " + e); + } + return true; + } + + /** + * Subscriber classes should be skipped if their class or any involved event class are not visible to the index. + */ + private void checkForSubscribersToSkip(Messager messager, String myPackage) { + for (TypeElement skipCandidate : methodsByClass.keySet()) { + TypeElement subscriberClass = skipCandidate; + while (subscriberClass != null) { + if (!isVisible(myPackage, subscriberClass)) { + boolean added = classesToSkip.add(skipCandidate); + if (added) { + String msg; + if (subscriberClass.equals(skipCandidate)) { + msg = "Falling back to reflection because class is not public"; + } else { + msg = "Falling back to reflection because " + skipCandidate + + " has a non-public super class"; + } + messager.printMessage(Diagnostic.Kind.NOTE, msg, subscriberClass); + } + break; + } + List methods = methodsByClass.get(subscriberClass); + if (methods != null) { + for (ExecutableElement method : methods) { + String skipReason = null; + VariableElement param = method.getParameters().get(0); + TypeMirror typeMirror = getParamTypeMirror(param, messager); + if (!(typeMirror instanceof DeclaredType) || + !(((DeclaredType) typeMirror).asElement() instanceof TypeElement)) { + skipReason = "event type cannot be processed"; + } + if (skipReason == null) { + TypeElement eventTypeElement = (TypeElement) ((DeclaredType) typeMirror).asElement(); + if (!isVisible(myPackage, eventTypeElement)) { + skipReason = "event type is not public"; + } + } + if (skipReason != null) { + boolean added = classesToSkip.add(skipCandidate); + if (added) { + String msg = "Falling back to reflection because " + skipReason; + if (!subscriberClass.equals(skipCandidate)) { + msg += " (found in super class for " + skipCandidate + ")"; + } + messager.printMessage(Diagnostic.Kind.NOTE, msg, param); + } + break; + } + } + } + subscriberClass = getSuperclass(subscriberClass); + } + } + } + + private boolean checkHasNoErrors(ExecutableElement element, Messager messager) { + if (element.getModifiers().contains(Modifier.STATIC)) { + messager.printMessage(Diagnostic.Kind.ERROR, "Subscriber method must not be static", element); + return false; + } + + if (!element.getModifiers().contains(Modifier.PUBLIC)) { + messager.printMessage(Diagnostic.Kind.ERROR, "Subscriber method must be public", element); + return false; + } + + List parameters = ((ExecutableElement) element).getParameters(); + if (parameters.size() != 1) { + messager.printMessage(Diagnostic.Kind.ERROR, "Subscriber method must have exactly 1 parameter", element); + return false; + } + return true; + } + + private void collectSubscribers(Set annotations, RoundEnvironment env, Messager messager) { + for (TypeElement annotation : annotations) { + Set elements = env.getElementsAnnotatedWith(annotation); + for (Element element : elements) { + if (element instanceof ExecutableElement) { + ExecutableElement method = (ExecutableElement) element; + if (checkHasNoErrors(method, messager)) { + TypeElement classElement = (TypeElement) method.getEnclosingElement(); + methodsByClass.putElement(classElement, method); + } + } else { + messager.printMessage(Diagnostic.Kind.ERROR, "@Subscribe is only valid for methods", element); + } + } + } + } + + private void createInfoIndexFile(String index) { + BufferedWriter writer = null; + try { + JavaFileObject sourceFile = processingEnv.getFiler().createSourceFile(index); + int period = index.lastIndexOf('.'); + String myPackage = period > 0 ? index.substring(0, period) : null; + String clazz = index.substring(period + 1); + writer = new BufferedWriter(sourceFile.openWriter()); + if (myPackage != null) { + writer.write("package " + myPackage + ";\n\n"); + } + writer.write("import org.greenrobot.eventbus.meta.SimpleSubscriberInfo;\n"); + writer.write("import org.greenrobot.eventbus.meta.SubscriberMethodInfo;\n"); + writer.write("import org.greenrobot.eventbus.meta.SubscriberInfo;\n"); + writer.write("import org.greenrobot.eventbus.meta.SubscriberInfoIndex;\n\n"); + writer.write("import org.greenrobot.eventbus.ThreadMode;\n\n"); + writer.write("import java.util.HashMap;\n"); + writer.write("import java.util.Map;\n\n"); + writer.write("/** This class is generated by EventBus, do not edit. */\n"); + writer.write("public class " + clazz + " implements SubscriberInfoIndex {\n"); + writer.write(" private static final Map, SubscriberInfo> SUBSCRIBER_INDEX;\n\n"); + writer.write(" static {\n"); + writer.write(" SUBSCRIBER_INDEX = new HashMap, SubscriberInfo>();\n\n"); + writeIndexLines(writer, myPackage); + writer.write(" }\n\n"); + writer.write(" private static void putIndex(SubscriberInfo info) {\n"); + writer.write(" SUBSCRIBER_INDEX.put(info.getSubscriberClass(), info);\n"); + writer.write(" }\n\n"); + writer.write(" @Override\n"); + writer.write(" public SubscriberInfo getSubscriberInfo(Class subscriberClass) {\n"); + writer.write(" SubscriberInfo info = SUBSCRIBER_INDEX.get(subscriberClass);\n"); + writer.write(" if (info != null) {\n"); + writer.write(" return info;\n"); + writer.write(" } else {\n"); + writer.write(" return null;\n"); + writer.write(" }\n"); + writer.write(" }\n"); + writer.write("}\n"); + } catch (IOException e) { + throw new RuntimeException("Could not write source for " + index, e); + } finally { + if (writer != null) { + try { + writer.close(); + } catch (IOException e) { + // Silent + } + } + } + } + + private String cutPackage(String paket, String className) { + if (className.startsWith(paket + '.')) { + // Don't use TypeElement.getSimpleName, it doesn't work for us with inner classes + return className.substring(paket.length() + 1); + } else { + // Paranoia + throw new IllegalStateException("Mismatching " + paket + " vs. " + className); + } + } + + private String getClassString(TypeElement typeElement, String myPackage) { + PackageElement packageElement = getPackageElement(typeElement); + String packageString = packageElement.getQualifiedName().toString(); + String className = typeElement.getQualifiedName().toString(); + if (packageString != null && !packageString.isEmpty()) { + if (packageString.equals(myPackage)) { + className = cutPackage(myPackage, className); + } else if (packageString.equals("java.lang")) { + className = typeElement.getSimpleName().toString(); + } + } + return className; + } + + private PackageElement getPackageElement(TypeElement subscriberClass) { + Element candidate = subscriberClass.getEnclosingElement(); + while (!(candidate instanceof PackageElement)) { + candidate = candidate.getEnclosingElement(); + } + return (PackageElement) candidate; + } + + private TypeMirror getParamTypeMirror(VariableElement param, Messager messager) { + TypeMirror typeMirror = param.asType(); + // Check for generic type + if (typeMirror instanceof TypeVariable) { + TypeMirror upperBound = ((TypeVariable) typeMirror).getUpperBound(); + if (upperBound instanceof DeclaredType) { + if (messager != null) { + messager.printMessage(Diagnostic.Kind.NOTE, "Using upper bound type " + upperBound + + " for generic parameter", param); + } + typeMirror = upperBound; + } + } + return typeMirror; + } + + private TypeElement getSuperclass(TypeElement type) { + if (type.getSuperclass().getKind() == TypeKind.DECLARED) { + TypeElement superclass = (TypeElement) processingEnv.getTypeUtils().asElement(type.getSuperclass()); + String name = superclass.getQualifiedName().toString(); + if (name.startsWith("java.") || name.startsWith("javax.") || name.startsWith("android.")) { + // Skip system classes, this just degrades performance + return null; + } else { + return superclass; + } + } else { + return null; + } + } + + private boolean isVisible(String myPackage, TypeElement typeElement) { + Set modifiers = typeElement.getModifiers(); + boolean visible; + if (modifiers.contains(Modifier.PUBLIC)) { + visible = true; + } else if (modifiers.contains(Modifier.PRIVATE) || modifiers.contains(Modifier.PROTECTED)) { + visible = false; + } else { + String subscriberPackage = getPackageElement(typeElement).getQualifiedName().toString(); + if (myPackage == null) { + visible = subscriberPackage.length() == 0; + } else { + visible = myPackage.equals(subscriberPackage); + } + } + return visible; + } + + private void writeCreateSubscriberMethods(BufferedWriter writer, List methods, + String callPrefix, String myPackage) throws IOException { + for (ExecutableElement method : methods) { + List parameters = method.getParameters(); + TypeMirror paramType = getParamTypeMirror(parameters.get(0), null); + TypeElement paramElement = (TypeElement) processingEnv.getTypeUtils().asElement(paramType); + String methodName = method.getSimpleName().toString(); + String eventClass = getClassString(paramElement, myPackage) + ".class"; + + Subscribe subscribe = method.getAnnotation(Subscribe.class); + List parts = new ArrayList<>(); + parts.add(callPrefix + "(\"" + methodName + "\","); + String lineEnd = "),"; + if (subscribe.priority() == 0 && !subscribe.sticky()) { + if (subscribe.threadMode() == ThreadMode.POSTING) { + parts.add(eventClass + lineEnd); + } else { + parts.add(eventClass + ","); + parts.add("ThreadMode." + subscribe.threadMode().name() + lineEnd); + } + } else { + parts.add(eventClass + ","); + parts.add("ThreadMode." + subscribe.threadMode().name() + ","); + parts.add(subscribe.priority() + ","); + parts.add(subscribe.sticky() + lineEnd); + } + writeLine(writer, 3, parts.toArray(new String[parts.size()])); + + if (verbose) { + processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "Indexed @Subscribe at " + + method.getEnclosingElement().getSimpleName() + "." + methodName + + "(" + paramElement.getSimpleName() + ")"); + } + + } + } + + private void writeIndent(BufferedWriter writer, int indentLevel) throws IOException { + for (int i = 0; i < indentLevel; i++) { + writer.write(" "); + } + } + + private void writeIndexLines(BufferedWriter writer, String myPackage) throws IOException { + for (TypeElement subscriberTypeElement : methodsByClass.keySet()) { + if (classesToSkip.contains(subscriberTypeElement)) { + continue; + } + + String subscriberClass = getClassString(subscriberTypeElement, myPackage); + if (isVisible(myPackage, subscriberTypeElement)) { + writeLine(writer, 2, + "putIndex(new SimpleSubscriberInfo(" + subscriberClass + ".class,", + "true,", "new SubscriberMethodInfo[] {"); + List methods = methodsByClass.get(subscriberTypeElement); + writeCreateSubscriberMethods(writer, methods, "new SubscriberMethodInfo", myPackage); + writer.write(" }));\n\n"); + } else { + writer.write(" // Subscriber not visible to index: " + subscriberClass + "\n"); + } + } + } + + private void writeLine(BufferedWriter writer, int indentLevel, int indentLevelIncrease, String... parts) + throws IOException { + writeIndent(writer, indentLevel); + int len = indentLevel * 4; + for (int i = 0; i < parts.length; i++) { + String part = parts[i]; + if (i != 0) { + if (len + part.length() > 118) { + writer.write("\n"); + if (indentLevel < 12) { + indentLevel += indentLevelIncrease; + } + writeIndent(writer, indentLevel); + len = indentLevel * 4; + } else { + writer.write(" "); + } + } + writer.write(part); + len += part.length(); + } + writer.write("\n"); + } + + private void writeLine(BufferedWriter writer, int indentLevel, String... parts) throws IOException { + writeLine(writer, indentLevel, 2, parts); + } +} diff --git a/annotations/src/main/java/com/itsaky/androidide/annotations/inflater/ViewAdapter.kt b/annotations/src/main/java/com/itsaky/androidide/annotations/inflater/ViewAdapter.kt deleted file mode 100644 index f1fefa36e0..0000000000 --- a/annotations/src/main/java/com/itsaky/androidide/annotations/inflater/ViewAdapter.kt +++ /dev/null @@ -1,33 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ -package com.itsaky.androidide.annotations.inflater - -import android.view.View -import kotlin.annotation.AnnotationTarget.CLASS -import kotlin.reflect.KClass - -/** - * Annotation used to indicate that a class is an attribute adapater for the given view class. - * - * @property forView The view that this adpater handles. - * @property moduleNamespace The package name of the artifact/module in which the [view][forView] is - * declared. Set to `android` by default. - * @author Akash Yadav - */ -@Target(CLASS) -@Retention(AnnotationRetention.SOURCE) -annotation class ViewAdapter(val forView: KClass, val moduleNamespace: String = "android") diff --git a/annotations/src/main/java/com/itsaky/androidide/annotations/uidesigner/IncludeInDesigner.kt b/annotations/src/main/java/com/itsaky/androidide/annotations/uidesigner/IncludeInDesigner.kt deleted file mode 100644 index e5299e3b2d..0000000000 --- a/annotations/src/main/java/com/itsaky/androidide/annotations/uidesigner/IncludeInDesigner.kt +++ /dev/null @@ -1,37 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.annotations.uidesigner - -/** - * Indicates that the view (whose view adapter is annotated with [ViewAdapter] - * [com.itsaky.androidide.annotations.inflater.ViewAdapter] and [IncludeInDesigner]) should be - * included in the UI Designer and made accessible to the user. - * - * @author Akash Yadav - */ -annotation class IncludeInDesigner(val group: Group) { - - /** The widget groups that are available in the UI Designer. */ - enum class Group { - /** Includes the Android platform widgets. */ - WIDGETS, - - /** Includes the Android platform layouts. */ - LAYOUTS - } -} diff --git a/annotations/src/main/java/org/appdevforall/codeonthego/annotations/inflater/ViewAdapter.kt b/annotations/src/main/java/org/appdevforall/codeonthego/annotations/inflater/ViewAdapter.kt new file mode 100644 index 0000000000..bc257f64c0 --- /dev/null +++ b/annotations/src/main/java/org/appdevforall/codeonthego/annotations/inflater/ViewAdapter.kt @@ -0,0 +1,36 @@ +/* + * This file is part of AndroidIDE. + * + * AndroidIDE is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * AndroidIDE is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with AndroidIDE. If not, see . + */ +package org.appdevforall.codeonthego.annotations.inflater + +import android.view.View +import kotlin.annotation.AnnotationTarget.CLASS +import kotlin.reflect.KClass + +/** + * Annotation used to indicate that a class is an attribute adapater for the given view class. + * + * @property forView The view that this adpater handles. + * @property moduleNamespace The package name of the artifact/module in which the [view][forView] is + * declared. Set to `android` by default. + * @author Akash Yadav + */ +@Target(CLASS) +@Retention(AnnotationRetention.SOURCE) +annotation class ViewAdapter( + val forView: KClass, + val moduleNamespace: String = "android", +) diff --git a/annotations/src/main/java/org/appdevforall/codeonthego/annotations/uidesigner/IncludeInDesigner.kt b/annotations/src/main/java/org/appdevforall/codeonthego/annotations/uidesigner/IncludeInDesigner.kt new file mode 100644 index 0000000000..12403f40f9 --- /dev/null +++ b/annotations/src/main/java/org/appdevforall/codeonthego/annotations/uidesigner/IncludeInDesigner.kt @@ -0,0 +1,38 @@ +/* + * This file is part of AndroidIDE. + * + * AndroidIDE is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * AndroidIDE is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with AndroidIDE. If not, see . + */ + +package org.appdevforall.codeonthego.annotations.uidesigner + +/** + * Indicates that the view (whose view adapter is annotated with [ViewAdapter] + * [org.appdevforall.codeonthego.annotations.inflater.ViewAdapter] and [IncludeInDesigner]) should be + * included in the UI Designer and made accessible to the user. + * + * @author Akash Yadav + */ +annotation class IncludeInDesigner( + val group: Group, +) { + /** The widget groups that are available in the UI Designer. */ + enum class Group { + /** Includes the Android platform widgets. */ + WIDGETS, + + /** Includes the Android platform layouts. */ + LAYOUTS, + } +} diff --git a/apk-viewer-plugin/build.gradle.kts b/apk-viewer-plugin/build.gradle.kts index 27fdbdf08b..992686fd89 100644 --- a/apk-viewer-plugin/build.gradle.kts +++ b/apk-viewer-plugin/build.gradle.kts @@ -1,67 +1,66 @@ plugins { - id("com.android.application") version "8.8.2" - id("org.jetbrains.kotlin.android") version "2.1.21" - id("com.itsaky.androidide.plugins.build") + id("com.android.application") version "8.8.2" + id("org.jetbrains.kotlin.android") version "2.1.21" + id("org.appdevforall.codeonthego.plugins.build") } pluginBuilder { - pluginName = "apk-viewer" + pluginName = "apk-viewer" } android { - namespace = "com.example.sampleplugin" - compileSdk = 34 + namespace = "com.example.sampleplugin" + compileSdk = 34 - defaultConfig { - applicationId = "com.example.sampleplugin" - minSdk = 26 - targetSdk = 34 - versionCode = 1 - versionName = "1.0.0" - } + defaultConfig { + applicationId = "com.example.sampleplugin" + minSdk = 26 + targetSdk = 34 + versionCode = 1 + versionName = "1.0.0" + } - buildTypes { - release { - isMinifyEnabled = false - proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro") - } - } + buildTypes { + release { + isMinifyEnabled = false + proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro") + } + } - compileOptions { - sourceCompatibility = JavaVersion.VERSION_17 - targetCompatibility = JavaVersion.VERSION_17 - } - kotlinOptions { - jvmTarget = "17" - } + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + kotlinOptions { + jvmTarget = "17" + } - - - packaging { - resources { - excludes += setOf( - "META-INF/versions/9/OSGI-INF/MANIFEST.MF", - "META-INF/DEPENDENCIES", - "META-INF/LICENSE", - "META-INF/LICENSE.txt", - "META-INF/NOTICE", - "META-INF/NOTICE.txt" - ) - } - } + packaging { + resources { + excludes += + setOf( + "META-INF/versions/9/OSGI-INF/MANIFEST.MF", + "META-INF/DEPENDENCIES", + "META-INF/LICENSE", + "META-INF/LICENSE.txt", + "META-INF/NOTICE", + "META-INF/NOTICE.txt", + ) + } + } } dependencies { - compileOnly(project(":plugin-api")) + compileOnly(project(":plugin-api")) - implementation("androidx.appcompat:appcompat:1.6.1") - implementation("com.google.android.material:material:1.10.0") - implementation("androidx.fragment:fragment-ktx:1.8.8") - implementation("org.jetbrains.kotlin:kotlin-stdlib:2.1.21") - implementation("androidx.fragment:fragment:1.8.8") + implementation("androidx.appcompat:appcompat:1.6.1") + implementation("com.google.android.material:material:1.10.0") + implementation("androidx.fragment:fragment-ktx:1.8.8") + implementation("org.jetbrains.kotlin:kotlin-stdlib:2.1.21") + implementation("androidx.fragment:fragment:1.8.8") } tasks.wrapper { - gradleVersion = "8.10.2" - distributionType = Wrapper.DistributionType.BIN + gradleVersion = "8.10.2" + distributionType = Wrapper.DistributionType.BIN } diff --git a/apk-viewer-plugin/proguard-rules.pro b/apk-viewer-plugin/proguard-rules.pro index 923af538d5..a908042025 100644 --- a/apk-viewer-plugin/proguard-rules.pro +++ b/apk-viewer-plugin/proguard-rules.pro @@ -9,8 +9,8 @@ -keep class com.example.sampleplugin.fragments.** { *; } # Keep plugin interfaces --keep interface com.itsaky.androidide.plugins.** { *; } --keep class com.itsaky.androidide.plugins.** { *; } +-keep interface org.appdevforall.codeonthego.plugins.** { *; } +-keep class org.appdevforall.codeonthego.plugins.** { *; } # Keep Android components -keepclassmembers class * extends androidx.fragment.app.Fragment { diff --git a/apk-viewer-plugin/src/main/kotlin/com/example/sampleplugin/ApkViewer.kt b/apk-viewer-plugin/src/main/kotlin/com/example/sampleplugin/ApkViewer.kt index 7f2d1033e7..380a2a929d 100644 --- a/apk-viewer-plugin/src/main/kotlin/com/example/sampleplugin/ApkViewer.kt +++ b/apk-viewer-plugin/src/main/kotlin/com/example/sampleplugin/ApkViewer.kt @@ -1,209 +1,206 @@ package com.example.sampleplugin import androidx.fragment.app.Fragment -import com.itsaky.androidide.plugins.IPlugin -import com.itsaky.androidide.plugins.PluginContext -import com.itsaky.androidide.plugins.extensions.UIExtension -import com.itsaky.androidide.plugins.extensions.EditorTabExtension -import com.itsaky.androidide.plugins.extensions.MenuItem -import com.itsaky.androidide.plugins.extensions.TabItem -import com.itsaky.androidide.plugins.extensions.EditorTabItem -import com.itsaky.androidide.plugins.extensions.NavigationItem -import com.itsaky.androidide.plugins.extensions.FileOpenExtension -import com.itsaky.androidide.plugins.extensions.FileTabMenuItem -import com.itsaky.androidide.plugins.services.IdeEditorTabService import com.example.sampleplugin.R import com.example.sampleplugin.fragments.ApkAnalyzerFragment +import org.appdevforall.codeonthego.plugins.IPlugin +import org.appdevforall.codeonthego.plugins.PluginContext +import org.appdevforall.codeonthego.plugins.extensions.EditorTabExtension +import org.appdevforall.codeonthego.plugins.extensions.EditorTabItem +import org.appdevforall.codeonthego.plugins.extensions.FileOpenExtension +import org.appdevforall.codeonthego.plugins.extensions.FileTabMenuItem +import org.appdevforall.codeonthego.plugins.extensions.MenuItem +import org.appdevforall.codeonthego.plugins.extensions.NavigationItem +import org.appdevforall.codeonthego.plugins.extensions.TabItem +import org.appdevforall.codeonthego.plugins.extensions.UIExtension +import org.appdevforall.codeonthego.plugins.services.IdeEditorTabService import java.io.File /** * APK Viewer Plugin * Provides APK analysis functionality via main menu toolbar and bottom sheet */ -class ApkViewer : IPlugin, UIExtension, EditorTabExtension, FileOpenExtension { - - private lateinit var context: PluginContext - private var pendingAnalysisFile: File? = null - - companion object { - private const val TAB_ID = "apk_analyzer_main_tab" - } - - override fun initialize(context: PluginContext): Boolean { - return try { - this.context = context - context.logger.info("ApkViewer: Plugin initialized successfully") - true - } catch (e: Exception) { - context.logger.error("ApkViewer: Plugin initialization failed", e) - false - } - } - - override fun activate(): Boolean { - context.logger.info("ApkViewer: Activating plugin") - return true - } - - override fun deactivate(): Boolean { - context.logger.info("ApkViewer: Deactivating plugin") - return true - } - - override fun dispose() { - context.logger.info("ApkViewer: Disposing plugin") - } - - // UIExtension - Main menu toolbar item - override fun getMainMenuItems(): List { - return listOf( - MenuItem( - id = "apk_analyzer_menu", - title = "APK Analyzer", - isEnabled = true, - isVisible = true, - action = { - context.logger.info("APK Analyzer menu item clicked") - openApkAnalyzerTab() - } - ) - ) - } - - // UIExtension - Bottom sheet tab - override fun getEditorTabs(): List { - context.logger.debug("ApkViewer: getEditorTabs() called") - - return listOf( - TabItem( - id = "apk_viewer_tab", - title = "APK Analyzer", - fragmentFactory = { - context.logger.debug("ApkViewer: Creating ApkAnalyzerFragment for bottom sheet") - ApkAnalyzerFragment() - }, - isEnabled = true, - isVisible = true, - order = 100 - ) - ) - } - - // UIExtension - Sidebar navigation item - override fun getSideMenuItems(): List { - return listOf( - NavigationItem( - id = "apk_analyzer_sidebar", - title = "APK Analyzer", - icon = R.drawable.ic_apk_analyzer, - isEnabled = true, - isVisible = true, - group = "tools", - order = 0, - action = { openApkAnalyzerTab() } - ) - ) - } - - // EditorTabExtension - Main editor tab to display the analyzer - override fun getMainEditorTabs(): List { - return listOf( - - EditorTabItem( - id = TAB_ID, - title = "APK Analyzer", - icon = R.drawable.ic_apk_analyzer, - fragmentFactory = { - context.logger.debug("Creating ApkAnalyzerFragment") - ApkAnalyzerFragment() - }, - isCloseable = true, - isPersistent = false, - order = 100, - isEnabled = true, - isVisible = true, - tooltip = "Analyze APK structure and contents" - ) - ) - } - - override fun onEditorTabSelected(tabId: String, fragment: Fragment) { - context.logger.info("Editor tab selected: $tabId") - val file = pendingAnalysisFile ?: return - pendingAnalysisFile = null - if (tabId == TAB_ID && fragment is ApkAnalyzerFragment) { - fragment.analyzeFile(file) - } - } - - override fun onEditorTabClosed(tabId: String) { - context.logger.info("Editor tab closed: $tabId") - } - - override fun canCloseEditorTab(tabId: String): Boolean { - return true - } - - override fun canHandleFileOpen(file: File): Boolean { - return file.extension.equals("apk", ignoreCase = true) - } - - override fun handleFileOpen(file: File): Boolean { - pendingAnalysisFile = file - openApkAnalyzerTab() - return true - } - - override fun onFileOpened(file: File) { - if (file.extension.equals("apk", ignoreCase = true)) { - context.logger.info("APK file opened: ${file.name}") - } - } - - override fun getFileTabMenuItems(file: File): List { - if (!file.extension.equals("apk", ignoreCase = true)) return emptyList() - - return listOf( - FileTabMenuItem( - id = "apk_viewer.analyze", - title = "Analyze APK", - order = 0, - action = { - pendingAnalysisFile = file - openApkAnalyzerTab() - } - ) - ) - } - - override fun onFileClosed(file: File) { - if (file.extension.equals("apk", ignoreCase = true)) { - context.logger.info("APK file closed: ${file.name}") - } - } - - private fun openApkAnalyzerTab() { - context.logger.info("Opening APK Analyzer tab") - - val editorTabService = context.services.get(IdeEditorTabService::class.java) - if (editorTabService == null) { - context.logger.error("Editor tab service not available") - return - } - - if (!editorTabService.isTabSystemAvailable()) { - context.logger.error("Editor tab system not available") - return - } - - try { - if (editorTabService.selectPluginTab(TAB_ID)) { - context.logger.info("Successfully opened APK Analyzer tab") - } else { - context.logger.warn("Failed to open APK Analyzer tab") - } - } catch (e: Exception) { - context.logger.error("Error opening APK Analyzer tab", e) - } - } +class ApkViewer : + IPlugin, + UIExtension, + EditorTabExtension, + FileOpenExtension { + private lateinit var context: PluginContext + private var pendingAnalysisFile: File? = null + + companion object { + private const val TAB_ID = "apk_analyzer_main_tab" + } + + override fun initialize(context: PluginContext): Boolean = + try { + this.context = context + context.logger.info("ApkViewer: Plugin initialized successfully") + true + } catch (e: Exception) { + context.logger.error("ApkViewer: Plugin initialization failed", e) + false + } + + override fun activate(): Boolean { + context.logger.info("ApkViewer: Activating plugin") + return true + } + + override fun deactivate(): Boolean { + context.logger.info("ApkViewer: Deactivating plugin") + return true + } + + override fun dispose() { + context.logger.info("ApkViewer: Disposing plugin") + } + + // UIExtension - Main menu toolbar item + override fun getMainMenuItems(): List = + listOf( + MenuItem( + id = "apk_analyzer_menu", + title = "APK Analyzer", + isEnabled = true, + isVisible = true, + action = { + context.logger.info("APK Analyzer menu item clicked") + openApkAnalyzerTab() + }, + ), + ) + + // UIExtension - Bottom sheet tab + override fun getEditorTabs(): List { + context.logger.debug("ApkViewer: getEditorTabs() called") + + return listOf( + TabItem( + id = "apk_viewer_tab", + title = "APK Analyzer", + fragmentFactory = { + context.logger.debug("ApkViewer: Creating ApkAnalyzerFragment for bottom sheet") + ApkAnalyzerFragment() + }, + isEnabled = true, + isVisible = true, + order = 100, + ), + ) + } + + // UIExtension - Sidebar navigation item + override fun getSideMenuItems(): List = + listOf( + NavigationItem( + id = "apk_analyzer_sidebar", + title = "APK Analyzer", + icon = R.drawable.ic_apk_analyzer, + isEnabled = true, + isVisible = true, + group = "tools", + order = 0, + action = { openApkAnalyzerTab() }, + ), + ) + + // EditorTabExtension - Main editor tab to display the analyzer + override fun getMainEditorTabs(): List = + listOf( + EditorTabItem( + id = TAB_ID, + title = "APK Analyzer", + icon = R.drawable.ic_apk_analyzer, + fragmentFactory = { + context.logger.debug("Creating ApkAnalyzerFragment") + ApkAnalyzerFragment() + }, + isCloseable = true, + isPersistent = false, + order = 100, + isEnabled = true, + isVisible = true, + tooltip = "Analyze APK structure and contents", + ), + ) + + override fun onEditorTabSelected( + tabId: String, + fragment: Fragment, + ) { + context.logger.info("Editor tab selected: $tabId") + val file = pendingAnalysisFile ?: return + pendingAnalysisFile = null + if (tabId == TAB_ID && fragment is ApkAnalyzerFragment) { + fragment.analyzeFile(file) + } + } + + override fun onEditorTabClosed(tabId: String) { + context.logger.info("Editor tab closed: $tabId") + } + + override fun canCloseEditorTab(tabId: String): Boolean = true + + override fun canHandleFileOpen(file: File): Boolean = file.extension.equals("apk", ignoreCase = true) + + override fun handleFileOpen(file: File): Boolean { + pendingAnalysisFile = file + openApkAnalyzerTab() + return true + } + + override fun onFileOpened(file: File) { + if (file.extension.equals("apk", ignoreCase = true)) { + context.logger.info("APK file opened: ${file.name}") + } + } + + override fun getFileTabMenuItems(file: File): List { + if (!file.extension.equals("apk", ignoreCase = true)) return emptyList() + + return listOf( + FileTabMenuItem( + id = "apk_viewer.analyze", + title = "Analyze APK", + order = 0, + action = { + pendingAnalysisFile = file + openApkAnalyzerTab() + }, + ), + ) + } + + override fun onFileClosed(file: File) { + if (file.extension.equals("apk", ignoreCase = true)) { + context.logger.info("APK file closed: ${file.name}") + } + } + + private fun openApkAnalyzerTab() { + context.logger.info("Opening APK Analyzer tab") + + val editorTabService = context.services.get(IdeEditorTabService::class.java) + if (editorTabService == null) { + context.logger.error("Editor tab service not available") + return + } + + if (!editorTabService.isTabSystemAvailable()) { + context.logger.error("Editor tab system not available") + return + } + + try { + if (editorTabService.selectPluginTab(TAB_ID)) { + context.logger.info("Successfully opened APK Analyzer tab") + } else { + context.logger.warn("Failed to open APK Analyzer tab") + } + } catch (e: Exception) { + context.logger.error("Error opening APK Analyzer tab", e) + } + } } diff --git a/apk-viewer-plugin/src/main/kotlin/com/example/sampleplugin/fragments/ApkAnalyzerFragment.kt b/apk-viewer-plugin/src/main/kotlin/com/example/sampleplugin/fragments/ApkAnalyzerFragment.kt index a2da07cf2a..a17404877b 100644 --- a/apk-viewer-plugin/src/main/kotlin/com/example/sampleplugin/fragments/ApkAnalyzerFragment.kt +++ b/apk-viewer-plugin/src/main/kotlin/com/example/sampleplugin/fragments/ApkAnalyzerFragment.kt @@ -24,319 +24,402 @@ import com.example.sampleplugin.R import com.example.sampleplugin.viewmodel.ApkAnalyzerViewModel import com.example.sampleplugin.viewmodel.ApkParseResult import com.google.android.material.color.MaterialColors -import com.itsaky.androidide.plugins.base.PluginFragmentHelper import kotlinx.coroutines.launch +import org.appdevforall.codeonthego.plugins.base.PluginFragmentHelper data class TableSection( - val title: String, - val headers: List, - val rows: List>, - val showAllAction: String? = null + val title: String, + val headers: List, + val rows: List>, + val showAllAction: String? = null, ) class ApkAnalyzerFragment : Fragment() { - - companion object { - private const val PLUGIN_ID = "com.example.apkviewer" - private const val MAX_LARGE_FILES_DISPLAYED = 10 - private const val FALLBACK_SURFACE = 0xFFFFFBFE.toInt() - private const val FALLBACK_SURFACE_VARIANT = 0xFFE7E0EC.toInt() - } - - private val viewModel by viewModels() - private var showAllLargeFiles = false - private var pendingAnalysisFile: java.io.File? = null - - private var statusText: TextView? = null - private var btnStart: Button? = null - private var progressBar: ProgressBar? = null - private var resultsContainer: LinearLayout? = null - - private val pickApkLauncher = registerForActivityResult( - ActivityResultContracts.StartActivityForResult() - ) { result -> - if (result.resultCode == Activity.RESULT_OK) { - result.data?.data?.let { viewModel.analyzeApk(it, requireContext().applicationContext) } - } - } - - override fun onGetLayoutInflater(savedInstanceState: Bundle?): LayoutInflater { - val inflater = super.onGetLayoutInflater(savedInstanceState) - return PluginFragmentHelper.getPluginInflater(PLUGIN_ID, inflater) - } - - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - runCatching { - PluginFragmentHelper.getServiceRegistry(PLUGIN_ID) - } - } - - override fun onCreateView( - inflater: LayoutInflater, - container: ViewGroup?, - savedInstanceState: Bundle? - ): View? { - return inflater.inflate(R.layout.fragment_sample, container, false) - } - - override fun onViewCreated(view: View, savedInstanceState: Bundle?) { - super.onViewCreated(view, savedInstanceState) - statusText = view.findViewById(R.id.tv_context) - btnStart = view.findViewById(R.id.btnStart) - progressBar = view.findViewById(R.id.progressBar) - resultsContainer = view.findViewById(R.id.resultsContainer) - - btnStart?.setOnClickListener { openFilePicker() } - - viewLifecycleOwner.lifecycleScope.launch { - viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) { - viewModel.uiState.collect { state -> renderState(state) } - } - } - - val file = pendingAnalysisFile ?: viewModel.pendingFile - if (file != null) { - pendingAnalysisFile = null - viewModel.pendingFile = null - viewModel.analyzeApk(file) - } - } - - private fun renderState(state: ApkAnalyzerViewModel.UiState) { - resultsContainer?.removeAllViews() - when (state) { - is ApkAnalyzerViewModel.UiState.Idle -> { - progressBar?.visibility = View.GONE - statusText?.visibility = View.GONE - btnStart?.isEnabled = true - } - is ApkAnalyzerViewModel.UiState.Analyzing -> { - showAllLargeFiles = false - progressBar?.visibility = View.VISIBLE - statusText?.visibility = View.VISIBLE - statusText?.text = getString(R.string.analyzing_apk) - btnStart?.isEnabled = false - } - is ApkAnalyzerViewModel.UiState.Success -> { - progressBar?.visibility = View.GONE - statusText?.visibility = View.GONE - btnStart?.isEnabled = true - renderSections(mapToSections(state.data)) - } - is ApkAnalyzerViewModel.UiState.Error -> { - progressBar?.visibility = View.GONE - statusText?.visibility = View.VISIBLE - statusText?.text = getString(R.string.analysis_failed, state.message) - btnStart?.isEnabled = true - } - } - } - - private fun openFilePicker() { - val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply { - addCategory(Intent.CATEGORY_OPENABLE) - type = "application/vnd.android.package-archive" - } - pickApkLauncher.launch(intent) - } - - fun analyzeFile(file: java.io.File) { - if (!isAdded || view == null) { - pendingAnalysisFile = file - return - } - viewModel.analyzeApk(file) - } - - private fun formatRatio(compressed: Long, raw: Long): String { - return if (raw > 0) { - String.format("%.1f%%", (compressed.toDouble() / raw.toDouble()) * 100) - } else getString(R.string.value_na) - } - - private fun mapToSections(data: ApkParseResult): List { - val sections = mutableListOf() - - sections.add(TableSection( - title = getString(R.string.section_apk_structure), - headers = listOf(getString(R.string.header_property), getString(R.string.header_value)), - rows = listOf( - listOf(getString(R.string.label_apk_file_size), formatFileSize(data.apkSize)), - listOf(getString(R.string.label_total_entries), "${data.totalEntries}"), - listOf(getString(R.string.label_uncompressed_size), formatFileSize(data.totalUncompressed)), - listOf(getString(R.string.label_compressed_size), formatFileSize(data.totalCompressed)), - listOf(getString(R.string.label_compression_ratio), formatRatio(data.totalCompressed, data.totalUncompressed)), - listOf(getString(R.string.label_directories), "${data.directoryCount}"), - listOf(getString(R.string.label_files), "${data.fileCount}") - ) - )) - - val keyFileRows = data.keyFiles.map { kf -> - if (kf.exists) { - listOf(kf.name, "\u2713", formatFileSize(kf.rawSize), formatFileSize(kf.compressedSize), formatRatio(kf.compressedSize, kf.rawSize)) - } else { - listOf(kf.name, "\u2717", "\u2014", "\u2014", "\u2014") - } - } - sections.add(TableSection( - title = getString(R.string.section_key_files), - headers = listOf(getString(R.string.header_file), "", getString(R.string.header_raw), getString(R.string.header_compressed), getString(R.string.header_ratio)), - rows = keyFileRows - )) - - if (data.nativeLibArchitectures.isNotEmpty()) { - val totalNativeLibs = data.nativeLibArchitectures.values.sumOf { it.size } - val nativeRows = mutableListOf>() - data.nativeLibArchitectures.forEach { (arch, libs) -> - val archRaw = libs.sumOf { it.rawSize } - val archCompressed = libs.sumOf { it.compressedSize } - nativeRows.add(listOf( - "\u25B8 $arch", - "${libs.size}", - formatFileSize(archRaw), - formatFileSize(archCompressed) - )) - libs.sortedByDescending { it.rawSize }.take(3).forEach { lib -> - nativeRows.add(listOf( - " ${lib.name}", - "", - formatFileSize(lib.rawSize), - formatFileSize(lib.compressedSize) - )) - } - if (libs.size > 3) { - nativeRows.add(listOf(" +${libs.size - 3} more", "", "", "")) - } - } - sections.add(TableSection( - title = getString(R.string.section_native_libraries, totalNativeLibs), - headers = listOf(getString(R.string.header_name), getString(R.string.header_count), getString(R.string.header_raw), getString(R.string.header_compressed)), - rows = nativeRows - )) - } - - if (data.resourceDirs.isNotEmpty()) { - val resDirRows = data.resourceDirs.map { dir -> - if (dir.rawSize > 0) { - listOf(dir.path, "${dir.fileCount}", formatFileSize(dir.rawSize), formatFileSize(dir.compressedSize)) - } else { - listOf(dir.path, "0", "\u2014", "\u2014") - } - } - sections.add(TableSection( - title = getString(R.string.section_resource_directories, data.resourceDirs.size), - headers = listOf(getString(R.string.header_directory), getString(R.string.header_files), getString(R.string.header_raw), getString(R.string.header_compressed)), - rows = resDirRows - )) - } - - if (data.largeFiles.isNotEmpty()) { - val displayedFiles = if (showAllLargeFiles) data.largeFiles else data.largeFiles.take(MAX_LARGE_FILES_DISPLAYED) - val largeFileRows = displayedFiles.map { lf -> - listOf(lf.name, formatFileSize(lf.rawSize), formatFileSize(lf.compressedSize), formatRatio(lf.compressedSize, lf.rawSize)) - } - sections.add(TableSection( - title = getString(R.string.section_large_files), - headers = listOf(getString(R.string.header_file), getString(R.string.header_raw), getString(R.string.header_compressed), getString(R.string.header_ratio)), - rows = largeFileRows, - showAllAction = if (!showAllLargeFiles && data.largeFiles.size > MAX_LARGE_FILES_DISPLAYED) { - getString(R.string.action_show_all, data.largeFiles.size) - } else null - )) - } - - val sigText = if (data.hasV1Signature) getString(R.string.value_v1_signing) else getString(R.string.value_v2_or_unsigned) - sections.add(TableSection( - title = getString(R.string.section_apk_metadata), - headers = listOf(getString(R.string.header_property), getString(R.string.header_value)), - rows = listOf( - listOf(getString(R.string.label_signature_scheme), sigText), - listOf(getString(R.string.label_multi_dex), if (data.hasMultiDex) getString(R.string.value_yes) else getString(R.string.value_no)), - listOf(getString(R.string.label_code_obfuscation), if (data.hasProguard) getString(R.string.value_detected) else getString(R.string.value_none_detected)) - ) - )) - - return sections - } - - private fun renderSections(sections: List) { - val container = resultsContainer ?: return - val inflater = layoutInflater - val ctx = requireContext() - - val surfaceColor = MaterialColors.getColor(ctx, com.google.android.material.R.attr.colorSurface, FALLBACK_SURFACE) - val surfaceVariantColor = MaterialColors.getColor(ctx, com.google.android.material.R.attr.colorSurfaceVariant, FALLBACK_SURFACE_VARIANT) - val altRowColor = ColorUtils.blendARGB(surfaceColor, surfaceVariantColor, 0.4f) - - sections.forEach { section -> - val cardView = inflater.inflate(R.layout.item_section_card, container, false) - val cardCtx = cardView.context - - cardView.findViewById(R.id.sectionTitle).text = section.title - val table = cardView.findViewById(R.id.sectionTable) - - if (section.headers.isNotEmpty()) { - val headerRow = TableRow(cardCtx).apply { - setBackgroundColor(surfaceVariantColor) - } - section.headers.forEach { header -> - headerRow.addView( - TextView(cardCtx, null, 0, R.style.TableHeaderCell).apply { - text = header - } - ) - } - table.addView(headerRow) - } - - section.rows.forEachIndexed { index, row -> - val dataRow = TableRow(cardCtx).apply { - if (index % 2 == 1) setBackgroundColor(altRowColor) - } - row.forEachIndexed { colIndex, cellText -> - dataRow.addView( - TextView(cardCtx, null, 0, R.style.TableDataCell).apply { - text = cellText - if (colIndex > 0 && section.headers.size > 2) { - gravity = Gravity.END - } - } - ) - } - table.addView(dataRow) - } - - if (section.showAllAction != null) { - val actionText = TextView(cardCtx).apply { - text = section.showAllAction - setPadding(16, 12, 16, 12) - setTextColor(MaterialColors.getColor(cardCtx, com.google.android.material.R.attr.colorPrimary, 0)) - isClickable = true - isFocusable = true - setOnClickListener { - showAllLargeFiles = true - val currentState = viewModel.uiState.value - if (currentState is ApkAnalyzerViewModel.UiState.Success) { - renderState(currentState) - } - } - } - (cardView as ViewGroup).addView(actionText) - } - - container.addView(cardView) - } - } - - private fun formatFileSize(bytes: Long): String { - val units = arrayOf("B", "KB", "MB", "GB") - var size = bytes.toDouble() - var unitIndex = 0 - while (size >= 1024 && unitIndex < units.size - 1) { - size /= 1024 - unitIndex++ - } - return String.format("%.2f %s", size, units[unitIndex]) - } + companion object { + private const val PLUGIN_ID = "com.example.apkviewer" + private const val MAX_LARGE_FILES_DISPLAYED = 10 + private const val FALLBACK_SURFACE = 0xFFFFFBFE.toInt() + private const val FALLBACK_SURFACE_VARIANT = 0xFFE7E0EC.toInt() + } + + private val viewModel by viewModels() + private var showAllLargeFiles = false + private var pendingAnalysisFile: java.io.File? = null + + private var statusText: TextView? = null + private var btnStart: Button? = null + private var progressBar: ProgressBar? = null + private var resultsContainer: LinearLayout? = null + + private val pickApkLauncher = + registerForActivityResult( + ActivityResultContracts.StartActivityForResult(), + ) { result -> + if (result.resultCode == Activity.RESULT_OK) { + result.data?.data?.let { viewModel.analyzeApk(it, requireContext().applicationContext) } + } + } + + override fun onGetLayoutInflater(savedInstanceState: Bundle?): LayoutInflater { + val inflater = super.onGetLayoutInflater(savedInstanceState) + return PluginFragmentHelper.getPluginInflater(PLUGIN_ID, inflater) + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + runCatching { + PluginFragmentHelper.getServiceRegistry(PLUGIN_ID) + } + } + + override fun onCreateView( + inflater: LayoutInflater, + container: ViewGroup?, + savedInstanceState: Bundle?, + ): View? = inflater.inflate(R.layout.fragment_sample, container, false) + + override fun onViewCreated( + view: View, + savedInstanceState: Bundle?, + ) { + super.onViewCreated(view, savedInstanceState) + statusText = view.findViewById(R.id.tv_context) + btnStart = view.findViewById(R.id.btnStart) + progressBar = view.findViewById(R.id.progressBar) + resultsContainer = view.findViewById(R.id.resultsContainer) + + btnStart?.setOnClickListener { openFilePicker() } + + viewLifecycleOwner.lifecycleScope.launch { + viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) { + viewModel.uiState.collect { state -> renderState(state) } + } + } + + val file = pendingAnalysisFile ?: viewModel.pendingFile + if (file != null) { + pendingAnalysisFile = null + viewModel.pendingFile = null + viewModel.analyzeApk(file) + } + } + + private fun renderState(state: ApkAnalyzerViewModel.UiState) { + resultsContainer?.removeAllViews() + when (state) { + is ApkAnalyzerViewModel.UiState.Idle -> { + progressBar?.visibility = View.GONE + statusText?.visibility = View.GONE + btnStart?.isEnabled = true + } + + is ApkAnalyzerViewModel.UiState.Analyzing -> { + showAllLargeFiles = false + progressBar?.visibility = View.VISIBLE + statusText?.visibility = View.VISIBLE + statusText?.text = getString(R.string.analyzing_apk) + btnStart?.isEnabled = false + } + + is ApkAnalyzerViewModel.UiState.Success -> { + progressBar?.visibility = View.GONE + statusText?.visibility = View.GONE + btnStart?.isEnabled = true + renderSections(mapToSections(state.data)) + } + + is ApkAnalyzerViewModel.UiState.Error -> { + progressBar?.visibility = View.GONE + statusText?.visibility = View.VISIBLE + statusText?.text = getString(R.string.analysis_failed, state.message) + btnStart?.isEnabled = true + } + } + } + + private fun openFilePicker() { + val intent = + Intent(Intent.ACTION_OPEN_DOCUMENT).apply { + addCategory(Intent.CATEGORY_OPENABLE) + type = "application/vnd.android.package-archive" + } + pickApkLauncher.launch(intent) + } + + fun analyzeFile(file: java.io.File) { + if (!isAdded || view == null) { + pendingAnalysisFile = file + return + } + viewModel.analyzeApk(file) + } + + private fun formatRatio( + compressed: Long, + raw: Long, + ): String = + if (raw > 0) { + String.format("%.1f%%", (compressed.toDouble() / raw.toDouble()) * 100) + } else { + getString(R.string.value_na) + } + + private fun mapToSections(data: ApkParseResult): List { + val sections = mutableListOf() + + sections.add( + TableSection( + title = getString(R.string.section_apk_structure), + headers = listOf(getString(R.string.header_property), getString(R.string.header_value)), + rows = + listOf( + listOf(getString(R.string.label_apk_file_size), formatFileSize(data.apkSize)), + listOf(getString(R.string.label_total_entries), "${data.totalEntries}"), + listOf(getString(R.string.label_uncompressed_size), formatFileSize(data.totalUncompressed)), + listOf(getString(R.string.label_compressed_size), formatFileSize(data.totalCompressed)), + listOf(getString(R.string.label_compression_ratio), formatRatio(data.totalCompressed, data.totalUncompressed)), + listOf(getString(R.string.label_directories), "${data.directoryCount}"), + listOf(getString(R.string.label_files), "${data.fileCount}"), + ), + ), + ) + + val keyFileRows = + data.keyFiles.map { kf -> + if (kf.exists) { + listOf( + kf.name, + "\u2713", + formatFileSize(kf.rawSize), + formatFileSize(kf.compressedSize), + formatRatio(kf.compressedSize, kf.rawSize), + ) + } else { + listOf(kf.name, "\u2717", "\u2014", "\u2014", "\u2014") + } + } + sections.add( + TableSection( + title = getString(R.string.section_key_files), + headers = + listOf( + getString(R.string.header_file), + "", + getString(R.string.header_raw), + getString(R.string.header_compressed), + getString(R.string.header_ratio), + ), + rows = keyFileRows, + ), + ) + + if (data.nativeLibArchitectures.isNotEmpty()) { + val totalNativeLibs = data.nativeLibArchitectures.values.sumOf { it.size } + val nativeRows = mutableListOf>() + data.nativeLibArchitectures.forEach { (arch, libs) -> + val archRaw = libs.sumOf { it.rawSize } + val archCompressed = libs.sumOf { it.compressedSize } + nativeRows.add( + listOf( + "\u25B8 $arch", + "${libs.size}", + formatFileSize(archRaw), + formatFileSize(archCompressed), + ), + ) + libs.sortedByDescending { it.rawSize }.take(3).forEach { lib -> + nativeRows.add( + listOf( + " ${lib.name}", + "", + formatFileSize(lib.rawSize), + formatFileSize(lib.compressedSize), + ), + ) + } + if (libs.size > 3) { + nativeRows.add(listOf(" +${libs.size - 3} more", "", "", "")) + } + } + sections.add( + TableSection( + title = getString(R.string.section_native_libraries, totalNativeLibs), + headers = + listOf( + getString(R.string.header_name), + getString(R.string.header_count), + getString(R.string.header_raw), + getString(R.string.header_compressed), + ), + rows = nativeRows, + ), + ) + } + + if (data.resourceDirs.isNotEmpty()) { + val resDirRows = + data.resourceDirs.map { dir -> + if (dir.rawSize > 0) { + listOf(dir.path, "${dir.fileCount}", formatFileSize(dir.rawSize), formatFileSize(dir.compressedSize)) + } else { + listOf(dir.path, "0", "\u2014", "\u2014") + } + } + sections.add( + TableSection( + title = getString(R.string.section_resource_directories, data.resourceDirs.size), + headers = + listOf( + getString(R.string.header_directory), + getString(R.string.header_files), + getString(R.string.header_raw), + getString(R.string.header_compressed), + ), + rows = resDirRows, + ), + ) + } + + if (data.largeFiles.isNotEmpty()) { + val displayedFiles = if (showAllLargeFiles) data.largeFiles else data.largeFiles.take(MAX_LARGE_FILES_DISPLAYED) + val largeFileRows = + displayedFiles.map { lf -> + listOf( + lf.name, + formatFileSize(lf.rawSize), + formatFileSize(lf.compressedSize), + formatRatio(lf.compressedSize, lf.rawSize), + ) + } + sections.add( + TableSection( + title = getString(R.string.section_large_files), + headers = + listOf( + getString(R.string.header_file), + getString(R.string.header_raw), + getString(R.string.header_compressed), + getString(R.string.header_ratio), + ), + rows = largeFileRows, + showAllAction = + if (!showAllLargeFiles && data.largeFiles.size > MAX_LARGE_FILES_DISPLAYED) { + getString(R.string.action_show_all, data.largeFiles.size) + } else { + null + }, + ), + ) + } + + val sigText = if (data.hasV1Signature) getString(R.string.value_v1_signing) else getString(R.string.value_v2_or_unsigned) + sections.add( + TableSection( + title = getString(R.string.section_apk_metadata), + headers = listOf(getString(R.string.header_property), getString(R.string.header_value)), + rows = + listOf( + listOf(getString(R.string.label_signature_scheme), sigText), + listOf( + getString(R.string.label_multi_dex), + if (data.hasMultiDex) getString(R.string.value_yes) else getString(R.string.value_no), + ), + listOf( + getString(R.string.label_code_obfuscation), + if (data.hasProguard) getString(R.string.value_detected) else getString(R.string.value_none_detected), + ), + ), + ), + ) + + return sections + } + + private fun renderSections(sections: List) { + val container = resultsContainer ?: return + val inflater = layoutInflater + val ctx = requireContext() + + val surfaceColor = MaterialColors.getColor(ctx, com.google.android.material.R.attr.colorSurface, FALLBACK_SURFACE) + val surfaceVariantColor = + MaterialColors.getColor( + ctx, + com.google.android.material.R.attr.colorSurfaceVariant, + FALLBACK_SURFACE_VARIANT, + ) + val altRowColor = ColorUtils.blendARGB(surfaceColor, surfaceVariantColor, 0.4f) + + sections.forEach { section -> + val cardView = inflater.inflate(R.layout.item_section_card, container, false) + val cardCtx = cardView.context + + cardView.findViewById(R.id.sectionTitle).text = section.title + val table = cardView.findViewById(R.id.sectionTable) + + if (section.headers.isNotEmpty()) { + val headerRow = + TableRow(cardCtx).apply { + setBackgroundColor(surfaceVariantColor) + } + section.headers.forEach { header -> + headerRow.addView( + TextView(cardCtx, null, 0, R.style.TableHeaderCell).apply { + text = header + }, + ) + } + table.addView(headerRow) + } + + section.rows.forEachIndexed { index, row -> + val dataRow = + TableRow(cardCtx).apply { + if (index % 2 == 1) setBackgroundColor(altRowColor) + } + row.forEachIndexed { colIndex, cellText -> + dataRow.addView( + TextView(cardCtx, null, 0, R.style.TableDataCell).apply { + text = cellText + if (colIndex > 0 && section.headers.size > 2) { + gravity = Gravity.END + } + }, + ) + } + table.addView(dataRow) + } + + if (section.showAllAction != null) { + val actionText = + TextView(cardCtx).apply { + text = section.showAllAction + setPadding(16, 12, 16, 12) + setTextColor(MaterialColors.getColor(cardCtx, com.google.android.material.R.attr.colorPrimary, 0)) + isClickable = true + isFocusable = true + setOnClickListener { + showAllLargeFiles = true + val currentState = viewModel.uiState.value + if (currentState is ApkAnalyzerViewModel.UiState.Success) { + renderState(currentState) + } + } + } + (cardView as ViewGroup).addView(actionText) + } + + container.addView(cardView) + } + } + + private fun formatFileSize(bytes: Long): String { + val units = arrayOf("B", "KB", "MB", "GB") + var size = bytes.toDouble() + var unitIndex = 0 + while (size >= 1024 && unitIndex < units.size - 1) { + size /= 1024 + unitIndex++ + } + return String.format("%.2f %s", size, units[unitIndex]) + } } diff --git a/app/build.gradle.kts b/app/build.gradle.kts index d0e1bfc9b5..0770b94e7a 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -72,7 +72,7 @@ android { defaultConfig { applicationId = BuildConfig.PACKAGE_NAME vectorDrawables.useSupportLibrary = true - testInstrumentationRunnerArguments["class"] = "com.itsaky.androidide.OrderedTestSuite" + testInstrumentationRunnerArguments["class"] = "org.appdevforall.codeonthego.OrderedTestSuite" } signingConfigs { @@ -633,7 +633,7 @@ tasks.register("createPluginArtifactsZip") { destinationDirectory.set(rootProject.file("assets")) } -// Fat compile-only jar published as com.itsaky.androidide:plugin-api:1.0.0. +// Fat compile-only jar published as org.appdevforall.codeonthego:plugin-api:1.0.0. // Merges the API surface plugins already compile against (plugin-api + common + // eventbus-events + idetooltips) into one coordinate. The three add-ons are // v7/v8-flavored (unlike plugin-api); their classes are ABI-neutral so v8 is used. @@ -757,10 +757,10 @@ val pluginApiKeepRules = fatJar.set(pluginApiFatJar.flatMap { it.archiveFile }) sentinelClasses.set( mapOf( - ":plugin-api" to "com.itsaky.androidide.plugins.IPlugin", - ":common" to "com.itsaky.androidide.utils.Environment", - ":eventbus-events" to "com.itsaky.androidide.eventbus.events.Event", - ":idetooltips" to "com.itsaky.androidide.idetooltips.IDETooltipItem", + ":plugin-api" to "org.appdevforall.codeonthego.plugins.IPlugin", + ":common" to "org.appdevforall.codeonthego.utils.Environment", + ":eventbus-events" to "org.appdevforall.codeonthego.eventbus.events.Event", + ":idetooltips" to "org.appdevforall.codeonthego.idetooltips.IDETooltipItem", ), ) keepRules.set(layout.buildDirectory.file("generated/proguard/plugin-api-keep.pro")) @@ -787,7 +787,7 @@ tasks.register("writePluginApiPom") { xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.itsaky.androidide + org.appdevforall.codeonthego plugin-api 1.0.0 jar @@ -810,11 +810,11 @@ tasks.register("createPluginMavenRepoZip") { archiveFileName.set("plugin-maven-repo.zip") destinationDirectory.set(rootProject.file("assets")) - into("com/itsaky/androidide/plugin-api/1.0.0") { + into("org/appdevforall/codeonthego/plugin-api/1.0.0") { from(layout.buildDirectory.file("plugin-maven-repo-staging/plugin-api-1.0.0.jar")) from(layout.buildDirectory.file("plugin-maven-repo-staging/plugin-api-1.0.0.pom")) } - // Builder tree is already in Maven layout (com/itsaky/androidide/plugins/...). + // Builder tree is already in Maven layout (org/appdevforall/codeonthego/plugins/...). from(rootProject.file("plugin-api/plugin-builder/build/plugin-maven-repo")) } diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro index d47e27c123..478ab56640 100644 --- a/app/proguard-rules.pro +++ b/app/proguard-rules.pro @@ -24,10 +24,10 @@ -keep class com.android.** { *; } # Tooling API classes --keep class com.itsaky.androidide.tooling.** { *; } +-keep class org.appdevforall.codeonthego.tooling.** { *; } # Builder model implementations --keep class com.itsaky.androidide.builder.model.** { *; } +-keep class org.appdevforall.codeonthego.builder.model.** { *; } # lsp/kotlin registers its own IntelliJ project/application services -- some # by class name in lsp/kotlin/src/main/resources/META-INF/kt-lsp/kt-lsp.xml, @@ -40,7 +40,7 @@ # then a PicoInitializationException on ModuleDependentsProvider's missing # constructor). Keep the whole package rather than list every implementation # class in AnalysisApiServiceProviders.kt individually. --keep class com.itsaky.androidide.lsp.kotlin.compiler.services.** { *; } +-keep class org.appdevforall.codeonthego.lsp.kotlin.compiler.services.** { *; } # Kotlin Analysis API (bundled in subprojects/kotlin-analysis-api, used by the # Kotlin LSP). subprojects/kotlin-analysis-api/consumer-rules.pro keeps every @@ -94,30 +94,30 @@ io.github.rosemoe.sora.widget.component.EditorCompletionAdapter adapter; int currentSelection; } --keep class com.itsaky.androidide.projects.util.StringSearch { +-keep class org.appdevforall.codeonthego.projects.util.StringSearch { packageName(java.nio.file.Path); } -keep class * implements org.antlr.v4.runtime.Lexer { (...); } --keep class * extends com.itsaky.androidide.lsp.java.providers.completion.IJavaCompletionProvider { +-keep class * extends org.appdevforall.codeonthego.lsp.java.providers.completion.IJavaCompletionProvider { (...); } --keep class com.itsaky.androidide.editor.api.IEditor { *; } --keep class * extends com.itsaky.androidide.inflater.IViewAdapter { *; } --keep class * extends com.itsaky.androidide.inflater.drawable.IDrawableParser { +-keep class org.appdevforall.codeonthego.editor.api.IEditor { *; } +-keep class * extends org.appdevforall.codeonthego.inflater.IViewAdapter { *; } +-keep class * extends org.appdevforall.codeonthego.inflater.drawable.IDrawableParser { (...); android.graphics.drawable.Drawable parse(); android.graphics.drawable.Drawable parseDrawable(); } --keep class com.itsaky.androidide.utils.DialogUtils { public ; } +-keep class org.appdevforall.codeonthego.utils.DialogUtils { public ; } # Gson model classes deserialized only via reflection (gson.fromJson(..., # X::class.java)), same "R8 strips the unreachable constructor" issue as # templates.impl.zip below. Covers OpenedFilesCache/OpenedFile (no prior # rule) as well as the APK metadata classes already listed individually. --keep class com.itsaky.androidide.models.** { *; } --keep class com.itsaky.androidide.lsp.debug.model.** { *; } +-keep class org.appdevforall.codeonthego.models.** { *; } +-keep class org.appdevforall.codeonthego.lsp.debug.model.** { *; } # Parcelable -keepclassmembers class * implements android.os.Parcelable { @@ -126,7 +126,7 @@ # Used in preferences -keep enum org.eclipse.lemminx.dom.builder.EmptyElements { *; } --keep enum com.itsaky.androidide.xml.permissions.Permission { *; } +-keep enum org.appdevforall.codeonthego.xml.permissions.Permission { *; } # Lots of native methods in tree-sitter # There are some fields as well that are accessed from native field @@ -168,7 +168,7 @@ # With no traceable constructor call, R8 strips the constructor and Gson's # runtime then reports the class as abstract ("Failed to load template # archive ... Abstract classes can't be instantiated!"). --keep class com.itsaky.androidide.templates.impl.zip.** { *; } +-keep class org.appdevforall.codeonthego.templates.impl.zip.** { *; } -keepclassmembers,allowobfuscation class * { @com.google.gson.annotations.SerializedName ; @@ -179,12 +179,12 @@ -keep,allowobfuscation,allowshrinking class * extends com.google.gson.reflect.TypeToken ## Themes --keep enum com.itsaky.androidide.ui.themes.IDETheme { +-keep enum org.appdevforall.codeonthego.ui.themes.IDETheme { *; } ## Contributor models - deserialized with GSON --keep class * implements com.itsaky.androidide.contributors.Contributor { +-keep class * implements org.appdevforall.codeonthego.contributors.Contributor { *; } @@ -268,8 +268,8 @@ ## returning emptyList()) to EmptyList, then inserts CHECKCAST at call sites. ## When a plugin returns a non-EmptyList (listOf(x), mutableListOf(), etc), ## the cast fails at runtime. --keep class com.itsaky.androidide.plugins.** { *; } --keep interface com.itsaky.androidide.plugins.** { *; } +-keep class org.appdevforall.codeonthego.plugins.** { *; } +-keep interface org.appdevforall.codeonthego.plugins.** { *; } ## ADFA-3604: JDI's SocketAttachingConnector/SocketListeningConnector are ## loaded via ServiceLoader (META-INF/services), which R8 can't trace, so it @@ -286,6 +286,6 @@ ## R8 Kotlin metadata workaround for Kotlin 2.3.0 compatibility ## Suppresses D8 errors when parsing kotlin metadata for StopWatch inline functions --keep class com.itsaky.androidide.utils.StopWatch { *; } --keepclassmembers class com.itsaky.androidide.utils.StopWatch** { *; } +-keep class org.appdevforall.codeonthego.utils.StopWatch { *; } +-keepclassmembers class org.appdevforall.codeonthego.utils.StopWatch** { *; } diff --git a/app/src/androidTest/AndroidManifest.xml b/app/src/androidTest/AndroidManifest.xml index 1a45bd4ab2..657bf4cbb3 100644 --- a/app/src/androidTest/AndroidManifest.xml +++ b/app/src/androidTest/AndroidManifest.xml @@ -1,5 +1,5 @@ - + \ No newline at end of file diff --git a/app/src/androidTest/kotlin/com/itsaky/androidide/AutomationTestSuite.kt b/app/src/androidTest/kotlin/com/itsaky/androidide/AutomationTestSuite.kt deleted file mode 100644 index b9228953eb..0000000000 --- a/app/src/androidTest/kotlin/com/itsaky/androidide/AutomationTestSuite.kt +++ /dev/null @@ -1,12 +0,0 @@ -package com.itsaky.androidide - -import org.junit.runner.RunWith -import org.junit.runners.Suite - -@RunWith(Suite::class) -@Suite.SuiteClasses( - CleanupTest::class, - AutomationEndToEndTest::class, - ExportCacheDirectoryTest::class, -) -class AutomationTestSuite diff --git a/app/src/androidTest/kotlin/com/itsaky/androidide/CleanupTest.kt b/app/src/androidTest/kotlin/com/itsaky/androidide/CleanupTest.kt deleted file mode 100644 index effaeb3aa6..0000000000 --- a/app/src/androidTest/kotlin/com/itsaky/androidide/CleanupTest.kt +++ /dev/null @@ -1,34 +0,0 @@ -package com.itsaky.androidide - -import android.app.Instrumentation -import android.os.ParcelFileDescriptor -import androidx.test.ext.junit.runners.AndroidJUnit4 -import androidx.test.platform.app.InstrumentationRegistry -import org.junit.AfterClass -import org.junit.Test -import org.junit.runner.RunWith -import java.io.FileInputStream -import java.io.IOException - -@RunWith(AndroidJUnit4::class) -class CleanupTest { - - @Test - fun performCleanup() { - try { - val command = "rm -rf /sdcard/CodeOnTheGoProjects" - executeShellCommand(command) - println("Cleanup executed successfully!") - } catch (e: IOException) { - println("Failed to execute cleanup: ${e.message}") - // Don't fail the test - cleanup is best effort - } - } - - private fun executeShellCommand(command: String): String { - val instrumentation: Instrumentation = InstrumentationRegistry.getInstrumentation() - val pfd: ParcelFileDescriptor = instrumentation.uiAutomation.executeShellCommand(command) - val fileInputStream = FileInputStream(pfd.fileDescriptor) - return fileInputStream.bufferedReader().use { it.readText() } - } -} \ No newline at end of file diff --git a/app/src/androidTest/kotlin/com/itsaky/androidide/ExportCacheDirectoryTest.kt b/app/src/androidTest/kotlin/com/itsaky/androidide/ExportCacheDirectoryTest.kt deleted file mode 100644 index 317160cb1a..0000000000 --- a/app/src/androidTest/kotlin/com/itsaky/androidide/ExportCacheDirectoryTest.kt +++ /dev/null @@ -1,98 +0,0 @@ -package com.itsaky.androidide - -import android.os.Environment -import androidx.test.ext.junit.runners.AndroidJUnit4 -import androidx.test.platform.app.InstrumentationRegistry -import org.junit.Assume.assumeTrue -import org.junit.Assert.assertTrue -import org.junit.Test -import org.junit.runner.RunWith -import java.io.File - -@RunWith(AndroidJUnit4::class) -class ExportCacheDirectoryTest { - - @Test - fun exportGradleModuleCacheBeforeConnectedTestCleanup() { - val context = InstrumentationRegistry.getInstrumentation().targetContext - val args = InstrumentationRegistry.getArguments() - - val destinationRelativePath = - args.getString(ARG_DESTINATION_RELATIVE_PATH) ?: DEFAULT_DESTINATION_RELATIVE_PATH - - val source = File(context.filesDir, SOURCE_RELATIVE_PATH) - val externalBase = File(Environment.getExternalStorageDirectory(), EXPORT_BASE_DIRECTORY).canonicalFile - val destination = resolveSafeDestination(externalBase, destinationRelativePath) - - assumeTrue("Source does not exist: ${source.absolutePath}", source.exists()) - assumeTrue("Source is not a directory: ${source.absolutePath}", source.isDirectory) - - destination.deleteRecursively() - destination.parentFile?.mkdirs() - - assertTrue( - "Failed to copy ${source.absolutePath} to ${destination.absolutePath}", - source.copyRecursively(target = destination, overwrite = true), - ) - assertTrue("Destination does not exist: ${destination.absolutePath}", destination.exists()) - } - - @Test - fun exportGeneratedGradleApiJarWhenRequested() { - val context = InstrumentationRegistry.getInstrumentation().targetContext - val args = InstrumentationRegistry.getArguments() - val version = args.getString(ARG_GRADLE_API_VERSION) - - assumeTrue("No Gradle API version requested", !version.isNullOrBlank()) - require(!version!!.contains(File.separatorChar)) { - "Gradle API version must not contain path separators: $version" - } - - val destinationRelativePath = - args.getString(ARG_GRADLE_API_DESTINATION_RELATIVE_PATH) - ?: DEFAULT_GRADLE_API_DESTINATION_RELATIVE_PATH - - val source = - File( - context.filesDir, - "$GRADLE_CACHE_RELATIVE_PATH/$version/generated-gradle-jars/gradle-api-$version.jar", - ) - val externalBase = File(Environment.getExternalStorageDirectory(), EXPORT_BASE_DIRECTORY).canonicalFile - val destinationDir = resolveSafeDestination(externalBase, destinationRelativePath) - val destination = File(destinationDir, source.name) - - assertTrue("Source does not exist: ${source.absolutePath}", source.exists()) - assertTrue("Source is not a file: ${source.absolutePath}", source.isFile) - - destination.parentFile?.mkdirs() - source.copyTo(target = destination, overwrite = true) - - assertTrue("Destination does not exist: ${destination.absolutePath}", destination.exists()) - } - - private fun resolveSafeDestination(base: File, relativePath: String): File { - require(relativePath.isNotBlank()) { - "Destination path must be a non-blank relative path" - } - require(!File(relativePath).isAbsolute) { - "Destination path must be relative" - } - - val destination = File(base, relativePath.removePrefix("$EXPORT_BASE_DIRECTORY/")).canonicalFile - require(destination.toPath().startsWith(base.toPath())) { - "Destination must stay under ${base.absolutePath}: ${destination.absolutePath}" - } - return destination - } - - private companion object { - const val SOURCE_RELATIVE_PATH = "home/.gradle/caches/modules-2/files-2.1" - const val GRADLE_CACHE_RELATIVE_PATH = "home/.gradle/caches" - const val ARG_DESTINATION_RELATIVE_PATH = "androidide.exportCache.destination" - const val ARG_GRADLE_API_VERSION = "androidide.exportGradleApi.version" - const val ARG_GRADLE_API_DESTINATION_RELATIVE_PATH = "androidide.exportGradleApi.destination" - const val EXPORT_BASE_DIRECTORY = "CodeOnTheGoProjects" - const val DEFAULT_DESTINATION_RELATIVE_PATH = "CodeOnTheGoProjects/gradle-cache/modules-2/files-2.1" - const val DEFAULT_GRADLE_API_DESTINATION_RELATIVE_PATH = "CodeOnTheGoProjects/gradle-api" - } -} diff --git a/app/src/androidTest/kotlin/com/itsaky/androidide/ProjectBuildTestWithGroovyGradle.kt b/app/src/androidTest/kotlin/com/itsaky/androidide/ProjectBuildTestWithGroovyGradle.kt deleted file mode 100644 index 72b29811e3..0000000000 --- a/app/src/androidTest/kotlin/com/itsaky/androidide/ProjectBuildTestWithGroovyGradle.kt +++ /dev/null @@ -1,209 +0,0 @@ -package com.itsaky.androidide - -import androidx.test.platform.app.InstrumentationRegistry -import com.itsaky.androidide.helper.initializeProjectAndCancelBuild -import com.itsaky.androidide.helper.navigateToMainScreen -import com.itsaky.androidide.helper.selectProjectTemplate -import com.itsaky.androidide.screens.HomeScreen.clickCreateProjectHomeScreen -import com.itsaky.androidide.screens.ProjectSettingsScreen.clickCreateProjectProjectSettings -import com.itsaky.androidide.screens.ProjectSettingsScreen.selectJavaLanguage -import com.itsaky.androidide.screens.ProjectSettingsScreen.selectKotlinLanguage -import com.itsaky.androidide.screens.ProjectSettingsScreen.uncheckKotlinScript -import com.kaspersky.kaspresso.testcases.api.testcase.TestCase -import org.junit.Test - - -class ProjectBuildTestWithGroovyGradle : TestCase() { - - @Test - fun test_projectBuild_emptyProject_java_groovyGradle() { - run { - navigateToMainScreen() - clickCreateProjectHomeScreen() - selectProjectTemplate( - "Select the empty project", - R.string.template_empty - ) - selectJavaLanguage() - uncheckKotlinScript() - clickCreateProjectProjectSettings() - initializeProjectAndCancelBuild() - } - } - - @Test - fun test_projectBuild_emptyProject_kotlin_groovyGradle() { - run { - navigateToMainScreen() - clickCreateProjectHomeScreen() - selectProjectTemplate( - "Select the empty project", - R.string.template_empty - ) - selectKotlinLanguage() - uncheckKotlinScript() - clickCreateProjectProjectSettings() - initializeProjectAndCancelBuild() - } - } - - @Test - fun test_projectBuild_baseProject_java_groovyGradle() { - run { - navigateToMainScreen() - clickCreateProjectHomeScreen() - selectProjectTemplate( - "Select the basic project", - R.string.template_basic - ) - selectJavaLanguage() - uncheckKotlinScript() - clickCreateProjectProjectSettings() - initializeProjectAndCancelBuild() - } - } - - @Test - fun test_projectBuild_baseProject_kotlin_groovyGradle() { - run { - navigateToMainScreen() - clickCreateProjectHomeScreen() - selectProjectTemplate( - "Select the basic project", - R.string.template_basic - ) - selectKotlinLanguage() - uncheckKotlinScript() - clickCreateProjectProjectSettings() - initializeProjectAndCancelBuild() - } - } - - @Test - fun test_projectBuild_navigationDrawerProject_java_groovyGradle() { - run { - navigateToMainScreen() - clickCreateProjectHomeScreen() - selectProjectTemplate( - "Select the navigation drawer project", - R.string.template_navigation_drawer - ) - selectJavaLanguage() - uncheckKotlinScript() - clickCreateProjectProjectSettings() - initializeProjectAndCancelBuild() - } - } - - @Test - fun test_projectBuild_navigationDrawerProject_kotlin_groovyGradle() { - run { - navigateToMainScreen() - clickCreateProjectHomeScreen() - selectProjectTemplate( - "Select the navigation drawer project", - R.string.template_navigation_drawer - ) - selectKotlinLanguage() - uncheckKotlinScript() - clickCreateProjectProjectSettings() - initializeProjectAndCancelBuild() - } - } - - @Test - fun test_projectBuild_bottomNavigationProject_java_groovyGradle() { - run { - navigateToMainScreen() - clickCreateProjectHomeScreen() - selectProjectTemplate( - "Select the bottom navigation project", - R.string.template_navigation_tabs - ) - selectJavaLanguage() - uncheckKotlinScript() - clickCreateProjectProjectSettings() - initializeProjectAndCancelBuild() - } - } - - @Test - fun test_projectBuild_bottomNavigationProject_kotlin_groovyGradle() { - run { - navigateToMainScreen() - clickCreateProjectHomeScreen() - selectProjectTemplate( - "Select the bottom navigation project", - R.string.template_navigation_tabs - ) - selectKotlinLanguage() - uncheckKotlinScript() - clickCreateProjectProjectSettings() - initializeProjectAndCancelBuild() - } - } - - @Test - fun test_projectBuild_tabbedActivityProject_java_groovyGradle() { - run { - navigateToMainScreen() - clickCreateProjectHomeScreen() - selectProjectTemplate( - "Select the tabbed activity project", - R.string.template_tabs - ) - selectJavaLanguage() - uncheckKotlinScript() - clickCreateProjectProjectSettings() - initializeProjectAndCancelBuild() - } - } - - @Test - fun test_projectBuild_tabbedActivityProject_kotlin_groovyGradle() { - run { - navigateToMainScreen() - clickCreateProjectHomeScreen() - selectProjectTemplate( - "Select the tabbed activity project", - R.string.template_tabs - ) - selectKotlinLanguage() - uncheckKotlinScript() - clickCreateProjectProjectSettings() - initializeProjectAndCancelBuild() - } - } - - @Test - fun test_projectBuild_noAndroidXProject_java_groovyGradle() { - run { - navigateToMainScreen() - clickCreateProjectHomeScreen() - selectProjectTemplate( - "Select the no AndroidX project", - R.string.template_no_AndroidX - ) - selectJavaLanguage() - uncheckKotlinScript() - clickCreateProjectProjectSettings() - initializeProjectAndCancelBuild() - } - } - - @Test - fun test_projectBuild_noAndroidXProject_kotlin_groovyGradle() { - run { - navigateToMainScreen() - clickCreateProjectHomeScreen() - selectProjectTemplate( - "Select the no AndroidX project", - R.string.template_no_AndroidX - ) - selectKotlinLanguage() - uncheckKotlinScript() - clickCreateProjectProjectSettings() - initializeProjectAndCancelBuild() - } - } -} \ No newline at end of file diff --git a/app/src/androidTest/kotlin/com/itsaky/androidide/ProjectBuildTestWithKtsGradle.kt b/app/src/androidTest/kotlin/com/itsaky/androidide/ProjectBuildTestWithKtsGradle.kt deleted file mode 100644 index 9bde1720c2..0000000000 --- a/app/src/androidTest/kotlin/com/itsaky/androidide/ProjectBuildTestWithKtsGradle.kt +++ /dev/null @@ -1,241 +0,0 @@ -package com.itsaky.androidide - -import androidx.test.platform.app.InstrumentationRegistry -import com.itsaky.androidide.helper.initializeProjectAndCancelBuild -import com.itsaky.androidide.helper.navigateToMainScreen -import com.itsaky.androidide.helper.selectProjectTemplate -import com.itsaky.androidide.screens.HomeScreen.clickCreateProjectHomeScreen -import com.itsaky.androidide.screens.ProjectSettingsScreen.clickCreateProjectProjectSettings -import com.itsaky.androidide.screens.ProjectSettingsScreen.selectJavaLanguage -import com.itsaky.androidide.screens.ProjectSettingsScreen.selectKotlinLanguage -import com.kaspersky.kaspresso.testcases.api.testcase.TestCase -import org.junit.Test - -class ProjectBuildTestWithKtsGradle : TestCase() { - - - @Test - fun test_projectBuild_emptyProject_java() { - run { - navigateToMainScreen() - clickCreateProjectHomeScreen() - selectProjectTemplate( - "Select the empty project", - R.string.template_empty - ) - selectJavaLanguage() - clickCreateProjectProjectSettings() - initializeProjectAndCancelBuild() - } - } - - @Test - fun test_projectBuild_emptyProject_kotlin() { - run { - navigateToMainScreen() - clickCreateProjectHomeScreen() - selectProjectTemplate( - "Select the empty project", - R.string.template_empty - ) - selectKotlinLanguage() - clickCreateProjectProjectSettings() - initializeProjectAndCancelBuild() - } - } - - @Test - fun test_projectBuild_baseProject_java() { - run { - navigateToMainScreen() - clickCreateProjectHomeScreen() - selectProjectTemplate( - "Select the basic project", - R.string.template_basic - ) - selectJavaLanguage() - clickCreateProjectProjectSettings() - initializeProjectAndCancelBuild() - } - } - - @Test - fun test_projectBuild_baseProject_kotlin() { - run { - step("Navigate to main screen") { - // Ensure consistent start state with increased timeout - flakySafely(timeoutMs = 30000) { - navigateToMainScreen() - } - } - - step("Click create project on home screen") { - flakySafely(timeoutMs = 10000) { - clickCreateProjectHomeScreen() - } - } - - step("Select the basic project template") { - flakySafely(timeoutMs = 10000) { - selectProjectTemplate( - "Select the basic project", - R.string.template_basic - ) - } - } - - step("Select Kotlin language") { - flakySafely(timeoutMs = 10000) { - selectKotlinLanguage() - } - } - - step("Click create project on settings screen") { - flakySafely(timeoutMs = 10000) { - clickCreateProjectProjectSettings() - } - } - - step("Initialize project and cancel build") { - flakySafely(timeoutMs = 10000) { - initializeProjectAndCancelBuild() - } - } - } - } - - @Test - fun test_projectBuild_navigationDrawerProject_java() { - run { - navigateToMainScreen() - clickCreateProjectHomeScreen() - selectProjectTemplate( - "Select the navigation drawer project", - R.string.template_navigation_drawer - ) - selectJavaLanguage() - clickCreateProjectProjectSettings() - initializeProjectAndCancelBuild() - } - } - - @Test - fun test_projectBuild_navigationDrawerProject_kotlin() { - run { - navigateToMainScreen() - clickCreateProjectHomeScreen() - selectProjectTemplate( - "Select the navigation drawer project", - R.string.template_navigation_drawer - ) - selectKotlinLanguage() - clickCreateProjectProjectSettings() - initializeProjectAndCancelBuild() - } - } - - @Test - fun test_projectBuild_bottomNavigationProject_java() { - run { - navigateToMainScreen() - clickCreateProjectHomeScreen() - selectProjectTemplate( - "Select the bottom navigation project", - R.string.template_navigation_tabs - ) - selectJavaLanguage() - clickCreateProjectProjectSettings() - initializeProjectAndCancelBuild() - } - } - - @Test - fun test_projectBuild_bottomNavigationProject_kotlin() { - run { - navigateToMainScreen() - clickCreateProjectHomeScreen() - selectProjectTemplate( - "Select the bottom navigation project", - R.string.template_navigation_tabs - ) - selectKotlinLanguage() - clickCreateProjectProjectSettings() - initializeProjectAndCancelBuild() - } - } - - @Test - fun test_projectBuild_tabbedActivityProject_java() { - run { - navigateToMainScreen() - clickCreateProjectHomeScreen() - selectProjectTemplate( - "Select the tabbed activity project", - R.string.template_tabs - ) - selectJavaLanguage() - clickCreateProjectProjectSettings() - initializeProjectAndCancelBuild() - } - } - - @Test - fun test_projectBuild_tabbedActivityProject_kotlin() { - run { - navigateToMainScreen() - clickCreateProjectHomeScreen() - selectProjectTemplate( - "Select the tabbed activity project", - R.string.template_tabs - ) - selectKotlinLanguage() - clickCreateProjectProjectSettings() - initializeProjectAndCancelBuild() - } - } - - @Test - fun test_projectBuild_noAnd2roidXProject_java() { - run { - navigateToMainScreen() - clickCreateProjectHomeScreen() - selectProjectTemplate( - "Select the no AndroidX project", - R.string.template_no_AndroidX - ) - selectJavaLanguage() - clickCreateProjectProjectSettings() - initializeProjectAndCancelBuild() - } - } - - @Test - fun test_projectBuild_noAndroidXProject_kotlin() { - run { - navigateToMainScreen() - clickCreateProjectHomeScreen() - selectProjectTemplate( - "Select the no AndroidX project", - R.string.template_no_AndroidX - ) - selectKotlinLanguage() - clickCreateProjectProjectSettings() - initializeProjectAndCancelBuild() - } - } - -// TODO: to be uncommented out when the compose project template is fixed -// @Test -// fun test_projectBuild_composeProject() { -// run { -// navigateToMainScreen() -// clickCreateProjectHomeScreen() -// selectProjectTemplate( -// "Select the no Compose project", -// R.string.template_compose -// ) -// clickCreateProjectProjectSettings() -// initializeProjectAndCancelBuild() -// } -// } -} diff --git a/app/src/androidTest/kotlin/com/itsaky/androidide/helper/AdvancePastWelcomeScreenHelper.kt b/app/src/androidTest/kotlin/com/itsaky/androidide/helper/AdvancePastWelcomeScreenHelper.kt deleted file mode 100644 index ffbe5a17d6..0000000000 --- a/app/src/androidTest/kotlin/com/itsaky/androidide/helper/AdvancePastWelcomeScreenHelper.kt +++ /dev/null @@ -1,60 +0,0 @@ -package com.itsaky.androidide.helper - -import android.view.accessibility.AccessibilityNodeInfo -import androidx.test.platform.app.InstrumentationRegistry -import com.kaspersky.kaspresso.testcases.core.testcontext.TestContext - -/** - * Clicks the Next button on the welcome screen using accessibility ACTION_CLICK. - * The button is in the system gesture exclusion zone so coordinate-based clicks fail. - */ -fun TestContext.advancePastWelcomeScreen() { - step("Click continue button on the Welcome Screen") { - flakySafely(timeoutMs = 3_000) { - device.uiDevice.waitForIdle() - - val clicked = accessibilityClickByDescription("NEXT") - || accessibilityClickByText("Next") - || accessibilityClickByText("Continue") - - if (!clicked) { - throw AssertionError("Next/Continue button not found on welcome screen") - } - device.uiDevice.waitForIdle() - } - } -} - -private fun accessibilityClickByDescription(desc: String): Boolean { - val root = InstrumentationRegistry.getInstrumentation().uiAutomation - .rootInActiveWindow ?: return false - val nodes = root.findAccessibilityNodeInfosByText(desc) - for (node in nodes) { - if (node.contentDescription?.toString()?.contains(desc, ignoreCase = true) == true) { - val result = node.performAction(AccessibilityNodeInfo.ACTION_CLICK) - node.recycle() - root.recycle() - return result - } - node.recycle() - } - root.recycle() - return false -} - -private fun accessibilityClickByText(text: String): Boolean { - val root = InstrumentationRegistry.getInstrumentation().uiAutomation - .rootInActiveWindow ?: return false - val nodes = root.findAccessibilityNodeInfosByText(text) - for (node in nodes) { - if (node.text?.toString()?.contains(text, ignoreCase = true) == true) { - val result = node.performAction(AccessibilityNodeInfo.ACTION_CLICK) - node.recycle() - root.recycle() - return result - } - node.recycle() - } - root.recycle() - return false -} diff --git a/app/src/androidTest/kotlin/com/itsaky/androidide/helper/ProjectBuildHelper.kt b/app/src/androidTest/kotlin/com/itsaky/androidide/helper/ProjectBuildHelper.kt deleted file mode 100644 index 55aac447be..0000000000 --- a/app/src/androidTest/kotlin/com/itsaky/androidide/helper/ProjectBuildHelper.kt +++ /dev/null @@ -1,48 +0,0 @@ -package com.itsaky.androidide.helper - -import com.itsaky.androidide.scenarios.InitializationProjectAndCancelingBuildScenario -import com.itsaky.androidide.scenarios.NavigateToMainScreenScenario -import com.itsaky.androidide.scenarios.RunAssembleTasksScenario -import com.itsaky.androidide.screens.TemplateScreen.selectTemplate -import com.kaspersky.kaspresso.testcases.core.testcontext.TestContext - -fun TestContext.navigateToMainScreen() { - step("Initialize the app and navigate to the Main Screen") { - scenario(NavigateToMainScreenScenario()) - } -} - -fun TestContext.selectProjectTemplate( - stepTitle: String, - templateResId: Int, - visibleTextOverride: String? = null, -) { - step(stepTitle) { - selectTemplate(templateResId, visibleTextOverride) - } -} - -fun TestContext.initializeProjectAndCancelBuild() { - step("Initialization the project and cancelling the build") { - scenario(InitializationProjectAndCancelingBuildScenario()) - } -} - -fun TestContext.initializeProjectRunAssembleTasksAndCancelBuild() { - step("Initialize project, quick-run debug build, and run assemble task set") { - var failure: Throwable? = null - try { - scenario(InitializationProjectAndCancelingBuildScenario(closeProjectAfterBuild = false)) - scenario(RunAssembleTasksScenario()) - } catch (throwable: Throwable) { - failure = throwable - throw throwable - } finally { - runCatching { - scenario(InitializationProjectAndCancelingBuildScenario.CloseProjectScenario()) - }.onFailure { closeFailure -> - failure?.addSuppressed(closeFailure) ?: throw closeFailure - } - } - } -} diff --git a/app/src/androidTest/kotlin/com/itsaky/androidide/scenarios/NavigateToMainScreenScenario.kt b/app/src/androidTest/kotlin/com/itsaky/androidide/scenarios/NavigateToMainScreenScenario.kt deleted file mode 100644 index cf83459e1b..0000000000 --- a/app/src/androidTest/kotlin/com/itsaky/androidide/scenarios/NavigateToMainScreenScenario.kt +++ /dev/null @@ -1,126 +0,0 @@ -package com.itsaky.androidide.scenarios - -import com.itsaky.androidide.helper.advancePastWelcomeScreen -import com.itsaky.androidide.helper.clickFirstAccessibilityNodeByText -import com.itsaky.androidide.helper.grantAllRequiredPermissionsThroughOnboardingUi -import com.itsaky.androidide.helper.logOnboardingNavigation -import com.itsaky.androidide.helper.waitForMainHomeOrEditorUi -import com.itsaky.androidide.screens.InstallToolsScreen -import com.itsaky.androidide.screens.PermissionScreen -import com.kaspersky.kaspresso.testcases.api.scenario.Scenario -import com.kaspersky.kaspresso.testcases.core.testcontext.TestContext -import androidx.test.platform.app.InstrumentationRegistry -import androidx.test.uiautomator.UiSelector - -/** - * Navigates from whatever the current onboarding state is to the main screen. - * - * Each step checks whether it's needed before acting, so this scenario is - * idempotent — safe to call whether onboarding is at the welcome screen, - * the permissions list, or already on the main screen. - */ -class NavigateToMainScreenScenario : Scenario() { - - override val steps: TestContext.() -> Unit = { - logOnboardingNavigation("NavigateToMainScreenScenario: starting") - - val d = device.uiDevice - val pkg = InstrumentationRegistry.getInstrumentation().targetContext.packageName - - // If we're already on the main screen, skip everything - step("Check if already on main screen") { - d.waitForIdle() - val getStarted = d.findObject(UiSelector().resourceIdMatches(".*:id/getStarted")) - val editor = d.findObject(UiSelector().resourceIdMatches(".*:id/editor_appBarLayout")) - if (getStarted.waitForExists(1_000) || editor.exists()) { - logOnboardingNavigation("Already on main screen — skipping onboarding") - return@step - } - } - - // If the welcome screen NEXT button is visible, advance past it - step("Advance past welcome screen (if showing)") { - val nextBtn = d.findObject(UiSelector().descriptionContains("NEXT")) - val permissionTitle = d.findObject(UiSelector().resourceIdMatches(".*:id/onboarding_title")) - // Only advance if we appear to be on the welcome slide (NEXT visible but not yet on permissions) - if (nextBtn.waitForExists(1_000)) { - // Check if we're on the welcome slide vs permissions info slide - // The welcome slide has a greeting title, not the permissions title - val greetingTitle = d.findObject(UiSelector().resourceIdMatches(".*:id/title").textContains("Code on the Go")) - if (greetingTitle.exists()) { - logOnboardingNavigation("Welcome screen visible — advancing") - advancePastWelcomeScreen() - } - } - } - - // If the privacy dialog is showing, accept it - step("Accept privacy dialog (if showing)") { - val ctx = InstrumentationRegistry.getInstrumentation().targetContext - val accept = ctx.getString(com.itsaky.androidide.resources.R.string.privacy_disclosure_accept) - val btn = d.findObject(UiSelector().text(accept)) - if (btn.waitForExists(1_000)) { - logOnboardingNavigation("Privacy dialog visible — accepting") - clickFirstAccessibilityNodeByText(accept) - d.waitForIdle() - } - } - - // If the permission list is showing, grant all permissions - step("Grant permissions (if on permission list)") { - val permScreen = d.findObject(UiSelector().resourceIdMatches(".*:id/onboarding_items")) - if (permScreen.waitForExists(2_000)) { - val ctx = InstrumentationRegistry.getInstrumentation().targetContext - val grantText = ctx.getString(com.itsaky.androidide.R.string.title_grant) - val grantBtn = d.findObject(UiSelector().text(grantText)) - if (grantBtn.exists()) { - logOnboardingNavigation("Permission list visible with ungranted permissions — granting") - grantAllRequiredPermissionsThroughOnboardingUi() - } - } - } - - step("Finish installation (leave permission screen)") { - flakySafely(timeoutMs = 20_000) { - PermissionScreen { - finishInstallationButton { - isVisible() - isEnabled() - isClickable() - click() - } - } - } - } - - step("After Finish installation: optional AppIntro Done, then wait for IDE setup -> main UI") { - logOnboardingNavigation( - "Permissions Finish starts in-app IDE setup; AppIntro R.id.done is often absent — waiting for main UI", - ) - runCatching { - flakySafely(timeoutMs = 12_000) { - InstallToolsScreen.doneButton { - isVisible() - click() - } - } - }.fold( - onSuccess = { logOnboardingNavigation("Clicked legacy AppIntro Done (optional)") }, - onFailure = { - logOnboardingNavigation( - "No AppIntro Done within 12s (expected): ${it.javaClass.simpleName} ${it.message}", - ) - }, - ) - waitForMainHomeOrEditorUi(device.uiDevice, maxWaitMs = 300_000L) - } - - step("Decline runtime permission dialog if still shown") { - runCatching { - flakySafely(timeoutMs = 8000) { - device.permissions.denyViaDialog() - } - } - } - } -} diff --git a/app/src/androidTest/kotlin/com/itsaky/androidide/scenarios/RunAssembleTasksScenario.kt b/app/src/androidTest/kotlin/com/itsaky/androidide/scenarios/RunAssembleTasksScenario.kt deleted file mode 100644 index 37aa151486..0000000000 --- a/app/src/androidTest/kotlin/com/itsaky/androidide/scenarios/RunAssembleTasksScenario.kt +++ /dev/null @@ -1,167 +0,0 @@ -package com.itsaky.androidide.scenarios - -import android.util.Log -import androidx.test.platform.app.InstrumentationRegistry -import androidx.test.uiautomator.UiScrollable -import androidx.test.uiautomator.UiSelector -import com.itsaky.androidide.R -import com.itsaky.androidide.helper.clickFirstAccessibilityNodeByDescription -import com.itsaky.androidide.helper.clickFirstAccessibilityNodeParentByText -import com.kaspersky.kaspresso.testcases.api.scenario.Scenario -import com.kaspersky.kaspresso.testcases.core.testcontext.TestContext - -private const val RUN_ASSEMBLE_TAG = "RunAssembleTasks" -private const val SHORT_UI_TIMEOUT_MS = 2_000L -private const val DEFAULT_UI_TIMEOUT_MS = 3_000L -private const val INSTALLER_GONE_TIMEOUT_MS = 5_000L -private const val RUN_TASKS_DIALOG_TIMEOUT_MS = 10_000L -private const val TASK_SELECTION_TIMEOUT_MS = 20_000L -private const val EDITOR_TOOLBAR_TIMEOUT_MS = 30_000L -private const val BUILD_LOG_INTERVAL_MS = 10_000L -private const val POLL_INTERVAL_MS = 1_000L - -private fun runAssembleLog(message: String) { - Log.e(RUN_ASSEMBLE_TAG, message) - System.err.println("$RUN_ASSEMBLE_TAG: $message") -} - -class RunAssembleTasksScenario( - private val tasks: List = DEFAULT_ASSEMBLE_TASKS, -) : Scenario() { - - override val steps: TestContext.() -> Unit = { - step("Dismiss post-build overlays before running assemble tasks") { - val d = device.uiDevice - val dismiss = d.findObject(UiSelector().text("Dismiss")) - if (dismiss.waitForExists(DEFAULT_UI_TIMEOUT_MS)) { - dismiss.click() - d.waitForIdle() - } - val installer = d.findObject( - UiSelector().packageNameMatches(".*packageinstaller.*|.*permissioncontroller.*") - ) - if (installer.exists()) { - runAssembleLog("Package installer still visible before assemble tasks; dismissing") - val cancel = d.findObject(UiSelector().textMatches("(?i)cancel")) - if (cancel.waitForExists(SHORT_UI_TIMEOUT_MS)) { - cancel.click() - } else { - d.pressBack() - } - runCatching { installer.waitUntilGone(INSTALLER_GONE_TIMEOUT_MS) } - d.waitForIdle() - } - } - - step("Open Run tasks dialog") { - val d = device.uiDevice - val targetContext = InstrumentationRegistry.getInstrumentation().targetContext - val runTasksDescription = targetContext.getString(R.string.cd_toolbar_run_gradle_tasks) - val toolbar = d.findObject(UiSelector().resourceIdMatches(".*:id/editor_appBarLayout")) - check(toolbar.waitForExists(EDITOR_TOOLBAR_TIMEOUT_MS)) { "Editor toolbar not found" } - clickFirstAccessibilityNodeByDescription(runTasksDescription) - d.waitForIdle() - - val title = targetContext.getString(R.string.title_run_tasks) - check(d.findObject(UiSelector().text(title)).waitForExists(RUN_TASKS_DIALOG_TIMEOUT_MS)) { - "Run tasks dialog did not open" - } - } - - step("Filter assemble tasks") { - val d = device.uiDevice - val search = d.findObject(UiSelector().className("android.widget.EditText")) - check(search.waitForExists(RUN_TASKS_DIALOG_TIMEOUT_MS)) { "Run tasks search field not found" } - search.setText("assemble") - d.waitForIdle() - } - - tasks.forEach { task -> - step("Select Gradle task $task") { - val d = device.uiDevice - var taskNode = d.findObject(UiSelector().text(task)) - if (!taskNode.waitForExists(DEFAULT_UI_TIMEOUT_MS)) { - UiScrollable(UiSelector().scrollable(true)).scrollTextIntoView(task) - taskNode = d.findObject(UiSelector().text(task)) - } - check(taskNode.waitForExists(TASK_SELECTION_TIMEOUT_MS)) { - "Task not found in Run tasks dialog: $task" - } - clickFirstAccessibilityNodeParentByText(task) - d.waitForIdle() - } - } - - step("Confirm and run selected Gradle tasks") { - val d = device.uiDevice - val runButton = d.findObject(UiSelector().resourceIdMatches(".*:id/exec")) - check(runButton.waitForExists(RUN_TASKS_DIALOG_TIMEOUT_MS)) { "Run tasks execute button not found" } - runButton.click() - d.waitForIdle() - - tasks.forEach { task -> - check(d.findObject(UiSelector().textContains(task)).waitForExists(RUN_TASKS_DIALOG_TIMEOUT_MS)) { - "Run tasks confirmation missing selected task: $task" - } - } - - runButton.click() - d.waitForIdle() - runAssembleLog("Selected assemble tasks submitted") - } - - step("Wait for selected Gradle tasks to finish") { - runAssembleLog("Waiting for selected assemble tasks to finish") - val d = device.uiDevice - val success = d.findObject(UiSelector().textContains("Build completed successfully")) - val gradleSuccess = d.findObject(UiSelector().textContains("BUILD SUCCESSFUL")) - val failure = d.findObject(UiSelector().textContains("Build failed")) - val gradleFailure = d.findObject(UiSelector().textContains("BUILD FAILED")) - - val deadline = System.currentTimeMillis() + BUILD_TIMEOUT_MS - var lastLogAt = 0L - var completed = false - - while (System.currentTimeMillis() < deadline && !completed) { - if (success.exists() || gradleSuccess.exists()) { - completed = true - break - } - - check(!failure.exists() && !gradleFailure.exists()) { - "Selected Gradle tasks failed" - } - - val now = System.currentTimeMillis() - if (now - lastLogAt > BUILD_LOG_INTERVAL_MS) { - runAssembleLog("Still waiting for selected assemble tasks to finish") - lastLogAt = now - } - - Thread.sleep(POLL_INTERVAL_MS) - d.waitForIdle() - } - - check(completed) { - "Timed out waiting for selected Gradle tasks to complete" - } - runAssembleLog("Selected assemble tasks finished; continuing to close project") - d.waitForIdle() - } - } - - companion object { - val DEFAULT_ASSEMBLE_TASKS = listOf( - ":app:assemble", - ":app:assembleAndroidTest", - ":app:assembleDebug", - ":app:assembleDebugAndroidTest", - ":app:assembleDebugUnitTest", - ":app:assembleRelease", - ":app:assembleReleaseUnitTest", - ":app:assembleUnitTest", - ) - - private const val BUILD_TIMEOUT_MS = 10 * 60 * 1000L - } -} diff --git a/app/src/androidTest/kotlin/com/itsaky/androidide/screens/EditorScreen.kt b/app/src/androidTest/kotlin/com/itsaky/androidide/screens/EditorScreen.kt deleted file mode 100644 index 1aff39405a..0000000000 --- a/app/src/androidTest/kotlin/com/itsaky/androidide/screens/EditorScreen.kt +++ /dev/null @@ -1,15 +0,0 @@ -package com.itsaky.androidide.screens - -import com.kaspersky.kaspresso.screens.KScreen -import io.github.kakaocup.kakao.dialog.KAlertDialog - -object EditorScreen : KScreen() { - - override val layoutId: Int? = null - - override val viewClass: Class<*>? = null - - val firstBuildDialog = KAlertDialog() - - val closeProjectDialog = KAlertDialog() -} \ No newline at end of file diff --git a/app/src/androidTest/kotlin/com/itsaky/androidide/screens/InstallToolsScreen.kt b/app/src/androidTest/kotlin/com/itsaky/androidide/screens/InstallToolsScreen.kt deleted file mode 100644 index e224d84456..0000000000 --- a/app/src/androidTest/kotlin/com/itsaky/androidide/screens/InstallToolsScreen.kt +++ /dev/null @@ -1,13 +0,0 @@ -package com.itsaky.androidide.screens - -import com.itsaky.androidide.R -import com.kaspersky.kaspresso.screens.KScreen -import io.github.kakaocup.kakao.text.KButton - -object InstallToolsScreen : KScreen() { - - override val layoutId: Int? = null - override val viewClass: Class<*>? = null - - val doneButton = KButton { withId(R.id.done) } -} \ No newline at end of file diff --git a/app/src/androidTest/kotlin/com/itsaky/androidide/screens/OnboardingScreen.kt b/app/src/androidTest/kotlin/com/itsaky/androidide/screens/OnboardingScreen.kt deleted file mode 100644 index 30a988a5a6..0000000000 --- a/app/src/androidTest/kotlin/com/itsaky/androidide/screens/OnboardingScreen.kt +++ /dev/null @@ -1,22 +0,0 @@ -package com.itsaky.androidide.screens - -import com.itsaky.androidide.R -import com.kaspersky.kaspresso.screens.KScreen -import io.github.kakaocup.kakao.text.KButton -import io.github.kakaocup.kakao.text.KTextView - -object OnboardingScreen : KScreen() { - - override val layoutId: Int? = null - override val viewClass: Class<*>? = null - - val greetingTitle = KTextView { - withId(R.id.title) - isDisplayed() - } - val greetingSubtitle = KTextView { - withId(R.id.description) - isDisplayed() - } - val nextButton = KButton { withId(R.id.next) } -} \ No newline at end of file diff --git a/app/src/androidTest/kotlin/com/itsaky/androidide/screens/PermissionScreen.kt b/app/src/androidTest/kotlin/com/itsaky/androidide/screens/PermissionScreen.kt deleted file mode 100644 index 50b158eea4..0000000000 --- a/app/src/androidTest/kotlin/com/itsaky/androidide/screens/PermissionScreen.kt +++ /dev/null @@ -1,33 +0,0 @@ -package com.itsaky.androidide.screens - -import android.view.View -import com.itsaky.androidide.R -import com.kaspersky.kaspresso.screens.KScreen -import io.github.kakaocup.kakao.recycler.KRecyclerItem -import io.github.kakaocup.kakao.recycler.KRecyclerView -import io.github.kakaocup.kakao.text.KButton -import io.github.kakaocup.kakao.text.KTextView -import org.hamcrest.Matcher - -object PermissionScreen : KScreen() { - - override val layoutId: Int? = null - override val viewClass: Class<*>? = null - - val title = KTextView { withText(R.string.onboarding_title_permissions) } - val subTitle = KTextView { withText(R.string.onboarding_subtitle_permissions) } - - val rvPermissions = KRecyclerView( - builder = { withId(R.id.onboarding_items) }, - itemTypeBuilder = { itemType(::PermissionItem) } - ) - - val finishInstallationButton = KButton { withId(R.id.finish_installation_button) } - - class PermissionItem(matcher: Matcher) : KRecyclerItem(matcher) { - - val grantButton = KButton(matcher) { withId(R.id.grant_button) } - val title = KTextView(matcher) { withId(R.id.title) } - val description = KTextView(matcher) { withId(R.id.description) } - } -} \ No newline at end of file diff --git a/app/src/androidTest/kotlin/com/itsaky/androidide/screens/ProjectSettingsScreen.kt b/app/src/androidTest/kotlin/com/itsaky/androidide/screens/ProjectSettingsScreen.kt deleted file mode 100644 index 4f2935b96a..0000000000 --- a/app/src/androidTest/kotlin/com/itsaky/androidide/screens/ProjectSettingsScreen.kt +++ /dev/null @@ -1,127 +0,0 @@ -package com.itsaky.androidide.screens - -import androidx.test.uiautomator.UiSelector -import com.itsaky.androidide.R -import com.itsaky.androidide.helper.clickFirstAccessibilityNodeByText -import com.itsaky.androidide.helper.setAccessibilityEditText -import com.kaspersky.kaspresso.screens.KScreen -import com.kaspersky.kaspresso.testcases.core.testcontext.TestContext -import io.github.kakaocup.kakao.check.KCheckBox -import io.github.kakaocup.kakao.spinner.KSpinner -import io.github.kakaocup.kakao.spinner.KSpinnerItem -import io.github.kakaocup.kakao.text.KButton - -private const val KOTLIN_LANGUAGE_SELECTION_TIMEOUT_MS = 30_000L -private const val LANGUAGE_OPTION_TIMEOUT_MS = 5_000L -private const val LANGUAGE_DROPDOWN_EXPANSION_TIMEOUT_MS = 2_000L -private const val PROJECT_NAME_FIELD_TIMEOUT_MS = 3_000L -private const val LANGUAGE_DROPDOWN_FALLBACK_X_OFFSET = 80 - -object ProjectSettingsScreen : KScreen() { - - override val layoutId: Int? = null - - override val viewClass: Class<*>? = null - - val createProjectButton = KButton { - withText(R.string.create_project) - withId(R.id.finish) - } - - val spinner = KSpinner( - builder = { withHint("Project Language") }, - itemTypeBuilder = { itemType(::KSpinnerItem) } - ) - - val kotlinScriptText = KCheckBox { - withText(R.string.msg_use_kts) - } - - fun TestContext.selectJavaLanguage() { - step("Select the java language") { - val javaText = device.targetContext.getString(R.string.lang_java) - ProjectSettingsScreen { - spinner { - isVisible() - open() - - childAt(0) { - isVisible() - hasText(javaText) - click() - } - } - } - } - } - - fun TestContext.selectKotlinLanguage() { - step("Select the kotlin language") { - flakySafely(KOTLIN_LANGUAGE_SELECTION_TIMEOUT_MS) { - val kotlinText = device.targetContext.getString(R.string.lang_kotlin) - openProjectLanguageDropdown() - - val d = device.uiDevice - val kotlin = d.findObject(UiSelector().text(kotlinText)) - check(kotlin.waitForExists(LANGUAGE_OPTION_TIMEOUT_MS)) { "Kotlin language option not found" } - kotlin.click() - d.waitForIdle() - } - } - } - - private fun TestContext.openProjectLanguageDropdown() { - val d = device.uiDevice - val javaText = device.targetContext.getString(R.string.lang_java) - val kotlinText = device.targetContext.getString(R.string.lang_kotlin) - val languageLabelText = device.targetContext.getString(R.string.wizard_language) - - val javaValue = d.findObject(UiSelector().text(javaText)) - if (javaValue.waitForExists(LANGUAGE_OPTION_TIMEOUT_MS)) { - val bounds = javaValue.visibleBounds - d.click(bounds.centerX(), bounds.centerY()) - d.waitForIdle() - if (d.findObject(UiSelector().text(kotlinText)).waitForExists(LANGUAGE_DROPDOWN_EXPANSION_TIMEOUT_MS)) { - return - } - } - - val languageLabel = d.findObject(UiSelector().text(languageLabelText)) - if (languageLabel.waitForExists(LANGUAGE_OPTION_TIMEOUT_MS)) { - val bounds = languageLabel.visibleBounds - d.click(d.displayWidth - LANGUAGE_DROPDOWN_FALLBACK_X_OFFSET, bounds.centerY()) - d.waitForIdle() - if (d.findObject(UiSelector().text(kotlinText)).waitForExists(LANGUAGE_DROPDOWN_EXPANSION_TIMEOUT_MS)) { - return - } - } - - error("Project language dropdown did not open") - } - - fun TestContext.clickCreateProjectProjectSettings() { - step("Click create project on the Settings Page") { - val createText = device.targetContext.getString(R.string.create_project) - clickFirstAccessibilityNodeByText(createText) - device.uiDevice.waitForIdle() - } - } - - fun TestContext.setProjectName(name: String) { - step("Set project name to '$name'") { - val d = device.uiDevice - val byText = d.findObject(UiSelector().textStartsWith("My Application")) - check(byText.waitForExists(PROJECT_NAME_FIELD_TIMEOUT_MS)) { "Project name field not found" } - setAccessibilityEditText("My Application", name, "project name") - d.waitForIdle() - } - } - - fun TestContext.uncheckKotlinScript() { - step("Unselect Kotlin Script for Gradle") { - kotlinScriptText { - setChecked(false) - } - } - } -} diff --git a/app/src/androidTest/kotlin/com/itsaky/androidide/screens/SystemPermissionsScreen.kt b/app/src/androidTest/kotlin/com/itsaky/androidide/screens/SystemPermissionsScreen.kt deleted file mode 100644 index 0a56785a42..0000000000 --- a/app/src/androidTest/kotlin/com/itsaky/androidide/screens/SystemPermissionsScreen.kt +++ /dev/null @@ -1,22 +0,0 @@ -package com.itsaky.androidide.screens - -import com.kaspersky.components.kautomator.component.common.views.UiView -import com.kaspersky.components.kautomator.screen.UiScreen - -object SystemPermissionsScreen : UiScreen() { - override val packageName: String = "com.android.settings" - - val storagePermissionView = UiView { withText("Allow access to manage all files") } - val storagePermissionViewAlt1 = UiView { withText("Files and media") } - val storagePermissionViewAlt2 = UiView { withText("Access all files") } - val storagePermissionViewAlt3 = UiView { withText("Allow") } - val storagePermissionViewAlt4 = UiView { withText("Allow file management") } - val storagePermissionViewAlt5 = UiView { withText("Allow permission") } - val storagePermissionViewAlt6 = UiView { withText("Use USB storage") } - val storagePermissionViewAlt7 = UiView { withText("Storage") } - val storagePermissionViewAlt8 = UiView { withText("Files") } - - val installPackagesPermission = UiView { withText("Allow from this source") } - val installPackagesPermissionAlt1 = UiView { withText("Allow install of apps") } - val installPackagesPermissionAlt2 = UiView { withText("Allow") } -} \ No newline at end of file diff --git a/app/src/androidTest/kotlin/com/itsaky/androidide/screens/TemplateScreen.kt b/app/src/androidTest/kotlin/com/itsaky/androidide/screens/TemplateScreen.kt deleted file mode 100644 index 5cc40b1fbb..0000000000 --- a/app/src/androidTest/kotlin/com/itsaky/androidide/screens/TemplateScreen.kt +++ /dev/null @@ -1,33 +0,0 @@ -package com.itsaky.androidide.screens - -import androidx.test.uiautomator.UiSelector -import androidx.test.uiautomator.UiScrollable -import com.itsaky.androidide.helper.clickFirstAccessibilityNodeParentByText -import com.kaspersky.kaspresso.testcases.core.testcontext.TestContext - -object TemplateScreen { - - fun TestContext.selectTemplate(templateResId: Int, visibleTextOverride: String? = null) { - val templateText = visibleTextOverride ?: device.targetContext.getString(templateResId) - - val d = device.uiDevice - var templateItem = d.findObject( - UiSelector().resourceIdMatches(".*:id/template_name").text(templateText), - ) - if (!templateItem.waitForExists(3_000)) { - runCatching { - UiScrollable(UiSelector().scrollable(true)).scrollTextIntoView(templateText) - } - d.waitForIdle() - templateItem = d.findObject( - UiSelector().resourceIdMatches(".*:id/template_name").text(templateText), - ) - } - - check(templateItem.waitForExists(3_000)) { - "Template '$templateText' not found in template list" - } - clickFirstAccessibilityNodeParentByText(templateText, "template '$templateText'") - d.waitForIdle() - } -} diff --git a/app/src/androidTest/kotlin/com/itsaky/androidide/AutomationEndToEndTest.kt b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/AutomationEndToEndTest.kt similarity index 80% rename from app/src/androidTest/kotlin/com/itsaky/androidide/AutomationEndToEndTest.kt rename to app/src/androidTest/kotlin/org/appdevforall/codeonthego/AutomationEndToEndTest.kt index 8d0ba2fc8a..bc5354541e 100644 --- a/app/src/androidTest/kotlin/com/itsaky/androidide/AutomationEndToEndTest.kt +++ b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/AutomationEndToEndTest.kt @@ -1,27 +1,28 @@ -package com.itsaky.androidide +package org.appdevforall.codeonthego import androidx.test.core.app.ActivityScenario import androidx.test.espresso.matcher.ViewMatchers.isNotEnabled import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry -import com.itsaky.androidide.activities.SplashActivity -import com.itsaky.androidide.helper.advancePastWelcomeScreen -import com.itsaky.androidide.helper.clickFirstAccessibilityNodeByText -import com.itsaky.androidide.helper.configureAutomationBuildPreferences -import com.itsaky.androidide.helper.ensureOnHomeScreenBeforeCreateProject -import com.itsaky.androidide.helper.grantAllRequiredPermissionsThroughOnboardingUi -import com.itsaky.androidide.helper.handlePrivacyDisclosure -import com.itsaky.androidide.helper.initializeProjectRunAssembleTasksAndCancelBuild -import com.itsaky.androidide.helper.selectProjectTemplate -import com.itsaky.androidide.helper.waitForMainHomeOrEditorUi -import com.itsaky.androidide.screens.HomeScreen.clickCreateProjectHomeScreen -import com.itsaky.androidide.screens.OnboardingScreen -import com.itsaky.androidide.screens.PermissionScreen -import com.itsaky.androidide.screens.ProjectSettingsScreen.clickCreateProjectProjectSettings -import com.itsaky.androidide.screens.ProjectSettingsScreen.selectKotlinLanguage -import com.itsaky.androidide.screens.ProjectSettingsScreen.setProjectName -import com.itsaky.androidide.utils.PermissionsHelper +import com.itsaky.androidide.R import com.kaspersky.kaspresso.testcases.api.testcase.TestCase +import org.appdevforall.codeonthego.activities.SplashActivity +import org.appdevforall.codeonthego.helper.advancePastWelcomeScreen +import org.appdevforall.codeonthego.helper.clickFirstAccessibilityNodeByText +import org.appdevforall.codeonthego.helper.configureAutomationBuildPreferences +import org.appdevforall.codeonthego.helper.ensureOnHomeScreenBeforeCreateProject +import org.appdevforall.codeonthego.helper.grantAllRequiredPermissionsThroughOnboardingUi +import org.appdevforall.codeonthego.helper.handlePrivacyDisclosure +import org.appdevforall.codeonthego.helper.initializeProjectRunAssembleTasksAndCancelBuild +import org.appdevforall.codeonthego.helper.selectProjectTemplate +import org.appdevforall.codeonthego.helper.waitForMainHomeOrEditorUi +import org.appdevforall.codeonthego.screens.HomeScreen.clickCreateProjectHomeScreen +import org.appdevforall.codeonthego.screens.OnboardingScreen +import org.appdevforall.codeonthego.screens.PermissionScreen +import org.appdevforall.codeonthego.screens.ProjectSettingsScreen.clickCreateProjectProjectSettings +import org.appdevforall.codeonthego.screens.ProjectSettingsScreen.selectKotlinLanguage +import org.appdevforall.codeonthego.screens.ProjectSettingsScreen.setProjectName +import org.appdevforall.codeonthego.utils.PermissionsHelper import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Test diff --git a/app/src/androidTest/kotlin/org/appdevforall/codeonthego/AutomationTestSuite.kt b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/AutomationTestSuite.kt new file mode 100644 index 0000000000..fe304d4b3f --- /dev/null +++ b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/AutomationTestSuite.kt @@ -0,0 +1,12 @@ +package org.appdevforall.codeonthego + +import org.junit.runner.RunWith +import org.junit.runners.Suite + +@RunWith(Suite::class) +@Suite.SuiteClasses( + CleanupTest::class, + AutomationEndToEndTest::class, + ExportCacheDirectoryTest::class, +) +class AutomationTestSuite diff --git a/app/src/androidTest/kotlin/org/appdevforall/codeonthego/CleanupTest.kt b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/CleanupTest.kt new file mode 100644 index 0000000000..fd5f488657 --- /dev/null +++ b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/CleanupTest.kt @@ -0,0 +1,33 @@ +package org.appdevforall.codeonthego + +import android.app.Instrumentation +import android.os.ParcelFileDescriptor +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import org.junit.AfterClass +import org.junit.Test +import org.junit.runner.RunWith +import java.io.FileInputStream +import java.io.IOException + +@RunWith(AndroidJUnit4::class) +class CleanupTest { + @Test + fun performCleanup() { + try { + val command = "rm -rf /sdcard/CodeOnTheGoProjects" + executeShellCommand(command) + println("Cleanup executed successfully!") + } catch (e: IOException) { + println("Failed to execute cleanup: ${e.message}") + // Don't fail the test - cleanup is best effort + } + } + + private fun executeShellCommand(command: String): String { + val instrumentation: Instrumentation = InstrumentationRegistry.getInstrumentation() + val pfd: ParcelFileDescriptor = instrumentation.uiAutomation.executeShellCommand(command) + val fileInputStream = FileInputStream(pfd.fileDescriptor) + return fileInputStream.bufferedReader().use { it.readText() } + } +} diff --git a/app/src/androidTest/kotlin/com/itsaky/androidide/EndToEndTest.kt b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/EndToEndTest.kt similarity index 77% rename from app/src/androidTest/kotlin/com/itsaky/androidide/EndToEndTest.kt rename to app/src/androidTest/kotlin/org/appdevforall/codeonthego/EndToEndTest.kt index a85d84c5c0..ff0a0ab730 100644 --- a/app/src/androidTest/kotlin/com/itsaky/androidide/EndToEndTest.kt +++ b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/EndToEndTest.kt @@ -1,26 +1,27 @@ -package com.itsaky.androidide +package org.appdevforall.codeonthego import androidx.test.core.app.ActivityScenario import androidx.test.espresso.matcher.ViewMatchers.isNotEnabled import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry -import com.itsaky.androidide.activities.SplashActivity -import com.itsaky.androidide.helper.advancePastWelcomeScreen -import com.itsaky.androidide.helper.clickFirstAccessibilityNodeByText -import com.itsaky.androidide.helper.configureAutomationBuildPreferences -import com.itsaky.androidide.helper.ensureOnHomeScreenBeforeCreateProject -import com.itsaky.androidide.helper.grantAllRequiredPermissionsThroughOnboardingUi -import com.itsaky.androidide.helper.handlePrivacyDisclosure -import com.itsaky.androidide.helper.initializeProjectAndCancelBuild -import com.itsaky.androidide.helper.selectProjectTemplate -import com.itsaky.androidide.helper.waitForMainHomeOrEditorUi -import com.itsaky.androidide.screens.HomeScreen.clickCreateProjectHomeScreen -import com.itsaky.androidide.screens.OnboardingScreen -import com.itsaky.androidide.screens.PermissionScreen -import com.itsaky.androidide.screens.ProjectSettingsScreen.clickCreateProjectProjectSettings -import com.itsaky.androidide.screens.ProjectSettingsScreen.setProjectName -import com.itsaky.androidide.utils.PermissionsHelper +import com.itsaky.androidide.R import com.kaspersky.kaspresso.testcases.api.testcase.TestCase +import org.appdevforall.codeonthego.activities.SplashActivity +import org.appdevforall.codeonthego.helper.advancePastWelcomeScreen +import org.appdevforall.codeonthego.helper.clickFirstAccessibilityNodeByText +import org.appdevforall.codeonthego.helper.configureAutomationBuildPreferences +import org.appdevforall.codeonthego.helper.ensureOnHomeScreenBeforeCreateProject +import org.appdevforall.codeonthego.helper.grantAllRequiredPermissionsThroughOnboardingUi +import org.appdevforall.codeonthego.helper.handlePrivacyDisclosure +import org.appdevforall.codeonthego.helper.initializeProjectAndCancelBuild +import org.appdevforall.codeonthego.helper.selectProjectTemplate +import org.appdevforall.codeonthego.helper.waitForMainHomeOrEditorUi +import org.appdevforall.codeonthego.screens.HomeScreen.clickCreateProjectHomeScreen +import org.appdevforall.codeonthego.screens.OnboardingScreen +import org.appdevforall.codeonthego.screens.PermissionScreen +import org.appdevforall.codeonthego.screens.ProjectSettingsScreen.clickCreateProjectProjectSettings +import org.appdevforall.codeonthego.screens.ProjectSettingsScreen.setProjectName +import org.appdevforall.codeonthego.utils.PermissionsHelper import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Test diff --git a/app/src/androidTest/kotlin/org/appdevforall/codeonthego/ExportCacheDirectoryTest.kt b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/ExportCacheDirectoryTest.kt new file mode 100644 index 0000000000..9bed93ca2a --- /dev/null +++ b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/ExportCacheDirectoryTest.kt @@ -0,0 +1,100 @@ +package org.appdevforall.codeonthego + +import android.os.Environment +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import org.junit.Assert.assertTrue +import org.junit.Assume.assumeTrue +import org.junit.Test +import org.junit.runner.RunWith +import java.io.File + +@RunWith(AndroidJUnit4::class) +class ExportCacheDirectoryTest { + @Test + fun exportGradleModuleCacheBeforeConnectedTestCleanup() { + val context = InstrumentationRegistry.getInstrumentation().targetContext + val args = InstrumentationRegistry.getArguments() + + val destinationRelativePath = + args.getString(ARG_DESTINATION_RELATIVE_PATH) ?: DEFAULT_DESTINATION_RELATIVE_PATH + + val source = File(context.filesDir, SOURCE_RELATIVE_PATH) + val externalBase = File(Environment.getExternalStorageDirectory(), EXPORT_BASE_DIRECTORY).canonicalFile + val destination = resolveSafeDestination(externalBase, destinationRelativePath) + + assumeTrue("Source does not exist: ${source.absolutePath}", source.exists()) + assumeTrue("Source is not a directory: ${source.absolutePath}", source.isDirectory) + + destination.deleteRecursively() + destination.parentFile?.mkdirs() + + assertTrue( + "Failed to copy ${source.absolutePath} to ${destination.absolutePath}", + source.copyRecursively(target = destination, overwrite = true), + ) + assertTrue("Destination does not exist: ${destination.absolutePath}", destination.exists()) + } + + @Test + fun exportGeneratedGradleApiJarWhenRequested() { + val context = InstrumentationRegistry.getInstrumentation().targetContext + val args = InstrumentationRegistry.getArguments() + val version = args.getString(ARG_GRADLE_API_VERSION) + + assumeTrue("No Gradle API version requested", !version.isNullOrBlank()) + require(!version!!.contains(File.separatorChar)) { + "Gradle API version must not contain path separators: $version" + } + + val destinationRelativePath = + args.getString(ARG_GRADLE_API_DESTINATION_RELATIVE_PATH) + ?: DEFAULT_GRADLE_API_DESTINATION_RELATIVE_PATH + + val source = + File( + context.filesDir, + "$GRADLE_CACHE_RELATIVE_PATH/$version/generated-gradle-jars/gradle-api-$version.jar", + ) + val externalBase = File(Environment.getExternalStorageDirectory(), EXPORT_BASE_DIRECTORY).canonicalFile + val destinationDir = resolveSafeDestination(externalBase, destinationRelativePath) + val destination = File(destinationDir, source.name) + + assertTrue("Source does not exist: ${source.absolutePath}", source.exists()) + assertTrue("Source is not a file: ${source.absolutePath}", source.isFile) + + destination.parentFile?.mkdirs() + source.copyTo(target = destination, overwrite = true) + + assertTrue("Destination does not exist: ${destination.absolutePath}", destination.exists()) + } + + private fun resolveSafeDestination( + base: File, + relativePath: String, + ): File { + require(relativePath.isNotBlank()) { + "Destination path must be a non-blank relative path" + } + require(!File(relativePath).isAbsolute) { + "Destination path must be relative" + } + + val destination = File(base, relativePath.removePrefix("$EXPORT_BASE_DIRECTORY/")).canonicalFile + require(destination.toPath().startsWith(base.toPath())) { + "Destination must stay under ${base.absolutePath}: ${destination.absolutePath}" + } + return destination + } + + private companion object { + const val SOURCE_RELATIVE_PATH = "home/.gradle/caches/modules-2/files-2.1" + const val GRADLE_CACHE_RELATIVE_PATH = "home/.gradle/caches" + const val ARG_DESTINATION_RELATIVE_PATH = "androidide.exportCache.destination" + const val ARG_GRADLE_API_VERSION = "androidide.exportGradleApi.version" + const val ARG_GRADLE_API_DESTINATION_RELATIVE_PATH = "androidide.exportGradleApi.destination" + const val EXPORT_BASE_DIRECTORY = "CodeOnTheGoProjects" + const val DEFAULT_DESTINATION_RELATIVE_PATH = "CodeOnTheGoProjects/gradle-cache/modules-2/files-2.1" + const val DEFAULT_GRADLE_API_DESTINATION_RELATIVE_PATH = "CodeOnTheGoProjects/gradle-api" + } +} diff --git a/app/src/androidTest/kotlin/com/itsaky/androidide/OrderedTestSuite.kt b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/OrderedTestSuite.kt similarity index 87% rename from app/src/androidTest/kotlin/com/itsaky/androidide/OrderedTestSuite.kt rename to app/src/androidTest/kotlin/org/appdevforall/codeonthego/OrderedTestSuite.kt index 1d4f99ac8d..ea3860e7f9 100644 --- a/app/src/androidTest/kotlin/com/itsaky/androidide/OrderedTestSuite.kt +++ b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/OrderedTestSuite.kt @@ -1,4 +1,4 @@ -package com.itsaky.androidide +package org.appdevforall.codeonthego import org.junit.runner.RunWith import org.junit.runners.Suite diff --git a/app/src/androidTest/kotlin/org/appdevforall/codeonthego/ProjectBuildTestWithGroovyGradle.kt b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/ProjectBuildTestWithGroovyGradle.kt new file mode 100644 index 0000000000..801aa8e753 --- /dev/null +++ b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/ProjectBuildTestWithGroovyGradle.kt @@ -0,0 +1,208 @@ +package org.appdevforall.codeonthego + +import androidx.test.platform.app.InstrumentationRegistry +import com.itsaky.androidide.R +import com.kaspersky.kaspresso.testcases.api.testcase.TestCase +import org.appdevforall.codeonthego.helper.initializeProjectAndCancelBuild +import org.appdevforall.codeonthego.helper.navigateToMainScreen +import org.appdevforall.codeonthego.helper.selectProjectTemplate +import org.appdevforall.codeonthego.screens.HomeScreen.clickCreateProjectHomeScreen +import org.appdevforall.codeonthego.screens.ProjectSettingsScreen.clickCreateProjectProjectSettings +import org.appdevforall.codeonthego.screens.ProjectSettingsScreen.selectJavaLanguage +import org.appdevforall.codeonthego.screens.ProjectSettingsScreen.selectKotlinLanguage +import org.appdevforall.codeonthego.screens.ProjectSettingsScreen.uncheckKotlinScript +import org.junit.Test + +class ProjectBuildTestWithGroovyGradle : TestCase() { + @Test + fun test_projectBuild_emptyProject_java_groovyGradle() { + run { + navigateToMainScreen() + clickCreateProjectHomeScreen() + selectProjectTemplate( + "Select the empty project", + R.string.template_empty, + ) + selectJavaLanguage() + uncheckKotlinScript() + clickCreateProjectProjectSettings() + initializeProjectAndCancelBuild() + } + } + + @Test + fun test_projectBuild_emptyProject_kotlin_groovyGradle() { + run { + navigateToMainScreen() + clickCreateProjectHomeScreen() + selectProjectTemplate( + "Select the empty project", + R.string.template_empty, + ) + selectKotlinLanguage() + uncheckKotlinScript() + clickCreateProjectProjectSettings() + initializeProjectAndCancelBuild() + } + } + + @Test + fun test_projectBuild_baseProject_java_groovyGradle() { + run { + navigateToMainScreen() + clickCreateProjectHomeScreen() + selectProjectTemplate( + "Select the basic project", + R.string.template_basic, + ) + selectJavaLanguage() + uncheckKotlinScript() + clickCreateProjectProjectSettings() + initializeProjectAndCancelBuild() + } + } + + @Test + fun test_projectBuild_baseProject_kotlin_groovyGradle() { + run { + navigateToMainScreen() + clickCreateProjectHomeScreen() + selectProjectTemplate( + "Select the basic project", + R.string.template_basic, + ) + selectKotlinLanguage() + uncheckKotlinScript() + clickCreateProjectProjectSettings() + initializeProjectAndCancelBuild() + } + } + + @Test + fun test_projectBuild_navigationDrawerProject_java_groovyGradle() { + run { + navigateToMainScreen() + clickCreateProjectHomeScreen() + selectProjectTemplate( + "Select the navigation drawer project", + R.string.template_navigation_drawer, + ) + selectJavaLanguage() + uncheckKotlinScript() + clickCreateProjectProjectSettings() + initializeProjectAndCancelBuild() + } + } + + @Test + fun test_projectBuild_navigationDrawerProject_kotlin_groovyGradle() { + run { + navigateToMainScreen() + clickCreateProjectHomeScreen() + selectProjectTemplate( + "Select the navigation drawer project", + R.string.template_navigation_drawer, + ) + selectKotlinLanguage() + uncheckKotlinScript() + clickCreateProjectProjectSettings() + initializeProjectAndCancelBuild() + } + } + + @Test + fun test_projectBuild_bottomNavigationProject_java_groovyGradle() { + run { + navigateToMainScreen() + clickCreateProjectHomeScreen() + selectProjectTemplate( + "Select the bottom navigation project", + R.string.template_navigation_tabs, + ) + selectJavaLanguage() + uncheckKotlinScript() + clickCreateProjectProjectSettings() + initializeProjectAndCancelBuild() + } + } + + @Test + fun test_projectBuild_bottomNavigationProject_kotlin_groovyGradle() { + run { + navigateToMainScreen() + clickCreateProjectHomeScreen() + selectProjectTemplate( + "Select the bottom navigation project", + R.string.template_navigation_tabs, + ) + selectKotlinLanguage() + uncheckKotlinScript() + clickCreateProjectProjectSettings() + initializeProjectAndCancelBuild() + } + } + + @Test + fun test_projectBuild_tabbedActivityProject_java_groovyGradle() { + run { + navigateToMainScreen() + clickCreateProjectHomeScreen() + selectProjectTemplate( + "Select the tabbed activity project", + R.string.template_tabs, + ) + selectJavaLanguage() + uncheckKotlinScript() + clickCreateProjectProjectSettings() + initializeProjectAndCancelBuild() + } + } + + @Test + fun test_projectBuild_tabbedActivityProject_kotlin_groovyGradle() { + run { + navigateToMainScreen() + clickCreateProjectHomeScreen() + selectProjectTemplate( + "Select the tabbed activity project", + R.string.template_tabs, + ) + selectKotlinLanguage() + uncheckKotlinScript() + clickCreateProjectProjectSettings() + initializeProjectAndCancelBuild() + } + } + + @Test + fun test_projectBuild_noAndroidXProject_java_groovyGradle() { + run { + navigateToMainScreen() + clickCreateProjectHomeScreen() + selectProjectTemplate( + "Select the no AndroidX project", + R.string.template_no_AndroidX, + ) + selectJavaLanguage() + uncheckKotlinScript() + clickCreateProjectProjectSettings() + initializeProjectAndCancelBuild() + } + } + + @Test + fun test_projectBuild_noAndroidXProject_kotlin_groovyGradle() { + run { + navigateToMainScreen() + clickCreateProjectHomeScreen() + selectProjectTemplate( + "Select the no AndroidX project", + R.string.template_no_AndroidX, + ) + selectKotlinLanguage() + uncheckKotlinScript() + clickCreateProjectProjectSettings() + initializeProjectAndCancelBuild() + } + } +} diff --git a/app/src/androidTest/kotlin/org/appdevforall/codeonthego/ProjectBuildTestWithKtsGradle.kt b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/ProjectBuildTestWithKtsGradle.kt new file mode 100644 index 0000000000..0687536281 --- /dev/null +++ b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/ProjectBuildTestWithKtsGradle.kt @@ -0,0 +1,240 @@ +package org.appdevforall.codeonthego + +import androidx.test.platform.app.InstrumentationRegistry +import com.itsaky.androidide.R +import com.kaspersky.kaspresso.testcases.api.testcase.TestCase +import org.appdevforall.codeonthego.helper.initializeProjectAndCancelBuild +import org.appdevforall.codeonthego.helper.navigateToMainScreen +import org.appdevforall.codeonthego.helper.selectProjectTemplate +import org.appdevforall.codeonthego.screens.HomeScreen.clickCreateProjectHomeScreen +import org.appdevforall.codeonthego.screens.ProjectSettingsScreen.clickCreateProjectProjectSettings +import org.appdevforall.codeonthego.screens.ProjectSettingsScreen.selectJavaLanguage +import org.appdevforall.codeonthego.screens.ProjectSettingsScreen.selectKotlinLanguage +import org.junit.Test + +class ProjectBuildTestWithKtsGradle : TestCase() { + @Test + fun test_projectBuild_emptyProject_java() { + run { + navigateToMainScreen() + clickCreateProjectHomeScreen() + selectProjectTemplate( + "Select the empty project", + R.string.template_empty, + ) + selectJavaLanguage() + clickCreateProjectProjectSettings() + initializeProjectAndCancelBuild() + } + } + + @Test + fun test_projectBuild_emptyProject_kotlin() { + run { + navigateToMainScreen() + clickCreateProjectHomeScreen() + selectProjectTemplate( + "Select the empty project", + R.string.template_empty, + ) + selectKotlinLanguage() + clickCreateProjectProjectSettings() + initializeProjectAndCancelBuild() + } + } + + @Test + fun test_projectBuild_baseProject_java() { + run { + navigateToMainScreen() + clickCreateProjectHomeScreen() + selectProjectTemplate( + "Select the basic project", + R.string.template_basic, + ) + selectJavaLanguage() + clickCreateProjectProjectSettings() + initializeProjectAndCancelBuild() + } + } + + @Test + fun test_projectBuild_baseProject_kotlin() { + run { + step("Navigate to main screen") { + // Ensure consistent start state with increased timeout + flakySafely(timeoutMs = 30000) { + navigateToMainScreen() + } + } + + step("Click create project on home screen") { + flakySafely(timeoutMs = 10000) { + clickCreateProjectHomeScreen() + } + } + + step("Select the basic project template") { + flakySafely(timeoutMs = 10000) { + selectProjectTemplate( + "Select the basic project", + R.string.template_basic, + ) + } + } + + step("Select Kotlin language") { + flakySafely(timeoutMs = 10000) { + selectKotlinLanguage() + } + } + + step("Click create project on settings screen") { + flakySafely(timeoutMs = 10000) { + clickCreateProjectProjectSettings() + } + } + + step("Initialize project and cancel build") { + flakySafely(timeoutMs = 10000) { + initializeProjectAndCancelBuild() + } + } + } + } + + @Test + fun test_projectBuild_navigationDrawerProject_java() { + run { + navigateToMainScreen() + clickCreateProjectHomeScreen() + selectProjectTemplate( + "Select the navigation drawer project", + R.string.template_navigation_drawer, + ) + selectJavaLanguage() + clickCreateProjectProjectSettings() + initializeProjectAndCancelBuild() + } + } + + @Test + fun test_projectBuild_navigationDrawerProject_kotlin() { + run { + navigateToMainScreen() + clickCreateProjectHomeScreen() + selectProjectTemplate( + "Select the navigation drawer project", + R.string.template_navigation_drawer, + ) + selectKotlinLanguage() + clickCreateProjectProjectSettings() + initializeProjectAndCancelBuild() + } + } + + @Test + fun test_projectBuild_bottomNavigationProject_java() { + run { + navigateToMainScreen() + clickCreateProjectHomeScreen() + selectProjectTemplate( + "Select the bottom navigation project", + R.string.template_navigation_tabs, + ) + selectJavaLanguage() + clickCreateProjectProjectSettings() + initializeProjectAndCancelBuild() + } + } + + @Test + fun test_projectBuild_bottomNavigationProject_kotlin() { + run { + navigateToMainScreen() + clickCreateProjectHomeScreen() + selectProjectTemplate( + "Select the bottom navigation project", + R.string.template_navigation_tabs, + ) + selectKotlinLanguage() + clickCreateProjectProjectSettings() + initializeProjectAndCancelBuild() + } + } + + @Test + fun test_projectBuild_tabbedActivityProject_java() { + run { + navigateToMainScreen() + clickCreateProjectHomeScreen() + selectProjectTemplate( + "Select the tabbed activity project", + R.string.template_tabs, + ) + selectJavaLanguage() + clickCreateProjectProjectSettings() + initializeProjectAndCancelBuild() + } + } + + @Test + fun test_projectBuild_tabbedActivityProject_kotlin() { + run { + navigateToMainScreen() + clickCreateProjectHomeScreen() + selectProjectTemplate( + "Select the tabbed activity project", + R.string.template_tabs, + ) + selectKotlinLanguage() + clickCreateProjectProjectSettings() + initializeProjectAndCancelBuild() + } + } + + @Test + fun test_projectBuild_noAnd2roidXProject_java() { + run { + navigateToMainScreen() + clickCreateProjectHomeScreen() + selectProjectTemplate( + "Select the no AndroidX project", + R.string.template_no_AndroidX, + ) + selectJavaLanguage() + clickCreateProjectProjectSettings() + initializeProjectAndCancelBuild() + } + } + + @Test + fun test_projectBuild_noAndroidXProject_kotlin() { + run { + navigateToMainScreen() + clickCreateProjectHomeScreen() + selectProjectTemplate( + "Select the no AndroidX project", + R.string.template_no_AndroidX, + ) + selectKotlinLanguage() + clickCreateProjectProjectSettings() + initializeProjectAndCancelBuild() + } + } + +// TODO: to be uncommented out when the compose project template is fixed +// @Test +// fun test_projectBuild_composeProject() { +// run { +// navigateToMainScreen() +// clickCreateProjectHomeScreen() +// selectProjectTemplate( +// "Select the no Compose project", +// R.string.template_compose +// ) +// clickCreateProjectProjectSettings() +// initializeProjectAndCancelBuild() +// } +// } +} diff --git a/app/src/androidTest/kotlin/com/itsaky/androidide/QuickBuildFlagOffTest.kt b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/QuickBuildFlagOffTest.kt similarity index 79% rename from app/src/androidTest/kotlin/com/itsaky/androidide/QuickBuildFlagOffTest.kt rename to app/src/androidTest/kotlin/org/appdevforall/codeonthego/QuickBuildFlagOffTest.kt index 95a60ff21f..0bcce17884 100644 --- a/app/src/androidTest/kotlin/com/itsaky/androidide/QuickBuildFlagOffTest.kt +++ b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/QuickBuildFlagOffTest.kt @@ -1,18 +1,18 @@ -package com.itsaky.androidide +package org.appdevforall.codeonthego import androidx.test.core.app.ActivityScenario import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry -import com.itsaky.androidide.activities.SplashActivity -import com.itsaky.androidide.activities.editor.EditorHandlerActivity -import com.itsaky.androidide.app.configuration.IJdkDistributionProvider -import com.itsaky.androidide.helper.isExperimentsFlagSet -import com.itsaky.androidide.helper.setExperimentsFlagForTest -import com.itsaky.androidide.helper.waitForMainHomeOrEditorUi -import com.itsaky.androidide.screens.QuickBuildScreen.assertQuickBuildButtonAbsent -import com.itsaky.androidide.screens.QuickBuildScreen.assertQuickBuildButtonShown -import com.itsaky.androidide.utils.EditorActivityActions import com.kaspersky.kaspresso.testcases.api.testcase.TestCase +import org.appdevforall.codeonthego.activities.SplashActivity +import org.appdevforall.codeonthego.activities.editor.EditorHandlerActivity +import org.appdevforall.codeonthego.app.configuration.IJdkDistributionProvider +import org.appdevforall.codeonthego.helper.isExperimentsFlagSet +import org.appdevforall.codeonthego.helper.setExperimentsFlagForTest +import org.appdevforall.codeonthego.helper.waitForMainHomeOrEditorUi +import org.appdevforall.codeonthego.screens.QuickBuildScreen.assertQuickBuildButtonAbsent +import org.appdevforall.codeonthego.screens.QuickBuildScreen.assertQuickBuildButtonShown +import org.appdevforall.codeonthego.utils.EditorActivityActions import org.junit.Test import org.junit.runner.RunWith @@ -22,7 +22,7 @@ private const val TOOLBAR_TIMEOUT_MS = 15_000L * The shipping-state gate for Quick Build (ADFA-4128, manual test T13): with no * `CodeOnTheGo.exp` flag file on the device, the feature must be invisible. * - * The gate is a single read of [com.itsaky.androidide.utils.FeatureFlags.isExperimentsEnabled] + * The gate is a single read of [org.appdevforall.codeonthego.utils.FeatureFlags.isExperimentsEnabled] * at [EditorActivityActions.register], so this drives that decision directly instead of * restarting the process: flip the flag, re-register, rebuild the toolbar, look. That also * makes the test honest about what it covers - the registration site, not the process-start diff --git a/app/src/androidTest/kotlin/com/itsaky/androidide/QuickBuildPipelineTest.kt b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/QuickBuildPipelineTest.kt similarity index 94% rename from app/src/androidTest/kotlin/com/itsaky/androidide/QuickBuildPipelineTest.kt rename to app/src/androidTest/kotlin/org/appdevforall/codeonthego/QuickBuildPipelineTest.kt index 91b727f54b..10e56bdd6f 100644 --- a/app/src/androidTest/kotlin/com/itsaky/androidide/QuickBuildPipelineTest.kt +++ b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/QuickBuildPipelineTest.kt @@ -1,28 +1,11 @@ -package com.itsaky.androidide +package org.appdevforall.codeonthego import android.os.Build import androidx.test.core.app.ActivityScenario import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import androidx.test.uiautomator.UiSelector -import com.itsaky.androidide.activities.SplashActivity -import com.itsaky.androidide.app.configuration.IJdkDistributionProvider -import com.itsaky.androidide.helper.FakeInstalledPackages -import com.itsaky.androidide.helper.ensureOnHomeScreenBeforeCreateProject -import com.itsaky.androidide.helper.isExperimentsFlagSet -import com.itsaky.androidide.helper.selectProjectTemplate -import com.itsaky.androidide.helper.setAccessibilityEditText -import com.itsaky.androidide.helper.setExperimentsFlagForTest -import com.itsaky.androidide.helper.waitForMainHomeOrEditorUi -import com.itsaky.androidide.projects.IProjectManager -import com.itsaky.androidide.quickbuild.AndroidInstalledPackages -import com.itsaky.androidide.screens.HomeScreen.clickCreateProjectHomeScreen -import com.itsaky.androidide.screens.ProjectSettingsScreen.clickCreateProjectProjectSettings -import com.itsaky.androidide.screens.ProjectSettingsScreen.selectKotlinLanguage -import com.itsaky.androidide.screens.ProjectSettingsScreen.setProjectName -import com.itsaky.androidide.screens.QuickBuildScreen.assertQuickBuildButtonShown -import com.itsaky.androidide.screens.QuickBuildScreen.dismissFirstBuildNoticeIfShown -import com.itsaky.androidide.screens.QuickBuildScreen.tapQuickBuildButton +import com.itsaky.androidide.R import com.kaspersky.kaspresso.testcases.api.testcase.TestCase import com.kaspersky.kaspresso.testcases.core.testcontext.TestContext import kotlinx.coroutines.CoroutineScope @@ -31,6 +14,24 @@ import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withTimeoutOrNull +import org.appdevforall.codeonthego.activities.SplashActivity +import org.appdevforall.codeonthego.app.configuration.IJdkDistributionProvider +import org.appdevforall.codeonthego.helper.FakeInstalledPackages +import org.appdevforall.codeonthego.helper.ensureOnHomeScreenBeforeCreateProject +import org.appdevforall.codeonthego.helper.isExperimentsFlagSet +import org.appdevforall.codeonthego.helper.selectProjectTemplate +import org.appdevforall.codeonthego.helper.setAccessibilityEditText +import org.appdevforall.codeonthego.helper.setExperimentsFlagForTest +import org.appdevforall.codeonthego.helper.waitForMainHomeOrEditorUi +import org.appdevforall.codeonthego.projects.IProjectManager +import org.appdevforall.codeonthego.quickbuild.AndroidInstalledPackages +import org.appdevforall.codeonthego.screens.HomeScreen.clickCreateProjectHomeScreen +import org.appdevforall.codeonthego.screens.ProjectSettingsScreen.clickCreateProjectProjectSettings +import org.appdevforall.codeonthego.screens.ProjectSettingsScreen.selectKotlinLanguage +import org.appdevforall.codeonthego.screens.ProjectSettingsScreen.setProjectName +import org.appdevforall.codeonthego.screens.QuickBuildScreen.assertQuickBuildButtonShown +import org.appdevforall.codeonthego.screens.QuickBuildScreen.dismissFirstBuildNoticeIfShown +import org.appdevforall.codeonthego.screens.QuickBuildScreen.tapQuickBuildButton import org.appdevforall.cotg.quickbuild.domain.session.QuickBuildSessionState import org.appdevforall.cotg.quickbuild.domain.session.SessionFailure import org.appdevforall.cotg.quickbuild.service.deploy.ProxyAppConnections diff --git a/app/src/androidTest/kotlin/com/itsaky/androidide/QuickBuildSmokeTest.kt b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/QuickBuildSmokeTest.kt similarity index 81% rename from app/src/androidTest/kotlin/com/itsaky/androidide/QuickBuildSmokeTest.kt rename to app/src/androidTest/kotlin/org/appdevforall/codeonthego/QuickBuildSmokeTest.kt index 665a6e74fd..686c6de613 100644 --- a/app/src/androidTest/kotlin/com/itsaky/androidide/QuickBuildSmokeTest.kt +++ b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/QuickBuildSmokeTest.kt @@ -1,44 +1,45 @@ -package com.itsaky.androidide +package org.appdevforall.codeonthego import androidx.test.core.app.ActivityScenario import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import androidx.test.uiautomator.UiSelector -import com.itsaky.androidide.activities.SplashActivity -import com.itsaky.androidide.activities.editor.EditorHandlerActivity -import com.itsaky.androidide.app.configuration.IJdkDistributionProvider -import com.itsaky.androidide.helper.FakeInstalledPackages -import com.itsaky.androidide.helper.ensureOnHomeScreenBeforeCreateProject -import com.itsaky.androidide.helper.isExperimentsFlagSet -import com.itsaky.androidide.helper.selectProjectTemplate -import com.itsaky.androidide.helper.setAccessibilityEditText -import com.itsaky.androidide.helper.setExperimentsFlagForTest -import com.itsaky.androidide.helper.waitForMainHomeOrEditorUi -import com.itsaky.androidide.projects.IProjectManager -import com.itsaky.androidide.quickbuild.AndroidInstalledPackages -import com.itsaky.androidide.screens.ErrorBannerScreen.assertErrorBannerShown -import com.itsaky.androidide.screens.ErrorBannerScreen.dismissErrorBannerViaButton -import com.itsaky.androidide.screens.ErrorBannerScreen.dismissErrorBannerViaSwipe -import com.itsaky.androidide.screens.ErrorBannerScreen.dismissErrorBannerViaTapOnBar -import com.itsaky.androidide.screens.HomeScreen.clickCreateProjectHomeScreen -import com.itsaky.androidide.screens.ProjectSettingsScreen.clickCreateProjectProjectSettings -import com.itsaky.androidide.screens.ProjectSettingsScreen.setProjectName -import com.itsaky.androidide.screens.QuickBuildScreen.acceptClobberConfirm -import com.itsaky.androidide.screens.QuickBuildScreen.assertClobberConfirmShown -import com.itsaky.androidide.screens.QuickBuildScreen.assertQuickBuildButtonShown -import com.itsaky.androidide.screens.QuickBuildScreen.assertQuickBuildButtonShowsStop -import com.itsaky.androidide.screens.QuickBuildScreen.declineClobberConfirm -import com.itsaky.androidide.screens.QuickBuildScreen.dismissFirstBuildNoticeIfShown -import com.itsaky.androidide.screens.QuickBuildScreen.dismissQuickBuildDropdown -import com.itsaky.androidide.screens.QuickBuildScreen.longPressOpensQuickBuildDropdown -import com.itsaky.androidide.screens.QuickBuildScreen.restartSessionViaDropdown -import com.itsaky.androidide.screens.QuickBuildScreen.tapQuickBuildButton -import com.itsaky.androidide.utils.flashError +import com.itsaky.androidide.R import com.kaspersky.kaspresso.testcases.api.testcase.TestCase import kotlinx.coroutines.flow.first import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withTimeout import kotlinx.coroutines.withTimeoutOrNull +import org.appdevforall.codeonthego.activities.SplashActivity +import org.appdevforall.codeonthego.activities.editor.EditorHandlerActivity +import org.appdevforall.codeonthego.app.configuration.IJdkDistributionProvider +import org.appdevforall.codeonthego.helper.FakeInstalledPackages +import org.appdevforall.codeonthego.helper.ensureOnHomeScreenBeforeCreateProject +import org.appdevforall.codeonthego.helper.isExperimentsFlagSet +import org.appdevforall.codeonthego.helper.selectProjectTemplate +import org.appdevforall.codeonthego.helper.setAccessibilityEditText +import org.appdevforall.codeonthego.helper.setExperimentsFlagForTest +import org.appdevforall.codeonthego.helper.waitForMainHomeOrEditorUi +import org.appdevforall.codeonthego.projects.IProjectManager +import org.appdevforall.codeonthego.quickbuild.AndroidInstalledPackages +import org.appdevforall.codeonthego.screens.ErrorBannerScreen.assertErrorBannerShown +import org.appdevforall.codeonthego.screens.ErrorBannerScreen.dismissErrorBannerViaButton +import org.appdevforall.codeonthego.screens.ErrorBannerScreen.dismissErrorBannerViaSwipe +import org.appdevforall.codeonthego.screens.ErrorBannerScreen.dismissErrorBannerViaTapOnBar +import org.appdevforall.codeonthego.screens.HomeScreen.clickCreateProjectHomeScreen +import org.appdevforall.codeonthego.screens.ProjectSettingsScreen.clickCreateProjectProjectSettings +import org.appdevforall.codeonthego.screens.ProjectSettingsScreen.setProjectName +import org.appdevforall.codeonthego.screens.QuickBuildScreen.acceptClobberConfirm +import org.appdevforall.codeonthego.screens.QuickBuildScreen.assertClobberConfirmShown +import org.appdevforall.codeonthego.screens.QuickBuildScreen.assertQuickBuildButtonShown +import org.appdevforall.codeonthego.screens.QuickBuildScreen.assertQuickBuildButtonShowsStop +import org.appdevforall.codeonthego.screens.QuickBuildScreen.declineClobberConfirm +import org.appdevforall.codeonthego.screens.QuickBuildScreen.dismissFirstBuildNoticeIfShown +import org.appdevforall.codeonthego.screens.QuickBuildScreen.dismissQuickBuildDropdown +import org.appdevforall.codeonthego.screens.QuickBuildScreen.longPressOpensQuickBuildDropdown +import org.appdevforall.codeonthego.screens.QuickBuildScreen.restartSessionViaDropdown +import org.appdevforall.codeonthego.screens.QuickBuildScreen.tapQuickBuildButton +import org.appdevforall.codeonthego.utils.flashError import org.appdevforall.cotg.quickbuild.domain.session.QuickBuildStatus import org.appdevforall.cotg.quickbuild.service.provision.InstalledPackages import org.appdevforall.cotg.quickbuild.service.provision.QuickBuildClobberCheck @@ -73,7 +74,7 @@ private const val BANNER_MESSAGE = "Quick Build smoke: injected error banner" /** * Kaspresso smoke for the Quick Build surfaces added by ADFA-4128: - * - the lightning-bolt toolbar action (via [com.itsaky.androidide.screens.QuickBuildScreen]) + * - the lightning-bolt toolbar action (via [org.appdevforall.codeonthego.screens.QuickBuildScreen]) * and its long-press split-button dropdown; * - the indefinite error banner (the surface `userMessages` renders through `flashError`) * and its three dismiss paths: Dismiss button, tap-anywhere, swipe; diff --git a/app/src/androidTest/kotlin/com/itsaky/androidide/app/strictmode/FrameMatcherTest.kt b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/app/strictmode/FrameMatcherTest.kt similarity index 98% rename from app/src/androidTest/kotlin/com/itsaky/androidide/app/strictmode/FrameMatcherTest.kt rename to app/src/androidTest/kotlin/org/appdevforall/codeonthego/app/strictmode/FrameMatcherTest.kt index afc93c99df..eb7d174e17 100644 --- a/app/src/androidTest/kotlin/com/itsaky/androidide/app/strictmode/FrameMatcherTest.kt +++ b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/app/strictmode/FrameMatcherTest.kt @@ -1,4 +1,4 @@ -package com.itsaky.androidide.app.strictmode +package org.appdevforall.codeonthego.app.strictmode import com.google.common.truth.Truth.assertThat import org.junit.Test diff --git a/app/src/androidTest/kotlin/com/itsaky/androidide/app/strictmode/StackMatcherTest.kt b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/app/strictmode/StackMatcherTest.kt similarity index 98% rename from app/src/androidTest/kotlin/com/itsaky/androidide/app/strictmode/StackMatcherTest.kt rename to app/src/androidTest/kotlin/org/appdevforall/codeonthego/app/strictmode/StackMatcherTest.kt index 7a445d9c80..614738a65c 100644 --- a/app/src/androidTest/kotlin/com/itsaky/androidide/app/strictmode/StackMatcherTest.kt +++ b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/app/strictmode/StackMatcherTest.kt @@ -1,4 +1,4 @@ -package com.itsaky.androidide.app.strictmode +package org.appdevforall.codeonthego.app.strictmode import com.google.common.truth.Truth.assertThat import org.junit.Test diff --git a/app/src/androidTest/kotlin/com/itsaky/androidide/app/strictmode/Utils.kt b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/app/strictmode/Utils.kt similarity index 95% rename from app/src/androidTest/kotlin/com/itsaky/androidide/app/strictmode/Utils.kt rename to app/src/androidTest/kotlin/org/appdevforall/codeonthego/app/strictmode/Utils.kt index a4dd496d9f..00c119aa6a 100644 --- a/app/src/androidTest/kotlin/com/itsaky/androidide/app/strictmode/Utils.kt +++ b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/app/strictmode/Utils.kt @@ -1,4 +1,4 @@ -package com.itsaky.androidide.app.strictmode +package org.appdevforall.codeonthego.app.strictmode import android.os.strictmode.Violation import com.google.common.truth.Truth.assertThat diff --git a/app/src/androidTest/kotlin/com/itsaky/androidide/app/strictmode/WhitelistEngineTest.kt b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/app/strictmode/WhitelistEngineTest.kt similarity index 98% rename from app/src/androidTest/kotlin/com/itsaky/androidide/app/strictmode/WhitelistEngineTest.kt rename to app/src/androidTest/kotlin/org/appdevforall/codeonthego/app/strictmode/WhitelistEngineTest.kt index c86b7abaf1..168cd6de82 100644 --- a/app/src/androidTest/kotlin/com/itsaky/androidide/app/strictmode/WhitelistEngineTest.kt +++ b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/app/strictmode/WhitelistEngineTest.kt @@ -1,4 +1,4 @@ -package com.itsaky.androidide.app.strictmode +package org.appdevforall.codeonthego.app.strictmode import android.os.strictmode.CustomViolation import android.os.strictmode.DiskReadViolation diff --git a/app/src/androidTest/kotlin/com/itsaky/androidide/app/strictmode/WhitelistRulesTest.kt b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/app/strictmode/WhitelistRulesTest.kt similarity index 96% rename from app/src/androidTest/kotlin/com/itsaky/androidide/app/strictmode/WhitelistRulesTest.kt rename to app/src/androidTest/kotlin/org/appdevforall/codeonthego/app/strictmode/WhitelistRulesTest.kt index c061a2fbc5..6c5fce3d23 100644 --- a/app/src/androidTest/kotlin/com/itsaky/androidide/app/strictmode/WhitelistRulesTest.kt +++ b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/app/strictmode/WhitelistRulesTest.kt @@ -1,4 +1,4 @@ -package com.itsaky.androidide.app.strictmode +package org.appdevforall.codeonthego.app.strictmode import android.os.strictmode.DiskReadViolation import android.os.strictmode.DiskWriteViolation @@ -73,7 +73,7 @@ class WhitelistRulesTest { stackTraceElement("com.google.firebase.components.Lazy", "get", "Lazy.java", 53), stackTraceElement("com.google.firebase.FirebaseApp", "isDataCollectionDefaultEnabled", "FirebaseApp.java", 371), stackTraceElement("com.google.firebase.analytics.connector.AnalyticsConnectorImpl", "getInstance", "play-services-measurement-api@@22.1.2", 31), - stackTraceElement("com.google.firebase.FirebaseApp\$UserUnlockReceiver", "onReceive", "FirebaseApp.java", 672) + stackTraceElement("com.google.firebase.FirebaseApp\$UserUnlockReceiver", "onReceive", "FirebaseApp.java", 672), // @formatter:on ) } @@ -81,10 +81,10 @@ class WhitelistRulesTest { @Test fun allow_DiskRead_on_ServiceLoader_JdkDistributionProvider() { assertAllowed( - stackTraceElement("com.itsaky.androidide.utils.ServiceLoader", "parse"), + stackTraceElement("org.appdevforall.codeonthego.utils.ServiceLoader", "parse"), stackTraceElement( - "com.itsaky.androidide.app.configuration.IJdkDistributionProvider\$Companion", - "_instance_delegate\$lambda\$0" + "org.appdevforall.codeonthego.app.configuration.IJdkDistributionProvider\$Companion", + "_instance_delegate\$lambda\$0", ), ) } @@ -94,8 +94,8 @@ class WhitelistRulesTest { assertAllowed( stackTraceElement("java.io.File", "exists"), stackTraceElement( - "com.itsaky.androidide.activities.OnboardingActivity", - "checkToolsIsInstalled" + "org.appdevforall.codeonthego.activities.OnboardingActivity", + "checkToolsIsInstalled", ), ) } diff --git a/app/src/androidTest/kotlin/com/itsaky/androidide/editor/ui/IDEEditorTest.kt b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/editor/ui/IDEEditorTest.kt similarity index 97% rename from app/src/androidTest/kotlin/com/itsaky/androidide/editor/ui/IDEEditorTest.kt rename to app/src/androidTest/kotlin/org/appdevforall/codeonthego/editor/ui/IDEEditorTest.kt index a9a87c2877..a9f6b8cdb8 100644 --- a/app/src/androidTest/kotlin/com/itsaky/androidide/editor/ui/IDEEditorTest.kt +++ b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/editor/ui/IDEEditorTest.kt @@ -1,4 +1,4 @@ -package com.itsaky.androidide.editor.ui +package org.appdevforall.codeonthego.editor.ui import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry diff --git a/app/src/androidTest/kotlin/org/appdevforall/codeonthego/helper/AdvancePastWelcomeScreenHelper.kt b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/helper/AdvancePastWelcomeScreenHelper.kt new file mode 100644 index 0000000000..da89a7dd8f --- /dev/null +++ b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/helper/AdvancePastWelcomeScreenHelper.kt @@ -0,0 +1,67 @@ +package org.appdevforall.codeonthego.helper + +import android.view.accessibility.AccessibilityNodeInfo +import androidx.test.platform.app.InstrumentationRegistry +import com.kaspersky.kaspresso.testcases.core.testcontext.TestContext + +/** + * Clicks the Next button on the welcome screen using accessibility ACTION_CLICK. + * The button is in the system gesture exclusion zone so coordinate-based clicks fail. + */ +fun TestContext.advancePastWelcomeScreen() { + step("Click continue button on the Welcome Screen") { + flakySafely(timeoutMs = 3_000) { + device.uiDevice.waitForIdle() + + val clicked = + accessibilityClickByDescription("NEXT") || + accessibilityClickByText("Next") || + accessibilityClickByText("Continue") + + if (!clicked) { + throw AssertionError("Next/Continue button not found on welcome screen") + } + device.uiDevice.waitForIdle() + } + } +} + +private fun accessibilityClickByDescription(desc: String): Boolean { + val root = + InstrumentationRegistry + .getInstrumentation() + .uiAutomation + .rootInActiveWindow ?: return false + val nodes = root.findAccessibilityNodeInfosByText(desc) + for (node in nodes) { + if (node.contentDescription?.toString()?.contains(desc, ignoreCase = true) == true) { + val result = node.performAction(AccessibilityNodeInfo.ACTION_CLICK) + node.recycle() + root.recycle() + return result + } + node.recycle() + } + root.recycle() + return false +} + +private fun accessibilityClickByText(text: String): Boolean { + val root = + InstrumentationRegistry + .getInstrumentation() + .uiAutomation + .rootInActiveWindow ?: return false + val nodes = root.findAccessibilityNodeInfosByText(text) + for (node in nodes) { + if (node.text?.toString()?.contains(text, ignoreCase = true) == true) { + val result = node.performAction(AccessibilityNodeInfo.ACTION_CLICK) + node.recycle() + root.recycle() + return result + } + node.recycle() + } + root.recycle() + return false +} diff --git a/app/src/androidTest/kotlin/com/itsaky/androidide/helper/ConfigureAutomationBuildPreferencesHelper.kt b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/helper/ConfigureAutomationBuildPreferencesHelper.kt similarity index 91% rename from app/src/androidTest/kotlin/com/itsaky/androidide/helper/ConfigureAutomationBuildPreferencesHelper.kt rename to app/src/androidTest/kotlin/org/appdevforall/codeonthego/helper/ConfigureAutomationBuildPreferencesHelper.kt index 1eaddee4ca..86c01eea15 100644 --- a/app/src/androidTest/kotlin/com/itsaky/androidide/helper/ConfigureAutomationBuildPreferencesHelper.kt +++ b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/helper/ConfigureAutomationBuildPreferencesHelper.kt @@ -1,9 +1,9 @@ -package com.itsaky.androidide.helper +package org.appdevforall.codeonthego.helper import android.util.Log import androidx.test.platform.app.InstrumentationRegistry -import com.itsaky.androidide.preferences.internal.BuildPreferences import com.kaspersky.kaspresso.testcases.core.testcontext.TestContext +import org.appdevforall.codeonthego.preferences.internal.BuildPreferences private const val TAG = "AutomationBuildPrefs" private const val ARG_BUILD_OFFLINE = "androidide.build.offline" diff --git a/app/src/androidTest/kotlin/com/itsaky/androidide/helper/DevicePermissionGrantUiHelper.kt b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/helper/DevicePermissionGrantUiHelper.kt similarity index 99% rename from app/src/androidTest/kotlin/com/itsaky/androidide/helper/DevicePermissionGrantUiHelper.kt rename to app/src/androidTest/kotlin/org/appdevforall/codeonthego/helper/DevicePermissionGrantUiHelper.kt index 95545047f3..a16c2a435f 100644 --- a/app/src/androidTest/kotlin/com/itsaky/androidide/helper/DevicePermissionGrantUiHelper.kt +++ b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/helper/DevicePermissionGrantUiHelper.kt @@ -1,4 +1,4 @@ -package com.itsaky.androidide.helper +package org.appdevforall.codeonthego.helper import android.Manifest import android.os.SystemClock diff --git a/app/src/androidTest/kotlin/com/itsaky/androidide/helper/EnsureHomeScreenHelper.kt b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/helper/EnsureHomeScreenHelper.kt similarity index 92% rename from app/src/androidTest/kotlin/com/itsaky/androidide/helper/EnsureHomeScreenHelper.kt rename to app/src/androidTest/kotlin/org/appdevforall/codeonthego/helper/EnsureHomeScreenHelper.kt index 06d06bb7c5..8687fa5697 100644 --- a/app/src/androidTest/kotlin/com/itsaky/androidide/helper/EnsureHomeScreenHelper.kt +++ b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/helper/EnsureHomeScreenHelper.kt @@ -1,4 +1,4 @@ -package com.itsaky.androidide.helper +package org.appdevforall.codeonthego.helper import android.content.Context import android.content.Intent @@ -9,10 +9,10 @@ import androidx.test.uiautomator.UiDevice import androidx.test.uiautomator.UiSelector import com.itsaky.androidide.BuildConfig import com.itsaky.androidide.R -import com.itsaky.androidide.activities.MainActivity -import com.itsaky.androidide.preferences.internal.GeneralPreferences -import com.itsaky.androidide.screens.HomeScreen import com.kaspersky.kaspresso.testcases.core.testcontext.TestContext +import org.appdevforall.codeonthego.activities.MainActivity +import org.appdevforall.codeonthego.preferences.internal.GeneralPreferences +import org.appdevforall.codeonthego.screens.HomeScreen import org.hamcrest.Matchers private const val TAG = "EnsureHomeScreen" @@ -65,16 +65,20 @@ fun TestContext.ensureOnHomeScreenBeforeCreateProject() { testLog("Post-onboarding screen=$state (package=$pkg)") when (state) { - PostOnboardingScreen.EDITOR -> + PostOnboardingScreen.EDITOR -> { runCatching { testLog("Attempting drawer → close project → close without saving") closeProjectViaDrawerThenCloseWithoutSaving(device.uiDevice, targetContext) }.onFailure { testLog("Drawer close failed: ${it.message}") } + } - PostOnboardingScreen.UNKNOWN -> + PostOnboardingScreen.UNKNOWN -> { testLog("Screen UNKNOWN — will try relaunch if home not visible") + } - PostOnboardingScreen.HOME -> testLog("Screen looks like HOME already") + PostOnboardingScreen.HOME -> { + testLog("Screen looks like HOME already") + } } device.uiDevice.waitForIdle(3000) @@ -235,9 +239,9 @@ fun logOnboardingNavigation(msg: String) { } /** - * After "Finish installation" on the permissions slide, [com.itsaky.androidide.fragments.onboarding.PermissionsFragment] - * runs IDE setup — there is **no** guarantee that AppIntro's `@id/done` exists ([com.itsaky.androidide.activities.OnboardingActivity] does not add - * [com.itsaky.androidide.fragments.onboarding.IdeSetupConfigurationFragment] as a slide). Poll until **Get started** + * After "Finish installation" on the permissions slide, [org.appdevforall.codeonthego.fragments.onboarding.PermissionsFragment] + * runs IDE setup — there is **no** guarantee that AppIntro's `@id/done` exists ([org.appdevforall.codeonthego.activities.OnboardingActivity] does not add + * [org.appdevforall.codeonthego.fragments.onboarding.IdeSetupConfigurationFragment] as a slide). Poll until **Get started** * or **editor** is visible. * * First-run IDE setup extracts multi-GB assets (bootstrap, SDK, Gradle dist, diff --git a/app/src/androidTest/kotlin/com/itsaky/androidide/helper/ExperimentsFlagHelper.kt b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/helper/ExperimentsFlagHelper.kt similarity index 92% rename from app/src/androidTest/kotlin/com/itsaky/androidide/helper/ExperimentsFlagHelper.kt rename to app/src/androidTest/kotlin/org/appdevforall/codeonthego/helper/ExperimentsFlagHelper.kt index d2bbb99493..95b9170338 100644 --- a/app/src/androidTest/kotlin/com/itsaky/androidide/helper/ExperimentsFlagHelper.kt +++ b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/helper/ExperimentsFlagHelper.kt @@ -1,9 +1,9 @@ -package com.itsaky.androidide.helper +package org.appdevforall.codeonthego.helper import android.os.ParcelFileDescriptor import androidx.test.platform.app.InstrumentationRegistry -import com.itsaky.androidide.utils.FeatureFlags import kotlinx.coroutines.runBlocking +import org.appdevforall.codeonthego.utils.FeatureFlags import org.junit.Assert.assertEquals private const val EXPERIMENTS_FLAG_PATH = "/sdcard/Download/CodeOnTheGo.exp" @@ -36,7 +36,7 @@ fun setExperimentsFlagForTest(enabled: Boolean) { .apply { isAccessible = true } val defaultFlags = Class - .forName("com.itsaky.androidide.utils.FlagsCache") + .forName("org.appdevforall.codeonthego.utils.FlagsCache") .getDeclaredField("DEFAULT") .apply { isAccessible = true } .get(null) diff --git a/app/src/androidTest/kotlin/com/itsaky/androidide/helper/FakeInstalledPackages.kt b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/helper/FakeInstalledPackages.kt similarity index 96% rename from app/src/androidTest/kotlin/com/itsaky/androidide/helper/FakeInstalledPackages.kt rename to app/src/androidTest/kotlin/org/appdevforall/codeonthego/helper/FakeInstalledPackages.kt index 4f00488e88..3a87c2ab95 100644 --- a/app/src/androidTest/kotlin/com/itsaky/androidide/helper/FakeInstalledPackages.kt +++ b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/helper/FakeInstalledPackages.kt @@ -1,4 +1,4 @@ -package com.itsaky.androidide.helper +package org.appdevforall.codeonthego.helper import org.appdevforall.cotg.quickbuild.service.provision.InstalledPackages import java.io.File diff --git a/app/src/androidTest/kotlin/com/itsaky/androidide/helper/GrantRequiredPermissionsUiHelper.kt b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/helper/GrantRequiredPermissionsUiHelper.kt similarity index 93% rename from app/src/androidTest/kotlin/com/itsaky/androidide/helper/GrantRequiredPermissionsUiHelper.kt rename to app/src/androidTest/kotlin/org/appdevforall/codeonthego/helper/GrantRequiredPermissionsUiHelper.kt index e3d65fe98e..2e0090995e 100644 --- a/app/src/androidTest/kotlin/com/itsaky/androidide/helper/GrantRequiredPermissionsUiHelper.kt +++ b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/helper/GrantRequiredPermissionsUiHelper.kt @@ -1,11 +1,11 @@ -package com.itsaky.androidide.helper +package org.appdevforall.codeonthego.helper import android.Manifest import androidx.test.platform.app.InstrumentationRegistry import com.itsaky.androidide.R -import com.itsaky.androidide.screens.PermissionScreen -import com.itsaky.androidide.utils.PermissionsHelper import com.kaspersky.kaspresso.testcases.core.testcontext.TestContext +import org.appdevforall.codeonthego.screens.PermissionScreen +import org.appdevforall.codeonthego.utils.PermissionsHelper /** * Drives the onboarding permission list and system Settings UIs for every entry in @@ -41,15 +41,19 @@ fun TestContext.grantAllRequiredPermissionsThroughOnboardingUi() { Manifest.permission.POST_NOTIFICATIONS -> { device.grantPostNotificationsUi() } + Manifest.permission_group.STORAGE -> { device.grantStorageManageAllFilesUi() } + Manifest.permission.REQUEST_INSTALL_PACKAGES -> { device.grantInstallUnknownAppsUi() } + Manifest.permission.SYSTEM_ALERT_WINDOW -> { device.grantDisplayOverOtherAppsUi() } + else -> { throw IllegalStateException("Unknown permission row: ${item.permission}") } diff --git a/app/src/androidTest/kotlin/com/itsaky/androidide/helper/HandlePrivacyDisclosureHelper.kt b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/helper/HandlePrivacyDisclosureHelper.kt similarity index 93% rename from app/src/androidTest/kotlin/com/itsaky/androidide/helper/HandlePrivacyDisclosureHelper.kt rename to app/src/androidTest/kotlin/org/appdevforall/codeonthego/helper/HandlePrivacyDisclosureHelper.kt index 9a766b8765..7794b29bfe 100644 --- a/app/src/androidTest/kotlin/com/itsaky/androidide/helper/HandlePrivacyDisclosureHelper.kt +++ b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/helper/HandlePrivacyDisclosureHelper.kt @@ -1,11 +1,11 @@ -package com.itsaky.androidide.helper +package org.appdevforall.codeonthego.helper import android.util.Log import androidx.test.platform.app.InstrumentationRegistry import androidx.test.uiautomator.UiSelector -import com.itsaky.androidide.preferences.internal.StatPreferences -import com.itsaky.androidide.preferences.internal.TelemetryConsent import com.kaspersky.kaspresso.testcases.core.testcontext.TestContext +import org.appdevforall.codeonthego.preferences.internal.StatPreferences +import org.appdevforall.codeonthego.preferences.internal.TelemetryConsent import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import com.itsaky.androidide.resources.R as ResourcesR diff --git a/app/src/androidTest/kotlin/org/appdevforall/codeonthego/helper/ProjectBuildHelper.kt b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/helper/ProjectBuildHelper.kt new file mode 100644 index 0000000000..fb775901e9 --- /dev/null +++ b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/helper/ProjectBuildHelper.kt @@ -0,0 +1,48 @@ +package org.appdevforall.codeonthego.helper + +import com.kaspersky.kaspresso.testcases.core.testcontext.TestContext +import org.appdevforall.codeonthego.scenarios.InitializationProjectAndCancelingBuildScenario +import org.appdevforall.codeonthego.scenarios.NavigateToMainScreenScenario +import org.appdevforall.codeonthego.scenarios.RunAssembleTasksScenario +import org.appdevforall.codeonthego.screens.TemplateScreen.selectTemplate + +fun TestContext.navigateToMainScreen() { + step("Initialize the app and navigate to the Main Screen") { + scenario(NavigateToMainScreenScenario()) + } +} + +fun TestContext.selectProjectTemplate( + stepTitle: String, + templateResId: Int, + visibleTextOverride: String? = null, +) { + step(stepTitle) { + selectTemplate(templateResId, visibleTextOverride) + } +} + +fun TestContext.initializeProjectAndCancelBuild() { + step("Initialization the project and cancelling the build") { + scenario(InitializationProjectAndCancelingBuildScenario()) + } +} + +fun TestContext.initializeProjectRunAssembleTasksAndCancelBuild() { + step("Initialize project, quick-run debug build, and run assemble task set") { + var failure: Throwable? = null + try { + scenario(InitializationProjectAndCancelingBuildScenario(closeProjectAfterBuild = false)) + scenario(RunAssembleTasksScenario()) + } catch (throwable: Throwable) { + failure = throwable + throw throwable + } finally { + runCatching { + scenario(InitializationProjectAndCancelingBuildScenario.CloseProjectScenario()) + }.onFailure { closeFailure -> + failure?.addSuppressed(closeFailure) ?: throw closeFailure + } + } + } +} diff --git a/app/src/androidTest/kotlin/com/itsaky/androidide/scenarios/InitializationProjectAndCancelingBuildScenario.kt b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/scenarios/InitializationProjectAndCancelingBuildScenario.kt similarity index 98% rename from app/src/androidTest/kotlin/com/itsaky/androidide/scenarios/InitializationProjectAndCancelingBuildScenario.kt rename to app/src/androidTest/kotlin/org/appdevforall/codeonthego/scenarios/InitializationProjectAndCancelingBuildScenario.kt index deee418d32..807979a0f7 100644 --- a/app/src/androidTest/kotlin/com/itsaky/androidide/scenarios/InitializationProjectAndCancelingBuildScenario.kt +++ b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/scenarios/InitializationProjectAndCancelingBuildScenario.kt @@ -1,13 +1,13 @@ -package com.itsaky.androidide.scenarios +package org.appdevforall.codeonthego.scenarios import android.util.Log import androidx.test.platform.app.InstrumentationRegistry import androidx.test.uiautomator.UiSelector import com.itsaky.androidide.R -import com.itsaky.androidide.helper.clickFirstAccessibilityNodeByDescription -import com.itsaky.androidide.helper.clickFirstAccessibilityNodeByText import com.kaspersky.kaspresso.testcases.api.scenario.Scenario import com.kaspersky.kaspresso.testcases.core.testcontext.TestContext +import org.appdevforall.codeonthego.helper.clickFirstAccessibilityNodeByDescription +import org.appdevforall.codeonthego.helper.clickFirstAccessibilityNodeByText private const val CLOSE_PROJECT_TAG = "CloseProjectScenario" private const val DEFAULT_TOOLBAR_BUTTON_TIMEOUT_MS = 10_000L diff --git a/app/src/androidTest/kotlin/org/appdevforall/codeonthego/scenarios/NavigateToMainScreenScenario.kt b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/scenarios/NavigateToMainScreenScenario.kt new file mode 100644 index 0000000000..f9409a2fad --- /dev/null +++ b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/scenarios/NavigateToMainScreenScenario.kt @@ -0,0 +1,125 @@ +package org.appdevforall.codeonthego.scenarios + +import androidx.test.platform.app.InstrumentationRegistry +import androidx.test.uiautomator.UiSelector +import com.kaspersky.kaspresso.testcases.api.scenario.Scenario +import com.kaspersky.kaspresso.testcases.core.testcontext.TestContext +import org.appdevforall.codeonthego.helper.advancePastWelcomeScreen +import org.appdevforall.codeonthego.helper.clickFirstAccessibilityNodeByText +import org.appdevforall.codeonthego.helper.grantAllRequiredPermissionsThroughOnboardingUi +import org.appdevforall.codeonthego.helper.logOnboardingNavigation +import org.appdevforall.codeonthego.helper.waitForMainHomeOrEditorUi +import org.appdevforall.codeonthego.screens.InstallToolsScreen +import org.appdevforall.codeonthego.screens.PermissionScreen + +/** + * Navigates from whatever the current onboarding state is to the main screen. + * + * Each step checks whether it's needed before acting, so this scenario is + * idempotent — safe to call whether onboarding is at the welcome screen, + * the permissions list, or already on the main screen. + */ +class NavigateToMainScreenScenario : Scenario() { + override val steps: TestContext.() -> Unit = { + logOnboardingNavigation("NavigateToMainScreenScenario: starting") + + val d = device.uiDevice + val pkg = InstrumentationRegistry.getInstrumentation().targetContext.packageName + + // If we're already on the main screen, skip everything + step("Check if already on main screen") { + d.waitForIdle() + val getStarted = d.findObject(UiSelector().resourceIdMatches(".*:id/getStarted")) + val editor = d.findObject(UiSelector().resourceIdMatches(".*:id/editor_appBarLayout")) + if (getStarted.waitForExists(1_000) || editor.exists()) { + logOnboardingNavigation("Already on main screen — skipping onboarding") + return@step + } + } + + // If the welcome screen NEXT button is visible, advance past it + step("Advance past welcome screen (if showing)") { + val nextBtn = d.findObject(UiSelector().descriptionContains("NEXT")) + val permissionTitle = d.findObject(UiSelector().resourceIdMatches(".*:id/onboarding_title")) + // Only advance if we appear to be on the welcome slide (NEXT visible but not yet on permissions) + if (nextBtn.waitForExists(1_000)) { + // Check if we're on the welcome slide vs permissions info slide + // The welcome slide has a greeting title, not the permissions title + val greetingTitle = d.findObject(UiSelector().resourceIdMatches(".*:id/title").textContains("Code on the Go")) + if (greetingTitle.exists()) { + logOnboardingNavigation("Welcome screen visible — advancing") + advancePastWelcomeScreen() + } + } + } + + // If the privacy dialog is showing, accept it + step("Accept privacy dialog (if showing)") { + val ctx = InstrumentationRegistry.getInstrumentation().targetContext + val accept = ctx.getString(com.itsaky.androidide.resources.R.string.privacy_disclosure_accept) + val btn = d.findObject(UiSelector().text(accept)) + if (btn.waitForExists(1_000)) { + logOnboardingNavigation("Privacy dialog visible — accepting") + clickFirstAccessibilityNodeByText(accept) + d.waitForIdle() + } + } + + // If the permission list is showing, grant all permissions + step("Grant permissions (if on permission list)") { + val permScreen = d.findObject(UiSelector().resourceIdMatches(".*:id/onboarding_items")) + if (permScreen.waitForExists(2_000)) { + val ctx = InstrumentationRegistry.getInstrumentation().targetContext + val grantText = ctx.getString(com.itsaky.androidide.R.string.title_grant) + val grantBtn = d.findObject(UiSelector().text(grantText)) + if (grantBtn.exists()) { + logOnboardingNavigation("Permission list visible with ungranted permissions — granting") + grantAllRequiredPermissionsThroughOnboardingUi() + } + } + } + + step("Finish installation (leave permission screen)") { + flakySafely(timeoutMs = 20_000) { + PermissionScreen { + finishInstallationButton { + isVisible() + isEnabled() + isClickable() + click() + } + } + } + } + + step("After Finish installation: optional AppIntro Done, then wait for IDE setup -> main UI") { + logOnboardingNavigation( + "Permissions Finish starts in-app IDE setup; AppIntro R.id.done is often absent — waiting for main UI", + ) + runCatching { + flakySafely(timeoutMs = 12_000) { + InstallToolsScreen.doneButton { + isVisible() + click() + } + } + }.fold( + onSuccess = { logOnboardingNavigation("Clicked legacy AppIntro Done (optional)") }, + onFailure = { + logOnboardingNavigation( + "No AppIntro Done within 12s (expected): ${it.javaClass.simpleName} ${it.message}", + ) + }, + ) + waitForMainHomeOrEditorUi(device.uiDevice, maxWaitMs = 300_000L) + } + + step("Decline runtime permission dialog if still shown") { + runCatching { + flakySafely(timeoutMs = 8000) { + device.permissions.denyViaDialog() + } + } + } + } +} diff --git a/app/src/androidTest/kotlin/org/appdevforall/codeonthego/scenarios/RunAssembleTasksScenario.kt b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/scenarios/RunAssembleTasksScenario.kt new file mode 100644 index 0000000000..eea58ff2cc --- /dev/null +++ b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/scenarios/RunAssembleTasksScenario.kt @@ -0,0 +1,168 @@ +package org.appdevforall.codeonthego.scenarios + +import android.util.Log +import androidx.test.platform.app.InstrumentationRegistry +import androidx.test.uiautomator.UiScrollable +import androidx.test.uiautomator.UiSelector +import com.itsaky.androidide.R +import com.kaspersky.kaspresso.testcases.api.scenario.Scenario +import com.kaspersky.kaspresso.testcases.core.testcontext.TestContext +import org.appdevforall.codeonthego.helper.clickFirstAccessibilityNodeByDescription +import org.appdevforall.codeonthego.helper.clickFirstAccessibilityNodeParentByText + +private const val RUN_ASSEMBLE_TAG = "RunAssembleTasks" +private const val SHORT_UI_TIMEOUT_MS = 2_000L +private const val DEFAULT_UI_TIMEOUT_MS = 3_000L +private const val INSTALLER_GONE_TIMEOUT_MS = 5_000L +private const val RUN_TASKS_DIALOG_TIMEOUT_MS = 10_000L +private const val TASK_SELECTION_TIMEOUT_MS = 20_000L +private const val EDITOR_TOOLBAR_TIMEOUT_MS = 30_000L +private const val BUILD_LOG_INTERVAL_MS = 10_000L +private const val POLL_INTERVAL_MS = 1_000L + +private fun runAssembleLog(message: String) { + Log.e(RUN_ASSEMBLE_TAG, message) + System.err.println("$RUN_ASSEMBLE_TAG: $message") +} + +class RunAssembleTasksScenario( + private val tasks: List = DEFAULT_ASSEMBLE_TASKS, +) : Scenario() { + override val steps: TestContext.() -> Unit = { + step("Dismiss post-build overlays before running assemble tasks") { + val d = device.uiDevice + val dismiss = d.findObject(UiSelector().text("Dismiss")) + if (dismiss.waitForExists(DEFAULT_UI_TIMEOUT_MS)) { + dismiss.click() + d.waitForIdle() + } + val installer = + d.findObject( + UiSelector().packageNameMatches(".*packageinstaller.*|.*permissioncontroller.*"), + ) + if (installer.exists()) { + runAssembleLog("Package installer still visible before assemble tasks; dismissing") + val cancel = d.findObject(UiSelector().textMatches("(?i)cancel")) + if (cancel.waitForExists(SHORT_UI_TIMEOUT_MS)) { + cancel.click() + } else { + d.pressBack() + } + runCatching { installer.waitUntilGone(INSTALLER_GONE_TIMEOUT_MS) } + d.waitForIdle() + } + } + + step("Open Run tasks dialog") { + val d = device.uiDevice + val targetContext = InstrumentationRegistry.getInstrumentation().targetContext + val runTasksDescription = targetContext.getString(R.string.cd_toolbar_run_gradle_tasks) + val toolbar = d.findObject(UiSelector().resourceIdMatches(".*:id/editor_appBarLayout")) + check(toolbar.waitForExists(EDITOR_TOOLBAR_TIMEOUT_MS)) { "Editor toolbar not found" } + clickFirstAccessibilityNodeByDescription(runTasksDescription) + d.waitForIdle() + + val title = targetContext.getString(R.string.title_run_tasks) + check(d.findObject(UiSelector().text(title)).waitForExists(RUN_TASKS_DIALOG_TIMEOUT_MS)) { + "Run tasks dialog did not open" + } + } + + step("Filter assemble tasks") { + val d = device.uiDevice + val search = d.findObject(UiSelector().className("android.widget.EditText")) + check(search.waitForExists(RUN_TASKS_DIALOG_TIMEOUT_MS)) { "Run tasks search field not found" } + search.setText("assemble") + d.waitForIdle() + } + + tasks.forEach { task -> + step("Select Gradle task $task") { + val d = device.uiDevice + var taskNode = d.findObject(UiSelector().text(task)) + if (!taskNode.waitForExists(DEFAULT_UI_TIMEOUT_MS)) { + UiScrollable(UiSelector().scrollable(true)).scrollTextIntoView(task) + taskNode = d.findObject(UiSelector().text(task)) + } + check(taskNode.waitForExists(TASK_SELECTION_TIMEOUT_MS)) { + "Task not found in Run tasks dialog: $task" + } + clickFirstAccessibilityNodeParentByText(task) + d.waitForIdle() + } + } + + step("Confirm and run selected Gradle tasks") { + val d = device.uiDevice + val runButton = d.findObject(UiSelector().resourceIdMatches(".*:id/exec")) + check(runButton.waitForExists(RUN_TASKS_DIALOG_TIMEOUT_MS)) { "Run tasks execute button not found" } + runButton.click() + d.waitForIdle() + + tasks.forEach { task -> + check(d.findObject(UiSelector().textContains(task)).waitForExists(RUN_TASKS_DIALOG_TIMEOUT_MS)) { + "Run tasks confirmation missing selected task: $task" + } + } + + runButton.click() + d.waitForIdle() + runAssembleLog("Selected assemble tasks submitted") + } + + step("Wait for selected Gradle tasks to finish") { + runAssembleLog("Waiting for selected assemble tasks to finish") + val d = device.uiDevice + val success = d.findObject(UiSelector().textContains("Build completed successfully")) + val gradleSuccess = d.findObject(UiSelector().textContains("BUILD SUCCESSFUL")) + val failure = d.findObject(UiSelector().textContains("Build failed")) + val gradleFailure = d.findObject(UiSelector().textContains("BUILD FAILED")) + + val deadline = System.currentTimeMillis() + BUILD_TIMEOUT_MS + var lastLogAt = 0L + var completed = false + + while (System.currentTimeMillis() < deadline && !completed) { + if (success.exists() || gradleSuccess.exists()) { + completed = true + break + } + + check(!failure.exists() && !gradleFailure.exists()) { + "Selected Gradle tasks failed" + } + + val now = System.currentTimeMillis() + if (now - lastLogAt > BUILD_LOG_INTERVAL_MS) { + runAssembleLog("Still waiting for selected assemble tasks to finish") + lastLogAt = now + } + + Thread.sleep(POLL_INTERVAL_MS) + d.waitForIdle() + } + + check(completed) { + "Timed out waiting for selected Gradle tasks to complete" + } + runAssembleLog("Selected assemble tasks finished; continuing to close project") + d.waitForIdle() + } + } + + companion object { + val DEFAULT_ASSEMBLE_TASKS = + listOf( + ":app:assemble", + ":app:assembleAndroidTest", + ":app:assembleDebug", + ":app:assembleDebugAndroidTest", + ":app:assembleDebugUnitTest", + ":app:assembleRelease", + ":app:assembleReleaseUnitTest", + ":app:assembleUnitTest", + ) + + private const val BUILD_TIMEOUT_MS = 10 * 60 * 1000L + } +} diff --git a/app/src/androidTest/kotlin/org/appdevforall/codeonthego/screens/EditorScreen.kt b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/screens/EditorScreen.kt new file mode 100644 index 0000000000..ca79a16994 --- /dev/null +++ b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/screens/EditorScreen.kt @@ -0,0 +1,14 @@ +package org.appdevforall.codeonthego.screens + +import com.kaspersky.kaspresso.screens.KScreen +import io.github.kakaocup.kakao.dialog.KAlertDialog + +object EditorScreen : KScreen() { + override val layoutId: Int? = null + + override val viewClass: Class<*>? = null + + val firstBuildDialog = KAlertDialog() + + val closeProjectDialog = KAlertDialog() +} diff --git a/app/src/androidTest/kotlin/com/itsaky/androidide/screens/ErrorBannerScreen.kt b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/screens/ErrorBannerScreen.kt similarity index 98% rename from app/src/androidTest/kotlin/com/itsaky/androidide/screens/ErrorBannerScreen.kt rename to app/src/androidTest/kotlin/org/appdevforall/codeonthego/screens/ErrorBannerScreen.kt index 0c3bd5b661..61e1eeb17d 100644 --- a/app/src/androidTest/kotlin/com/itsaky/androidide/screens/ErrorBannerScreen.kt +++ b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/screens/ErrorBannerScreen.kt @@ -1,4 +1,4 @@ -package com.itsaky.androidide.screens +package org.appdevforall.codeonthego.screens import androidx.test.uiautomator.UiObject import androidx.test.uiautomator.UiSelector diff --git a/app/src/androidTest/kotlin/com/itsaky/androidide/screens/HomeScreen.kt b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/screens/HomeScreen.kt similarity index 89% rename from app/src/androidTest/kotlin/com/itsaky/androidide/screens/HomeScreen.kt rename to app/src/androidTest/kotlin/org/appdevforall/codeonthego/screens/HomeScreen.kt index d922930d78..de4734956a 100644 --- a/app/src/androidTest/kotlin/com/itsaky/androidide/screens/HomeScreen.kt +++ b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/screens/HomeScreen.kt @@ -1,11 +1,11 @@ -package com.itsaky.androidide.screens +package org.appdevforall.codeonthego.screens import androidx.test.platform.app.InstrumentationRegistry import com.itsaky.androidide.R -import com.itsaky.androidide.helper.clickFirstAccessibilityNodeByText import com.kaspersky.kaspresso.screens.KScreen import com.kaspersky.kaspresso.testcases.core.testcontext.TestContext import io.github.kakaocup.kakao.text.KTextView +import org.appdevforall.codeonthego.helper.clickFirstAccessibilityNodeByText import com.itsaky.androidide.resources.R as ResourcesR object HomeScreen : KScreen() { diff --git a/app/src/androidTest/kotlin/org/appdevforall/codeonthego/screens/InstallToolsScreen.kt b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/screens/InstallToolsScreen.kt new file mode 100644 index 0000000000..00ace11ac7 --- /dev/null +++ b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/screens/InstallToolsScreen.kt @@ -0,0 +1,12 @@ +package org.appdevforall.codeonthego.screens + +import com.itsaky.androidide.R +import com.kaspersky.kaspresso.screens.KScreen +import io.github.kakaocup.kakao.text.KButton + +object InstallToolsScreen : KScreen() { + override val layoutId: Int? = null + override val viewClass: Class<*>? = null + + val doneButton = KButton { withId(R.id.done) } +} diff --git a/app/src/androidTest/kotlin/org/appdevforall/codeonthego/screens/OnboardingScreen.kt b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/screens/OnboardingScreen.kt new file mode 100644 index 0000000000..b8a91550f4 --- /dev/null +++ b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/screens/OnboardingScreen.kt @@ -0,0 +1,23 @@ +package org.appdevforall.codeonthego.screens + +import com.itsaky.androidide.R +import com.kaspersky.kaspresso.screens.KScreen +import io.github.kakaocup.kakao.text.KButton +import io.github.kakaocup.kakao.text.KTextView + +object OnboardingScreen : KScreen() { + override val layoutId: Int? = null + override val viewClass: Class<*>? = null + + val greetingTitle = + KTextView { + withId(R.id.title) + isDisplayed() + } + val greetingSubtitle = + KTextView { + withId(R.id.description) + isDisplayed() + } + val nextButton = KButton { withId(R.id.next) } +} diff --git a/app/src/androidTest/kotlin/org/appdevforall/codeonthego/screens/PermissionScreen.kt b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/screens/PermissionScreen.kt new file mode 100644 index 0000000000..017681e63e --- /dev/null +++ b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/screens/PermissionScreen.kt @@ -0,0 +1,34 @@ +package org.appdevforall.codeonthego.screens + +import android.view.View +import com.itsaky.androidide.R +import com.kaspersky.kaspresso.screens.KScreen +import io.github.kakaocup.kakao.recycler.KRecyclerItem +import io.github.kakaocup.kakao.recycler.KRecyclerView +import io.github.kakaocup.kakao.text.KButton +import io.github.kakaocup.kakao.text.KTextView +import org.hamcrest.Matcher + +object PermissionScreen : KScreen() { + override val layoutId: Int? = null + override val viewClass: Class<*>? = null + + val title = KTextView { withText(R.string.onboarding_title_permissions) } + val subTitle = KTextView { withText(R.string.onboarding_subtitle_permissions) } + + val rvPermissions = + KRecyclerView( + builder = { withId(R.id.onboarding_items) }, + itemTypeBuilder = { itemType(::PermissionItem) }, + ) + + val finishInstallationButton = KButton { withId(R.id.finish_installation_button) } + + class PermissionItem( + matcher: Matcher, + ) : KRecyclerItem(matcher) { + val grantButton = KButton(matcher) { withId(R.id.grant_button) } + val title = KTextView(matcher) { withId(R.id.title) } + val description = KTextView(matcher) { withId(R.id.description) } + } +} diff --git a/app/src/androidTest/kotlin/org/appdevforall/codeonthego/screens/ProjectSettingsScreen.kt b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/screens/ProjectSettingsScreen.kt new file mode 100644 index 0000000000..abaf6b7611 --- /dev/null +++ b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/screens/ProjectSettingsScreen.kt @@ -0,0 +1,129 @@ +package org.appdevforall.codeonthego.screens + +import androidx.test.uiautomator.UiSelector +import com.itsaky.androidide.R +import com.kaspersky.kaspresso.screens.KScreen +import com.kaspersky.kaspresso.testcases.core.testcontext.TestContext +import io.github.kakaocup.kakao.check.KCheckBox +import io.github.kakaocup.kakao.spinner.KSpinner +import io.github.kakaocup.kakao.spinner.KSpinnerItem +import io.github.kakaocup.kakao.text.KButton +import org.appdevforall.codeonthego.helper.clickFirstAccessibilityNodeByText +import org.appdevforall.codeonthego.helper.setAccessibilityEditText + +private const val KOTLIN_LANGUAGE_SELECTION_TIMEOUT_MS = 30_000L +private const val LANGUAGE_OPTION_TIMEOUT_MS = 5_000L +private const val LANGUAGE_DROPDOWN_EXPANSION_TIMEOUT_MS = 2_000L +private const val PROJECT_NAME_FIELD_TIMEOUT_MS = 3_000L +private const val LANGUAGE_DROPDOWN_FALLBACK_X_OFFSET = 80 + +object ProjectSettingsScreen : KScreen() { + override val layoutId: Int? = null + + override val viewClass: Class<*>? = null + + val createProjectButton = + KButton { + withText(R.string.create_project) + withId(R.id.finish) + } + + val spinner = + KSpinner( + builder = { withHint("Project Language") }, + itemTypeBuilder = { itemType(::KSpinnerItem) }, + ) + + val kotlinScriptText = + KCheckBox { + withText(R.string.msg_use_kts) + } + + fun TestContext.selectJavaLanguage() { + step("Select the java language") { + val javaText = device.targetContext.getString(R.string.lang_java) + ProjectSettingsScreen { + spinner { + isVisible() + open() + + childAt(0) { + isVisible() + hasText(javaText) + click() + } + } + } + } + } + + fun TestContext.selectKotlinLanguage() { + step("Select the kotlin language") { + flakySafely(KOTLIN_LANGUAGE_SELECTION_TIMEOUT_MS) { + val kotlinText = device.targetContext.getString(R.string.lang_kotlin) + openProjectLanguageDropdown() + + val d = device.uiDevice + val kotlin = d.findObject(UiSelector().text(kotlinText)) + check(kotlin.waitForExists(LANGUAGE_OPTION_TIMEOUT_MS)) { "Kotlin language option not found" } + kotlin.click() + d.waitForIdle() + } + } + } + + private fun TestContext.openProjectLanguageDropdown() { + val d = device.uiDevice + val javaText = device.targetContext.getString(R.string.lang_java) + val kotlinText = device.targetContext.getString(R.string.lang_kotlin) + val languageLabelText = device.targetContext.getString(R.string.wizard_language) + + val javaValue = d.findObject(UiSelector().text(javaText)) + if (javaValue.waitForExists(LANGUAGE_OPTION_TIMEOUT_MS)) { + val bounds = javaValue.visibleBounds + d.click(bounds.centerX(), bounds.centerY()) + d.waitForIdle() + if (d.findObject(UiSelector().text(kotlinText)).waitForExists(LANGUAGE_DROPDOWN_EXPANSION_TIMEOUT_MS)) { + return + } + } + + val languageLabel = d.findObject(UiSelector().text(languageLabelText)) + if (languageLabel.waitForExists(LANGUAGE_OPTION_TIMEOUT_MS)) { + val bounds = languageLabel.visibleBounds + d.click(d.displayWidth - LANGUAGE_DROPDOWN_FALLBACK_X_OFFSET, bounds.centerY()) + d.waitForIdle() + if (d.findObject(UiSelector().text(kotlinText)).waitForExists(LANGUAGE_DROPDOWN_EXPANSION_TIMEOUT_MS)) { + return + } + } + + error("Project language dropdown did not open") + } + + fun TestContext.clickCreateProjectProjectSettings() { + step("Click create project on the Settings Page") { + val createText = device.targetContext.getString(R.string.create_project) + clickFirstAccessibilityNodeByText(createText) + device.uiDevice.waitForIdle() + } + } + + fun TestContext.setProjectName(name: String) { + step("Set project name to '$name'") { + val d = device.uiDevice + val byText = d.findObject(UiSelector().textStartsWith("My Application")) + check(byText.waitForExists(PROJECT_NAME_FIELD_TIMEOUT_MS)) { "Project name field not found" } + setAccessibilityEditText("My Application", name, "project name") + d.waitForIdle() + } + } + + fun TestContext.uncheckKotlinScript() { + step("Unselect Kotlin Script for Gradle") { + kotlinScriptText { + setChecked(false) + } + } + } +} diff --git a/app/src/androidTest/kotlin/com/itsaky/androidide/screens/QuickBuildScreen.kt b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/screens/QuickBuildScreen.kt similarity index 98% rename from app/src/androidTest/kotlin/com/itsaky/androidide/screens/QuickBuildScreen.kt rename to app/src/androidTest/kotlin/org/appdevforall/codeonthego/screens/QuickBuildScreen.kt index 69726610af..5df5c43d6c 100644 --- a/app/src/androidTest/kotlin/com/itsaky/androidide/screens/QuickBuildScreen.kt +++ b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/screens/QuickBuildScreen.kt @@ -1,12 +1,12 @@ -package com.itsaky.androidide.screens +package org.appdevforall.codeonthego.screens import androidx.test.platform.app.InstrumentationRegistry import androidx.test.uiautomator.UiObject import androidx.test.uiautomator.UiSelector -import com.itsaky.androidide.helper.clickFirstAccessibilityNodeByText import com.itsaky.androidide.resources.R import com.kaspersky.kaspresso.screens.KScreen import com.kaspersky.kaspresso.testcases.core.testcontext.TestContext +import org.appdevforall.codeonthego.helper.clickFirstAccessibilityNodeByText import org.junit.Assert.assertTrue private const val FIRST_BUILD_NOTICE_TIMEOUT_MS = 3_000L diff --git a/app/src/androidTest/kotlin/org/appdevforall/codeonthego/screens/SystemPermissionsScreen.kt b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/screens/SystemPermissionsScreen.kt new file mode 100644 index 0000000000..5f4123393c --- /dev/null +++ b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/screens/SystemPermissionsScreen.kt @@ -0,0 +1,22 @@ +package org.appdevforall.codeonthego.screens + +import com.kaspersky.components.kautomator.component.common.views.UiView +import com.kaspersky.components.kautomator.screen.UiScreen + +object SystemPermissionsScreen : UiScreen() { + override val packageName: String = "com.android.settings" + + val storagePermissionView = UiView { withText("Allow access to manage all files") } + val storagePermissionViewAlt1 = UiView { withText("Files and media") } + val storagePermissionViewAlt2 = UiView { withText("Access all files") } + val storagePermissionViewAlt3 = UiView { withText("Allow") } + val storagePermissionViewAlt4 = UiView { withText("Allow file management") } + val storagePermissionViewAlt5 = UiView { withText("Allow permission") } + val storagePermissionViewAlt6 = UiView { withText("Use USB storage") } + val storagePermissionViewAlt7 = UiView { withText("Storage") } + val storagePermissionViewAlt8 = UiView { withText("Files") } + + val installPackagesPermission = UiView { withText("Allow from this source") } + val installPackagesPermissionAlt1 = UiView { withText("Allow install of apps") } + val installPackagesPermissionAlt2 = UiView { withText("Allow") } +} diff --git a/app/src/androidTest/kotlin/org/appdevforall/codeonthego/screens/TemplateScreen.kt b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/screens/TemplateScreen.kt new file mode 100644 index 0000000000..14dea9f83f --- /dev/null +++ b/app/src/androidTest/kotlin/org/appdevforall/codeonthego/screens/TemplateScreen.kt @@ -0,0 +1,37 @@ +package org.appdevforall.codeonthego.screens + +import androidx.test.uiautomator.UiScrollable +import androidx.test.uiautomator.UiSelector +import com.kaspersky.kaspresso.testcases.core.testcontext.TestContext +import org.appdevforall.codeonthego.helper.clickFirstAccessibilityNodeParentByText + +object TemplateScreen { + fun TestContext.selectTemplate( + templateResId: Int, + visibleTextOverride: String? = null, + ) { + val templateText = visibleTextOverride ?: device.targetContext.getString(templateResId) + + val d = device.uiDevice + var templateItem = + d.findObject( + UiSelector().resourceIdMatches(".*:id/template_name").text(templateText), + ) + if (!templateItem.waitForExists(3_000)) { + runCatching { + UiScrollable(UiSelector().scrollable(true)).scrollTextIntoView(templateText) + } + d.waitForIdle() + templateItem = + d.findObject( + UiSelector().resourceIdMatches(".*:id/template_name").text(templateText), + ) + } + + check(templateItem.waitForExists(3_000)) { + "Template '$templateText' not found in template list" + } + clickFirstAccessibilityNodeParentByText(templateText, "template '$templateText'") + d.waitForIdle() + } +} diff --git a/app/src/debug/AndroidManifest.xml b/app/src/debug/AndroidManifest.xml index aac7406859..3ace97aad5 100644 --- a/app/src/debug/AndroidManifest.xml +++ b/app/src/debug/AndroidManifest.xml @@ -16,13 +16,13 @@ opens only a directory inside the app's own projects dir, and only while the experiments AND qbbench flags are on. --> - + diff --git a/app/src/debug/java/com/itsaky/androidide/app/LeakCanaryConfig.kt b/app/src/debug/java/com/itsaky/androidide/app/LeakCanaryConfig.kt deleted file mode 100644 index 878cf5964b..0000000000 --- a/app/src/debug/java/com/itsaky/androidide/app/LeakCanaryConfig.kt +++ /dev/null @@ -1,12 +0,0 @@ -package com.itsaky.androidide.app - -import com.itsaky.androidide.utils.FeatureFlags -import leakcanary.LeakCanary - -internal object LeakCanaryConfig { - fun applyFromFeatureFlags() { - if (FeatureFlags.isLeakCanaryDumpInhibited) { - LeakCanary.config = LeakCanary.config.copy(dumpHeap = false) - } - } -} diff --git a/app/src/debug/java/com/itsaky/androidide/quickbuild/QuickBuildBenchHooks.kt b/app/src/debug/java/com/itsaky/androidide/quickbuild/QuickBuildBenchHooks.kt deleted file mode 100644 index 83aca8d644..0000000000 --- a/app/src/debug/java/com/itsaky/androidide/quickbuild/QuickBuildBenchHooks.kt +++ /dev/null @@ -1,141 +0,0 @@ -package com.itsaky.androidide.quickbuild - -import com.itsaky.androidide.utils.FeatureFlags -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.SupervisorJob -import kotlinx.coroutines.flow.StateFlow -import org.appdevforall.cotg.quickbuild.domain.session.QuickBuildSessionState -import org.appdevforall.cotg.quickbuild.domain.telemetry.QuickBuildMetricsSink -import org.koin.core.context.GlobalContext -import org.slf4j.LoggerFactory -import java.io.File - -/** - * Every hook the ADFA-4128 benchmark harness needs from shipping code, in one place, in the - * debug source set. `src/release/` carries a no-op twin with the same signatures, so a - * release APK contains no benchmark code at all - same debug/release pair as - * [com.itsaky.androidide.app.LeakCanaryConfig]. - * - * Every hook is additionally gated on [isEnabled] (the `CodeOnTheGo.qbbench` flag file), so - * a debug build with the flag absent behaves exactly like a release one. - */ -internal object QuickBuildBenchHooks { - /** - * Whether the benchmark interface is on at all. Callers check this before doing any work - * to build a hook's arguments (a canonical-path resolution, say); every hook re-checks it - * so an unguarded call is still inert. - */ - val isEnabled: Boolean - get() = FeatureFlags.isQuickBuildBenchEnabled - - /** - * Claims a pending autostart for [projectPath] (canonical), converting the harness's wire - * mode into the editor's [AutostartBuild]. One-shot: a claimed autostart is consumed. - */ - fun claimAutostart(projectPath: String): AutostartBuild { - if (!isEnabled) return AutostartBuild.NONE - return when (QuickBuildBenchAutostart.claim(projectPath)) { - QuickBuildBenchAutostart.MODE_QUICK_BUILD -> AutostartBuild.QUICK_BUILD - QuickBuildBenchAutostart.MODE_STANDARD -> AutostartBuild.STANDARD - else -> AutostartBuild.NONE - } - } - - /** - * Stamps the start of an autostarted standard build and arms the latch - * [standardBuildEnded] reads. - */ - fun standardBuildStarted( - projectPath: String, - modulePath: String, - variantName: String, - ) { - if (!isEnabled) return - standardBuildStartMs = System.currentTimeMillis() - events()?.append("standard_build_started") { - put("project", projectPath) - put("module", modulePath) - put("variant", variantName) - } - } - - /** - * Stamps the end of an autostarted standard build. [isTerminal] is false while the build - * is still running; [isSuccess] says whether the terminal state produced something - * installable. - * - * Returns true iff the caller must SUPPRESS the install this build state would normally - * trigger: the measurement ends at the build result, and an unattended run must not pop - * an install dialog. False whenever no autostarted build is in flight - which is always, - * in a release build - so a human's build installs as usual. - */ - fun standardBuildEnded( - isTerminal: Boolean, - isSuccess: Boolean, - ): Boolean { - val startMs = standardBuildStartMs ?: return false - if (!isTerminal) return false - standardBuildStartMs = null - events()?.append("standard_build_finished") { - put("isSuccess", isSuccess) - put("durationMs", System.currentTimeMillis() - startMs) - } - return true - } - - /** - * An extra metrics sink that mirrors every callback into the JSON-lines event log, or - * null when the bench flag is off. Fanned in alongside the shipping sinks. - */ - fun metricsSink(): QuickBuildMetricsSink? { - if (!isEnabled) return null - return events()?.let(::BenchQuickBuildMetricsSink) - } - - /** - * Mirrors session-state changes into the event log - a second, read-only collector on - * the session manager's existing stream, so the UI's own collector is untouched. - */ - fun attachStateRecorder(state: StateFlow) { - if (!isEnabled) return - val events = events() ?: return - BenchStateRecorder(events) - .attach(state, CoroutineScope(SupervisorJob() + Dispatchers.IO)) - } - - /** - * Whether the post-provisioning background warm compile runs. `CodeOnTheGo.qbnoseed` - * suppresses it so an A/B runs against the same installed build; inert unless the bench - * flag is on too, and absent entirely from a release build. - */ - fun warmCompileEnabled(): Boolean = !(isEnabled && FeatureFlags.isQuickBuildWarmCompileDisabled) - - /** - * Start time of an in-flight autostarted standard build, or null when none is running. - * Written on the project-init path, read on the build-state collector - hence volatile. - */ - @Volatile - private var standardBuildStartMs: Long? = null - - @Volatile - private var eventsFile: BenchEventsFile? = null - - /** - * The shared JSON-lines writer, created on first use so a debug build with the flag off - * never touches the filesystem. One instance per process: [BenchEventsFile] serializes - * its own writes, which only helps if every writer shares it. - */ - @Synchronized - private fun events(): BenchEventsFile? { - eventsFile?.let { return it } - return runCatching { - val paths = GlobalContext.get().get() - BenchEventsFile(File(paths.quickBuildHome, "bench-events.jsonl")) - }.onFailure { log.error("Bench events file unavailable", it) } - .getOrNull() - ?.also { eventsFile = it } - } - - private val log = LoggerFactory.getLogger("QB-BenchHooks") -} diff --git a/app/src/debug/java/org/appdevforall/codeonthego/app/LeakCanaryConfig.kt b/app/src/debug/java/org/appdevforall/codeonthego/app/LeakCanaryConfig.kt new file mode 100644 index 0000000000..b99bcb3806 --- /dev/null +++ b/app/src/debug/java/org/appdevforall/codeonthego/app/LeakCanaryConfig.kt @@ -0,0 +1,12 @@ +package org.appdevforall.codeonthego.app + +import leakcanary.LeakCanary +import org.appdevforall.codeonthego.utils.FeatureFlags + +internal object LeakCanaryConfig { + fun applyFromFeatureFlags() { + if (FeatureFlags.isLeakCanaryDumpInhibited) { + LeakCanary.config = LeakCanary.config.copy(dumpHeap = false) + } + } +} diff --git a/app/src/debug/java/com/itsaky/androidide/quickbuild/BenchEventsFile.kt b/app/src/debug/java/org/appdevforall/codeonthego/quickbuild/BenchEventsFile.kt similarity index 97% rename from app/src/debug/java/com/itsaky/androidide/quickbuild/BenchEventsFile.kt rename to app/src/debug/java/org/appdevforall/codeonthego/quickbuild/BenchEventsFile.kt index 61fe245230..235cbb8bd6 100644 --- a/app/src/debug/java/com/itsaky/androidide/quickbuild/BenchEventsFile.kt +++ b/app/src/debug/java/org/appdevforall/codeonthego/quickbuild/BenchEventsFile.kt @@ -1,4 +1,4 @@ -package com.itsaky.androidide.quickbuild +package org.appdevforall.codeonthego.quickbuild import org.json.JSONObject import org.slf4j.LoggerFactory diff --git a/app/src/debug/java/com/itsaky/androidide/quickbuild/BenchQuickBuildMetricsSink.kt b/app/src/debug/java/org/appdevforall/codeonthego/quickbuild/BenchQuickBuildMetricsSink.kt similarity index 99% rename from app/src/debug/java/com/itsaky/androidide/quickbuild/BenchQuickBuildMetricsSink.kt rename to app/src/debug/java/org/appdevforall/codeonthego/quickbuild/BenchQuickBuildMetricsSink.kt index 1716b17b43..fda9f2e0dd 100644 --- a/app/src/debug/java/com/itsaky/androidide/quickbuild/BenchQuickBuildMetricsSink.kt +++ b/app/src/debug/java/org/appdevforall/codeonthego/quickbuild/BenchQuickBuildMetricsSink.kt @@ -1,4 +1,4 @@ -package com.itsaky.androidide.quickbuild +package org.appdevforall.codeonthego.quickbuild import org.appdevforall.cotg.quickbuild.domain.ChangedFiles import org.appdevforall.cotg.quickbuild.domain.classify.BuildRoute diff --git a/app/src/debug/java/com/itsaky/androidide/quickbuild/BenchStateRecorder.kt b/app/src/debug/java/org/appdevforall/codeonthego/quickbuild/BenchStateRecorder.kt similarity index 98% rename from app/src/debug/java/com/itsaky/androidide/quickbuild/BenchStateRecorder.kt rename to app/src/debug/java/org/appdevforall/codeonthego/quickbuild/BenchStateRecorder.kt index 6e6990ef2e..c771d29f5f 100644 --- a/app/src/debug/java/com/itsaky/androidide/quickbuild/BenchStateRecorder.kt +++ b/app/src/debug/java/org/appdevforall/codeonthego/quickbuild/BenchStateRecorder.kt @@ -1,4 +1,4 @@ -package com.itsaky.androidide.quickbuild +package org.appdevforall.codeonthego.quickbuild import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.StateFlow diff --git a/app/src/debug/java/com/itsaky/androidide/quickbuild/QuickBuildBenchActivity.kt b/app/src/debug/java/org/appdevforall/codeonthego/quickbuild/QuickBuildBenchActivity.kt similarity index 88% rename from app/src/debug/java/com/itsaky/androidide/quickbuild/QuickBuildBenchActivity.kt rename to app/src/debug/java/org/appdevforall/codeonthego/quickbuild/QuickBuildBenchActivity.kt index e5442ddf14..45f624959b 100644 --- a/app/src/debug/java/com/itsaky/androidide/quickbuild/QuickBuildBenchActivity.kt +++ b/app/src/debug/java/org/appdevforall/codeonthego/quickbuild/QuickBuildBenchActivity.kt @@ -1,15 +1,15 @@ -package com.itsaky.androidide.quickbuild +package org.appdevforall.codeonthego.quickbuild import android.app.Activity import android.content.Intent import android.os.Bundle -import com.itsaky.androidide.activities.editor.EditorActivityKt -import com.itsaky.androidide.models.EditorIntentExtras -import com.itsaky.androidide.preferences.internal.GeneralPreferences -import com.itsaky.androidide.projects.ProjectManagerImpl -import com.itsaky.androidide.utils.Environment -import com.itsaky.androidide.utils.FeatureFlags import kotlinx.coroutines.runBlocking +import org.appdevforall.codeonthego.activities.editor.EditorActivityKt +import org.appdevforall.codeonthego.models.EditorIntentExtras +import org.appdevforall.codeonthego.preferences.internal.GeneralPreferences +import org.appdevforall.codeonthego.projects.ProjectManagerImpl +import org.appdevforall.codeonthego.utils.Environment +import org.appdevforall.codeonthego.utils.FeatureFlags import org.appdevforall.cotg.quickbuild.service.session.QuickBuildSessionManager import org.koin.core.context.GlobalContext import org.slf4j.LoggerFactory @@ -17,7 +17,7 @@ import java.io.File /** * adb-triggerable "open project + start Quick Build", for the ADFA-4128 benchmark harness - * only. Opens a project the same way [com.itsaky.androidide.activities.MainActivity] does + * only. Opens a project the same way [org.appdevforall.codeonthego.activities.MainActivity] does * and arms [QuickBuildBenchAutostart] so the editor fires the first Quick Build tap the * moment the project initializes - replacing the human's lightning-bolt tap in an * unattended edit->hot-reload measurement. @@ -133,8 +133,8 @@ class QuickBuildBenchActivity : Activity() { } companion object { - const val ACTION_BENCH_OPEN_PROJECT = "com.itsaky.androidide.quickbuild.action.BENCH_OPEN_PROJECT" - const val EXTRA_PROJECT_PATH = "com.itsaky.androidide.quickbuild.extra.PROJECT_PATH" + const val ACTION_BENCH_OPEN_PROJECT = "org.appdevforall.codeonthego.quickbuild.action.BENCH_OPEN_PROJECT" + const val EXTRA_PROJECT_PATH = "org.appdevforall.codeonthego.quickbuild.extra.PROJECT_PATH" /** * Which build the autostart fires once the project initializes: @@ -142,7 +142,7 @@ class QuickBuildBenchActivity : Activity() { * [QuickBuildBenchAutostart.MODE_STANDARD] (standard Run, for the cold * standard-vs-proxy app build comparison). Unknown values reject the intent. */ - const val EXTRA_MODE = "com.itsaky.androidide.quickbuild.extra.MODE" + const val EXTRA_MODE = "org.appdevforall.codeonthego.quickbuild.extra.MODE" private val log = LoggerFactory.getLogger("QB-BenchActivity") } diff --git a/app/src/debug/java/com/itsaky/androidide/quickbuild/QuickBuildBenchAutostart.kt b/app/src/debug/java/org/appdevforall/codeonthego/quickbuild/QuickBuildBenchAutostart.kt similarity index 93% rename from app/src/debug/java/com/itsaky/androidide/quickbuild/QuickBuildBenchAutostart.kt rename to app/src/debug/java/org/appdevforall/codeonthego/quickbuild/QuickBuildBenchAutostart.kt index 9e43a76a14..67b045806f 100644 --- a/app/src/debug/java/com/itsaky/androidide/quickbuild/QuickBuildBenchAutostart.kt +++ b/app/src/debug/java/org/appdevforall/codeonthego/quickbuild/QuickBuildBenchAutostart.kt @@ -1,9 +1,9 @@ -package com.itsaky.androidide.quickbuild +package org.appdevforall.codeonthego.quickbuild /** * One-shot handoff from [QuickBuildBenchActivity] to the editor: the bench activity records * the project it is about to open (and which build the harness wants), and - * [com.itsaky.androidide.activities.editor.ProjectHandlerActivity] claims it exactly once - + * [org.appdevforall.codeonthego.activities.editor.ProjectHandlerActivity] claims it exactly once - * when that project finishes initializing - to fire the first build in place of the human's * tap: either the Quick Build lightning-bolt ([MODE_QUICK_BUILD]) or the standard Run * ([MODE_STANDARD], for the cold standard-build-vs-proxy-app-build comparison). diff --git a/app/src/debug/java/org/appdevforall/codeonthego/quickbuild/QuickBuildBenchHooks.kt b/app/src/debug/java/org/appdevforall/codeonthego/quickbuild/QuickBuildBenchHooks.kt new file mode 100644 index 0000000000..de667ac2c6 --- /dev/null +++ b/app/src/debug/java/org/appdevforall/codeonthego/quickbuild/QuickBuildBenchHooks.kt @@ -0,0 +1,141 @@ +package org.appdevforall.codeonthego.quickbuild + +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.flow.StateFlow +import org.appdevforall.codeonthego.utils.FeatureFlags +import org.appdevforall.cotg.quickbuild.domain.session.QuickBuildSessionState +import org.appdevforall.cotg.quickbuild.domain.telemetry.QuickBuildMetricsSink +import org.koin.core.context.GlobalContext +import org.slf4j.LoggerFactory +import java.io.File + +/** + * Every hook the ADFA-4128 benchmark harness needs from shipping code, in one place, in the + * debug source set. `src/release/` carries a no-op twin with the same signatures, so a + * release APK contains no benchmark code at all - same debug/release pair as + * [org.appdevforall.codeonthego.app.LeakCanaryConfig]. + * + * Every hook is additionally gated on [isEnabled] (the `CodeOnTheGo.qbbench` flag file), so + * a debug build with the flag absent behaves exactly like a release one. + */ +internal object QuickBuildBenchHooks { + /** + * Whether the benchmark interface is on at all. Callers check this before doing any work + * to build a hook's arguments (a canonical-path resolution, say); every hook re-checks it + * so an unguarded call is still inert. + */ + val isEnabled: Boolean + get() = FeatureFlags.isQuickBuildBenchEnabled + + /** + * Claims a pending autostart for [projectPath] (canonical), converting the harness's wire + * mode into the editor's [AutostartBuild]. One-shot: a claimed autostart is consumed. + */ + fun claimAutostart(projectPath: String): AutostartBuild { + if (!isEnabled) return AutostartBuild.NONE + return when (QuickBuildBenchAutostart.claim(projectPath)) { + QuickBuildBenchAutostart.MODE_QUICK_BUILD -> AutostartBuild.QUICK_BUILD + QuickBuildBenchAutostart.MODE_STANDARD -> AutostartBuild.STANDARD + else -> AutostartBuild.NONE + } + } + + /** + * Stamps the start of an autostarted standard build and arms the latch + * [standardBuildEnded] reads. + */ + fun standardBuildStarted( + projectPath: String, + modulePath: String, + variantName: String, + ) { + if (!isEnabled) return + standardBuildStartMs = System.currentTimeMillis() + events()?.append("standard_build_started") { + put("project", projectPath) + put("module", modulePath) + put("variant", variantName) + } + } + + /** + * Stamps the end of an autostarted standard build. [isTerminal] is false while the build + * is still running; [isSuccess] says whether the terminal state produced something + * installable. + * + * Returns true iff the caller must SUPPRESS the install this build state would normally + * trigger: the measurement ends at the build result, and an unattended run must not pop + * an install dialog. False whenever no autostarted build is in flight - which is always, + * in a release build - so a human's build installs as usual. + */ + fun standardBuildEnded( + isTerminal: Boolean, + isSuccess: Boolean, + ): Boolean { + val startMs = standardBuildStartMs ?: return false + if (!isTerminal) return false + standardBuildStartMs = null + events()?.append("standard_build_finished") { + put("isSuccess", isSuccess) + put("durationMs", System.currentTimeMillis() - startMs) + } + return true + } + + /** + * An extra metrics sink that mirrors every callback into the JSON-lines event log, or + * null when the bench flag is off. Fanned in alongside the shipping sinks. + */ + fun metricsSink(): QuickBuildMetricsSink? { + if (!isEnabled) return null + return events()?.let(::BenchQuickBuildMetricsSink) + } + + /** + * Mirrors session-state changes into the event log - a second, read-only collector on + * the session manager's existing stream, so the UI's own collector is untouched. + */ + fun attachStateRecorder(state: StateFlow) { + if (!isEnabled) return + val events = events() ?: return + BenchStateRecorder(events) + .attach(state, CoroutineScope(SupervisorJob() + Dispatchers.IO)) + } + + /** + * Whether the post-provisioning background warm compile runs. `CodeOnTheGo.qbnoseed` + * suppresses it so an A/B runs against the same installed build; inert unless the bench + * flag is on too, and absent entirely from a release build. + */ + fun warmCompileEnabled(): Boolean = !(isEnabled && FeatureFlags.isQuickBuildWarmCompileDisabled) + + /** + * Start time of an in-flight autostarted standard build, or null when none is running. + * Written on the project-init path, read on the build-state collector - hence volatile. + */ + @Volatile + private var standardBuildStartMs: Long? = null + + @Volatile + private var eventsFile: BenchEventsFile? = null + + /** + * The shared JSON-lines writer, created on first use so a debug build with the flag off + * never touches the filesystem. One instance per process: [BenchEventsFile] serializes + * its own writes, which only helps if every writer shares it. + */ + @Synchronized + private fun events(): BenchEventsFile? { + eventsFile?.let { return it } + return runCatching { + val paths = GlobalContext.get().get() + BenchEventsFile(File(paths.quickBuildHome, "bench-events.jsonl")) + }.onFailure { log.error("Bench events file unavailable", it) } + .getOrNull() + ?.also { eventsFile = it } + } + + private val log = LoggerFactory.getLogger("QB-BenchHooks") +} diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 7222fbdafc..6ba2a631dc 100755 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -5,7 +5,7 @@ tools:ignore="Instantiatable"> - + @@ -50,7 +50,7 @@ - + @@ -88,7 +88,7 @@ @@ -112,7 +112,7 @@ never root the real one, which is what makes excludeFromRecents mean what it says here. --> - + @@ -217,7 +217,7 @@ without an Activity recreation, so the same "stale until back-and-return" tradeoff is narrower here than on the View-based screen. --> - + @@ -317,8 +317,8 @@ android:name="firebase_data_collection_default_enabled" android:value="false" /> @@ -328,7 +328,7 @@ @@ -350,12 +350,12 @@ - + @@ -366,7 +366,7 @@ broadcasts to this receiver. --> - + + android:permission="org.appdevforall.codeonthego.permission.BIND_LOG_SERVICE"> - + . - */ - -package com.itsaky.androidide.actions - -import android.content.Context -import android.graphics.drawable.Drawable -import android.widget.EditText -import androidx.core.content.ContextCompat -import androidx.core.graphics.drawable.DrawableCompat -import com.itsaky.androidide.editor.ui.IDEEditor -import com.itsaky.androidide.resources.R -import com.itsaky.androidide.editor.adapters.IdeEditorAdapter - -/** @author Akash Yadav */ -abstract class BaseEditorAction : EditorActionItem { - - override var label: String = "" - override var visible: Boolean = true - override var enabled: Boolean = true - override var icon: Drawable? = null - override var requiresUIThread: Boolean = true // all editor actions must be executed on UI thread - override var location: ActionItem.Location = ActionItem.Location.EDITOR_TEXT_ACTIONS - - override fun prepare(data: ActionData) { - super.prepare(data) - - val textTarget = getTextTarget(data) - val ideEditor = data.get(IDEEditor::class.java) - - if (textTarget != null) { - visible = true - enabled = (textTarget as? MutableTextTarget)?.isEditable() ?: false - return - } - - if (ideEditor != null) { - visible = true - enabled = true - return - } - - visible = false - enabled = visible - } - - fun getTextTarget(data: ActionData): TextTarget? { - val mutable = data.get(MutableTextTarget::class.java) - if (mutable != null) return mutable - - val target = data.get(TextTarget::class.java) - if (target != null) return target - - val editor = data.get(IDEEditor::class.java) - if (editor != null) { - return IdeEditorAdapter(editor) - } - - val view = data.get(EditText::class.java) - if (view != null) { - return EditTextAdapter(view) - } - - return null - } - - fun getEditor(data: ActionData): IDEEditor? { - return data.get(IDEEditor::class.java) - } - - fun getContext(data: ActionData): Context? { - return getTextTarget(data)?.getAnchorView()?.context - } - - fun tintDrawable(context: Context, drawable: Drawable): Drawable { - val wrapped = DrawableCompat.wrap(drawable).mutate() - val solidColor = ContextCompat.getColor(context, R.color.primaryIconColor) - - wrapped.alpha = 255 - DrawableCompat.setTint(wrapped, solidColor) - return wrapped - } -} diff --git a/app/src/main/java/com/itsaky/androidide/actions/EditorActivityAction.kt b/app/src/main/java/com/itsaky/androidide/actions/EditorActivityAction.kt deleted file mode 100644 index 6708527f7a..0000000000 --- a/app/src/main/java/com/itsaky/androidide/actions/EditorActivityAction.kt +++ /dev/null @@ -1,64 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.actions - -import android.content.Context -import android.graphics.drawable.Drawable -import com.itsaky.androidide.activities.editor.EditorHandlerActivity -import com.itsaky.androidide.tasks.cancelIfActive -import kotlinx.coroutines.CoroutineName -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.plus - -/** @author Akash Yadav */ -abstract class EditorActivityAction : ActionItem { - - override var enabled: Boolean = true - override var visible: Boolean = true - override var icon: Drawable? = null - override var label: String = "" - override var location: ActionItem.Location = ActionItem.Location.EDITOR_TOOLBAR - - override var requiresUIThread: Boolean = false - - protected val actionScope = CoroutineScope(Dispatchers.Default) + - CoroutineName("${javaClass.simpleName}Scope") - - override fun prepare(data: ActionData) { - super.prepare(data) - if (!data.hasRequiredData(Context::class.java)) { - markInvisible() - return - } - } - - fun ActionData.getActivity(): EditorHandlerActivity? { - return this[Context::class.java] as? EditorHandlerActivity - } - - fun ActionData.requireActivity(): EditorHandlerActivity { - return getActivity()!! - } - - override fun destroy() { - super.destroy() - actionScope.cancelIfActive("Action is being destroyed") - } - -} diff --git a/app/src/main/java/com/itsaky/androidide/actions/EditorRelatedAction.kt b/app/src/main/java/com/itsaky/androidide/actions/EditorRelatedAction.kt deleted file mode 100644 index 3e4a1400cb..0000000000 --- a/app/src/main/java/com/itsaky/androidide/actions/EditorRelatedAction.kt +++ /dev/null @@ -1,49 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.actions - -import com.itsaky.androidide.editor.ui.IDEEditor -import com.itsaky.androidide.ui.CodeEditorView - -/** @author Akash Yadav */ -abstract class EditorRelatedAction : EditorActivityAction(), EditorActionItem { - - override var requiresUIThread: Boolean = true - - override fun prepare(data: ActionData) { - super.prepare(data) - super.prepare(data) - val editor = - data.getEditor() - ?: run { - visible = false - enabled = false - return - } - - val file = editor.file - - visible = file != null - enabled = visible - } - - fun ActionData.getEditor(): IDEEditor? = get(IDEEditor::class.java) - - fun ActionData.getEditorView(): CodeEditorView? = get(CodeEditorView::class.java) - -} diff --git a/app/src/main/java/com/itsaky/androidide/actions/PluginActionItem.kt b/app/src/main/java/com/itsaky/androidide/actions/PluginActionItem.kt deleted file mode 100644 index c62642eb08..0000000000 --- a/app/src/main/java/com/itsaky/androidide/actions/PluginActionItem.kt +++ /dev/null @@ -1,58 +0,0 @@ - - -package com.itsaky.androidide.actions - -import android.content.Context -import android.graphics.drawable.Drawable -import androidx.core.content.ContextCompat -import com.itsaky.androidide.plugins.extensions.MenuItem -import com.itsaky.androidide.plugins.manager.pluginCategory -import com.itsaky.androidide.plugins.manager.pluginTooltipTag -import com.itsaky.androidide.plugins.manager.ui.PluginDrawableResolver - - -class PluginActionItem( - context: Context, - private val menuItem: MenuItem, - override val order: Int, - val pluginId: String -) : EditorActivityAction() { - - override val id: String = "plugin.${menuItem.id}" - - init { - label = menuItem.title - val iconResId = menuItem.icon - icon = if (iconResId != null) { - PluginDrawableResolver.resolve(iconResId, pluginId, context) - ?: ContextCompat.getDrawable(context, R.drawable.ic_package) - } else { - ContextCompat.getDrawable(context, R.drawable.ic_package) - } - location = ActionItem.Location.EDITOR_TOOLBAR - requiresUIThread = true - } - - override fun prepare(data: ActionData) { - super.prepare(data) - enabled = menuItem.isEnabledProvider?.invoke() ?: menuItem.isEnabled - visible = menuItem.isVisibleProvider?.invoke() ?: menuItem.isVisible - } - - override fun retrieveTooltipTag(isReadOnlyContext: Boolean): String = - menuItem.tooltipTag ?: pluginTooltipTag(pluginId, menuItem.id) - - override fun retrieveTooltipCategory(): String = pluginCategory(pluginId) - - override suspend fun execAction(data: ActionData): Any { - return try { - // Execute the plugin's action callback on UI thread - menuItem.action.invoke() - true - } catch (e: Exception) { - // Log error but don't crash the app - android.util.Log.e("PluginActionItem", "Error executing plugin action '${menuItem.id}': ${e.message}", e) - false - } - } -} diff --git a/app/src/main/java/com/itsaky/androidide/actions/PluginSidebarActionItem.kt b/app/src/main/java/com/itsaky/androidide/actions/PluginSidebarActionItem.kt deleted file mode 100644 index 8377105f56..0000000000 --- a/app/src/main/java/com/itsaky/androidide/actions/PluginSidebarActionItem.kt +++ /dev/null @@ -1,73 +0,0 @@ - - -package com.itsaky.androidide.actions - -import android.content.Context -import android.graphics.drawable.Drawable -import androidx.core.content.ContextCompat -import androidx.fragment.app.Fragment -import com.itsaky.androidide.plugins.extensions.NavigationItem -import com.itsaky.androidide.plugins.manager.pluginCategory -import com.itsaky.androidide.plugins.manager.pluginTooltipTag -import com.itsaky.androidide.plugins.manager.ui.PluginDrawableResolver -import com.itsaky.androidide.R -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.withContext -import kotlin.reflect.KClass - -class PluginSidebarActionItem( - private val context: Context, - private val navigationItem: NavigationItem, - baseOrder: Int, - val pluginId: String -) : SidebarActionItem { - - override val id: String = "plugin_sidebar_${navigationItem.id}" - override var enabled: Boolean = navigationItem.isEnabled - override var visible: Boolean = navigationItem.isVisible - override var label: String = navigationItem.title - override var order: Int = navigationItem.order + 1000 + baseOrder - override var requiresUIThread: Boolean = true - override var location: ActionItem.Location = ActionItem.Location.EDITOR_SIDEBAR - - override var icon: Drawable? = null - - override val fragmentClass: KClass? = null - - init { - val iconResId = navigationItem.icon - icon = if (iconResId != null) { - PluginDrawableResolver.resolve(iconResId, pluginId, context) - ?: ContextCompat.getDrawable(context, R.drawable.ic_extension) - } else { - ContextCompat.getDrawable(context, R.drawable.ic_extension) - } - } - - override fun retrieveTooltipTag(isReadOnlyContext: Boolean): String = - navigationItem.tooltipTag ?: pluginTooltipTag(pluginId, navigationItem.id) - - override fun retrieveTooltipCategory(): String = pluginCategory(pluginId) - - override suspend fun execAction(data: ActionData): Boolean { - return try { - // Plugin actions might need UI thread access for dialogs/UI operations - if (requiresUIThread) { - withContext(Dispatchers.Main) { - navigationItem.action.invoke() - } - } else { - navigationItem.action.invoke() - } - true - } catch (e: Exception) { - false - } - } - - override fun prepare(data: ActionData) { - super.prepare(data) - visible = navigationItem.isVisible - enabled = navigationItem.isEnabled - } -} \ No newline at end of file diff --git a/app/src/main/java/com/itsaky/androidide/actions/PluginToolbarActionItem.kt b/app/src/main/java/com/itsaky/androidide/actions/PluginToolbarActionItem.kt deleted file mode 100644 index feb651b915..0000000000 --- a/app/src/main/java/com/itsaky/androidide/actions/PluginToolbarActionItem.kt +++ /dev/null @@ -1,95 +0,0 @@ -package com.itsaky.androidide.actions - -import android.content.Context -import android.util.Log -import android.view.MenuItem -import androidx.core.content.ContextCompat -import com.itsaky.androidide.R -import com.itsaky.androidide.plugins.extensions.ShowAsAction -import com.itsaky.androidide.plugins.extensions.ToolbarAction -import com.itsaky.androidide.plugins.manager.pluginCategory -import com.itsaky.androidide.plugins.manager.pluginTooltipTag -import com.itsaky.androidide.plugins.manager.ui.PluginDrawableResolver - -/** - * Adapts a plugin-contributed [ToolbarAction] (from `UIExtension.getToolbarActions()`) - * into an editor-toolbar [ActionItem]. - * - * Unlike [PluginActionItem] (which wraps `getMainMenuItems()`), this is the dedicated - * path for toolbar icons: it carries the action's own [ToolbarAction.order] so a plugin - * can position its icon among the built-in actions, and it opts into [honorVisibility] - * so the toolbar fully removes it (instead of greying it) when not applicable. - */ -class PluginToolbarActionItem( - private val context: Context, - private val toolbarAction: ToolbarAction, - val pluginId: String -) : EditorActivityAction() { - - override val id: String = "plugin.toolbar.${toolbarAction.id}" - - override val order: Int = toolbarAction.order - - override val honorVisibility: Boolean get() = true - - init { - label = toolbarAction.title - val iconResId = toolbarAction.icon - icon = if (iconResId != null) { - PluginDrawableResolver.resolve(iconResId, pluginId, context) - ?: ContextCompat.getDrawable(context, R.drawable.ic_package) - } else { - ContextCompat.getDrawable(context, R.drawable.ic_package) - } - location = ActionItem.Location.EDITOR_TOOLBAR - requiresUIThread = true - } - - override fun prepare(data: ActionData) { - super.prepare(data) - if (!visible) { - // EditorActivityAction.prepare() hides the action when the editor context is - // missing; respect that and skip the plugin providers. - return - } - runCatching { - enabled = toolbarAction.isEnabledProvider?.invoke() ?: toolbarAction.isEnabled - visible = toolbarAction.isVisibleProvider?.invoke() ?: toolbarAction.isVisible - // Re-resolve the icon on every rebuild when the plugin drives it dynamically. - // When iconProvider is null the icon stays as resolved in init (static behavior). - if (visible) { - toolbarAction.iconProvider?.invoke()?.let { resId -> - PluginDrawableResolver.resolve(resId, pluginId, context)?.let { icon = it } - } - } - }.onFailure { e -> - // A throwing/disposed plugin must never keep a stale icon on the toolbar. - Log.w("PluginToolbarActionItem", "prepare failed for '${toolbarAction.id}'", e) - enabled = false - visible = false - } - } - - override fun getShowAsActionFlags(data: ActionData): Int = when (toolbarAction.showAsAction) { - ShowAsAction.ALWAYS -> MenuItem.SHOW_AS_ACTION_ALWAYS - ShowAsAction.IF_ROOM -> MenuItem.SHOW_AS_ACTION_IF_ROOM - ShowAsAction.NEVER -> MenuItem.SHOW_AS_ACTION_NEVER - ShowAsAction.WITH_TEXT -> MenuItem.SHOW_AS_ACTION_WITH_TEXT - ShowAsAction.COLLAPSE_ACTION_VIEW -> MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW - } - - override fun retrieveTooltipTag(isReadOnlyContext: Boolean): String = - pluginTooltipTag(pluginId, toolbarAction.id) - - override fun retrieveTooltipCategory(): String = pluginCategory(pluginId) - - override suspend fun execAction(data: ActionData): Any { - return try { - toolbarAction.action.invoke() - true - } catch (e: Exception) { - Log.e("PluginToolbarActionItem", "Error executing toolbar action '${toolbarAction.id}'", e) - false - } - } -} diff --git a/app/src/main/java/com/itsaky/androidide/actions/build/DebugAction.kt b/app/src/main/java/com/itsaky/androidide/actions/build/DebugAction.kt deleted file mode 100644 index a76431c2e8..0000000000 --- a/app/src/main/java/com/itsaky/androidide/actions/build/DebugAction.kt +++ /dev/null @@ -1,113 +0,0 @@ -package com.itsaky.androidide.actions.build - -import android.content.Context -import com.itsaky.androidide.actions.ActionData -import com.itsaky.androidide.actions.canShowPairingNotification -import com.itsaky.androidide.actions.handleMissingOverlayPermission -import com.itsaky.androidide.actions.showDebuggerNotReadyMessage -import com.itsaky.androidide.actions.showNotificationPermissionDialog -import com.itsaky.androidide.actions.showPairingDialog -import com.itsaky.androidide.idetooltips.TooltipTag -import com.itsaky.androidide.lsp.api.ILanguageServerRegistry -import com.itsaky.androidide.lsp.java.JavaLanguageServer -import com.itsaky.androidide.lsp.java.debug.JdwpOptions -import com.itsaky.androidide.projects.IProjectManager -import com.itsaky.androidide.projects.isPluginProject -import com.itsaky.androidide.resources.R -import com.itsaky.androidide.utils.PermissionsHelper -import com.itsaky.androidide.utils.flashError -import com.itsaky.androidide.utils.isAtLeastR -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.withContext -import rikka.shizuku.Shizuku - -/** - * Run the application to - * - * @author Akash Yadav - */ -class DebugAction( - context: Context, - override val order: Int, -) : AbstractRunAction( - context = context, - labelRes = R.string.action_start_debugger, - iconRes = R.drawable.ic_db_startdebugger, - ) { - override val id = ID - - override fun retrieveTooltipTag(isReadOnlyContext: Boolean) = TooltipTag.EDITOR_TOOLBAR_DEBUG - - companion object { - const val ID = "ide.editor.build.debug" - } - - override fun prepare(data: ActionData) { - super.prepare(data) - - if (IProjectManager.getInstance().isPluginProject()) { - visible = false - return - } - - val buildIsInProgress = data.getActivity().isBuildInProgress() - - // should be enabled if Shizuku is not running - // the user should not be required to wait for the build to complete - // in order to start the ADB pairing process - @Suppress("SimplifyBooleanWithConstants", "KotlinConstantConditions") - enabled = !(Shizuku.pingBinder()) || (JdwpOptions.JDWP_ENABLED && !buildIsInProgress) - } - - override suspend fun preExec(data: ActionData): Boolean { - val activity = data.requireActivity() - if (!isAtLeastR()) { - activity.flashError(R.string.err_debugger_requires_a11) - return false - } - - val javaLsp = - ILanguageServerRegistry.default - .getServer(JavaLanguageServer.SERVER_ID) - if (javaLsp?.debugAdapter?.isReady != true - ) { - withContext(Dispatchers.Main.immediate) { - showDebuggerNotReadyMessage(activity) - } - return false - } - - if (!canShowPairingNotification(activity)) { - withContext(Dispatchers.Main.immediate) { - showNotificationPermissionDialog(activity, onError = { - log.error("Failed to open notification settings", it) - }) - } - return false - } - - val overlayState = - withContext(Dispatchers.Main.immediate) { - PermissionsHelper.getOverlayPermissionState(activity) - } - - if (overlayState != PermissionsHelper.OverlayPermissionState.GRANTED) { - handleMissingOverlayPermission(activity, overlayState, onError = { - log.error("Failed to launch overlay settings", it) - }) - return false - } - - if (!Shizuku.pingBinder()) { - log.error("Shizuku service is not running") - withContext(Dispatchers.Main.immediate) { - showPairingDialog(activity, log = log, onError = { - log.error("Failed to open developer options", it) - }) - } - return false - } - - return Shizuku.pingBinder() - } -} diff --git a/app/src/main/java/com/itsaky/androidide/actions/build/QuickRunAction.kt b/app/src/main/java/com/itsaky/androidide/actions/build/QuickRunAction.kt deleted file mode 100644 index 29ead3e45c..0000000000 --- a/app/src/main/java/com/itsaky/androidide/actions/build/QuickRunAction.kt +++ /dev/null @@ -1,70 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.actions.build - -import android.content.Context -import android.graphics.ColorFilter -import android.graphics.PorterDuff -import android.graphics.PorterDuffColorFilter -import com.itsaky.androidide.actions.ActionData -import com.itsaky.androidide.actions.getContext -import com.itsaky.androidide.activities.editor.EditorHandlerActivity -import com.itsaky.androidide.idetooltips.TooltipTag -import com.itsaky.androidide.projects.api.AndroidModule -import com.itsaky.androidide.projects.builder.BuildService -import com.itsaky.androidide.resources.R -import com.itsaky.androidide.tooling.api.messages.TaskExecutionMessage -import com.itsaky.androidide.tooling.api.models.BasicAndroidVariantMetadata -import com.itsaky.androidide.utils.resolveAttr - -/** - * The 'Quick Run' and 'Cancel build' action in the editor activity. - * - * If a build is in progress, executing this action cancels the build. Otherwise, the selected - * build variant is built and installed to the device. - * - * @author Akash Yadav - */ -class QuickRunAction(context: Context, override val order: Int) : - AbstractRunAction( - context = context, - labelRes = R.string.quick_run_debug, - iconRes = R.drawable.ic_run_outline - ) { - - override val id: String = ID - - companion object { - const val ID = "ide.editor.build.quickRun" - } - - override fun retrieveTooltipTag(isReadOnlyContext: Boolean): String = - TooltipTag.EDITOR_TOOLBAR_QUICK_RUN - - override fun createColorFilter(data: ActionData): ColorFilter? { - return data.getContext()?.let { - PorterDuffColorFilter( - it.resolveAttr( - if (data.getActivity().isBuildInProgress()) - R.attr.colorError - else R.attr.colorSuccess - ), PorterDuff.Mode.SRC_ATOP - ) - } - } -} diff --git a/app/src/main/java/com/itsaky/androidide/actions/debug/AbstractDebuggerAction.kt b/app/src/main/java/com/itsaky/androidide/actions/debug/AbstractDebuggerAction.kt deleted file mode 100644 index 58ad2e29ab..0000000000 --- a/app/src/main/java/com/itsaky/androidide/actions/debug/AbstractDebuggerAction.kt +++ /dev/null @@ -1,37 +0,0 @@ -package com.itsaky.androidide.actions.debug - -import android.graphics.drawable.Drawable -import androidx.annotation.DrawableRes -import androidx.core.content.ContextCompat -import com.itsaky.androidide.actions.ActionData -import com.itsaky.androidide.actions.ActionItem -import com.itsaky.androidide.actions.requireContext -import com.itsaky.androidide.lsp.IDEDebugClientImpl - -/** - * @author Akash Yadav - */ -abstract class AbstractDebuggerAction( - @DrawableRes private val iconRes: Int -) : ActionItem { - - // debugger actions must always be executed in a background thread - override var requiresUIThread = false - override var location = ActionItem.Location.DEBUGGER_ACTIONS - - override var visible = true - override var enabled = true - override var icon: Drawable? = null - - protected val debugClient: IDEDebugClientImpl? - get() = IDEDebugClientImpl.getInstance() - - protected open fun checkEnabled(data: ActionData): Boolean = debugClient?.isVmConnected() == true - - override fun prepare(data: ActionData) { - super.prepare(data) - - icon = ContextCompat.getDrawable(data.requireContext(), iconRes) - enabled = checkEnabled(data) - } -} diff --git a/app/src/main/java/com/itsaky/androidide/actions/debug/AbstractStepAction.kt b/app/src/main/java/com/itsaky/androidide/actions/debug/AbstractStepAction.kt deleted file mode 100644 index 5fd6d0e757..0000000000 --- a/app/src/main/java/com/itsaky/androidide/actions/debug/AbstractStepAction.kt +++ /dev/null @@ -1,15 +0,0 @@ -package com.itsaky.androidide.actions.debug - -import androidx.annotation.DrawableRes -import com.itsaky.androidide.actions.ActionData -import com.itsaky.androidide.viewmodel.DebuggerConnectionState - -abstract class AbstractStepAction( - @DrawableRes iconRes: Int -): AbstractDebuggerAction(iconRes) { - - override fun checkEnabled(data: ActionData): Boolean { - val client = debugClient ?: return false - return client.connectionState >= DebuggerConnectionState.AWAITING_BREAKPOINT - } -} diff --git a/app/src/main/java/com/itsaky/androidide/actions/debug/KillVmAction.kt b/app/src/main/java/com/itsaky/androidide/actions/debug/KillVmAction.kt deleted file mode 100644 index 28c995dc78..0000000000 --- a/app/src/main/java/com/itsaky/androidide/actions/debug/KillVmAction.kt +++ /dev/null @@ -1,22 +0,0 @@ -package com.itsaky.androidide.actions.debug - -import android.content.Context -import com.itsaky.androidide.R -import com.itsaky.androidide.actions.ActionData -import com.itsaky.androidide.idetooltips.TooltipTag - -/** - * @author Akash Yadav - */ -class KillVmAction( - context: Context -) : AbstractDebuggerAction(R.drawable.ic_stop) { - override val id = "ide.debug.stop-vm" - override var label = context.getString(R.string.debugger_kill) - override val order = 4 - override var tooltipTag = TooltipTag.DEBUGGER_ACTION_KILL - - override suspend fun execAction(data: ActionData) { - debugClient?.killVm() - } -} diff --git a/app/src/main/java/com/itsaky/androidide/actions/debug/RestartVmAction.kt b/app/src/main/java/com/itsaky/androidide/actions/debug/RestartVmAction.kt deleted file mode 100644 index 3760db5e05..0000000000 --- a/app/src/main/java/com/itsaky/androidide/actions/debug/RestartVmAction.kt +++ /dev/null @@ -1,52 +0,0 @@ -package com.itsaky.androidide.actions.debug - -import android.content.Context -import com.itsaky.androidide.R -import com.itsaky.androidide.actions.ActionData -import com.itsaky.androidide.actions.requireContext -import com.itsaky.androidide.idetooltips.TooltipTag -import com.itsaky.androidide.lsp.IDEDebugClientImpl -import com.itsaky.androidide.utils.IntentUtils -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.delay -import kotlinx.coroutines.withContext -import kotlin.time.Duration.Companion.seconds - -/** - * @author Akash Yadav - */ -class RestartVmAction( - context: Context, -) : AbstractDebuggerAction(R.drawable.ic_restart) { - override val id = "ide.debug.restart-vm" - override var label = context.getString(R.string.debugger_restart) - override val order = 5 - override var tooltipTag = TooltipTag.DEBUGGER_ACTION_RESTART - - companion object { - val RESTART_DELAY = 1.seconds - } - - override suspend fun execAction(data: ActionData) { - val context = data.requireContext() - - val client = IDEDebugClientImpl.getInstance() ?: return - - // kill the current VM - client.killVm() - - // wait for some time - delay(RESTART_DELAY) - - // then launch the debugee again - IDEDebugClientImpl.getInstance()?.let { safeClient -> - withContext(Dispatchers.Main.immediate) { - IntentUtils.launchApp( - context = context, - packageName = safeClient.debugeePackage, - debug = true, - ) - } - } - } -} diff --git a/app/src/main/java/com/itsaky/androidide/actions/debug/StepIntoAction.kt b/app/src/main/java/com/itsaky/androidide/actions/debug/StepIntoAction.kt deleted file mode 100644 index 6c31f8271d..0000000000 --- a/app/src/main/java/com/itsaky/androidide/actions/debug/StepIntoAction.kt +++ /dev/null @@ -1,22 +0,0 @@ -package com.itsaky.androidide.actions.debug - -import android.content.Context -import com.itsaky.androidide.R -import com.itsaky.androidide.actions.ActionData -import com.itsaky.androidide.idetooltips.TooltipTag - -/** - * @author Akash Yadav - */ -class StepIntoAction( - context: Context -) : AbstractStepAction(R.drawable.ic_step_into) { - override val id = "ide.debug.step-into" - override var label = context.getString(R.string.debugger_step_into) - override val order = 2 - override var tooltipTag = TooltipTag.DEBUGGER_ACTION_STEP_INTO - - override suspend fun execAction(data: ActionData) { - debugClient?.stepInto() - } -} diff --git a/app/src/main/java/com/itsaky/androidide/actions/debug/StepOutAction.kt b/app/src/main/java/com/itsaky/androidide/actions/debug/StepOutAction.kt deleted file mode 100644 index 823af23d89..0000000000 --- a/app/src/main/java/com/itsaky/androidide/actions/debug/StepOutAction.kt +++ /dev/null @@ -1,22 +0,0 @@ -package com.itsaky.androidide.actions.debug - -import android.content.Context -import com.itsaky.androidide.R -import com.itsaky.androidide.actions.ActionData -import com.itsaky.androidide.idetooltips.TooltipTag - -/** - * @author Akash Yadav - */ -class StepOutAction( - context: Context -) : AbstractStepAction(R.drawable.ic_step_out) { - override val id = "ide.debug.step-out" - override var label = context.getString(R.string.debugger_step_out) - override val order = 3 - override var tooltipTag = TooltipTag.DEBUGGER_ACTION_STEP_OUT - - override suspend fun execAction(data: ActionData) { - debugClient?.stepOut() - } -} diff --git a/app/src/main/java/com/itsaky/androidide/actions/debug/StepOverAction.kt b/app/src/main/java/com/itsaky/androidide/actions/debug/StepOverAction.kt deleted file mode 100644 index c9957b255d..0000000000 --- a/app/src/main/java/com/itsaky/androidide/actions/debug/StepOverAction.kt +++ /dev/null @@ -1,22 +0,0 @@ -package com.itsaky.androidide.actions.debug - -import android.content.Context -import com.itsaky.androidide.R -import com.itsaky.androidide.actions.ActionData -import com.itsaky.androidide.idetooltips.TooltipTag - -/** - * @author Akash Yadav - */ -class StepOverAction( - context: Context -) : AbstractStepAction(R.drawable.ic_step_over) { - override val id = "ide.debug.step-over" - override var label = context.getString(R.string.debugger_step_over) - override val order = 1 - override var tooltipTag = TooltipTag.DEBUGGER_ACTION_STEP_OVER - - override suspend fun execAction(data: ActionData) { - debugClient?.stepOver() - } -} diff --git a/app/src/main/java/com/itsaky/androidide/actions/debug/SuspendResumeVmAction.kt b/app/src/main/java/com/itsaky/androidide/actions/debug/SuspendResumeVmAction.kt deleted file mode 100644 index e76bf508ea..0000000000 --- a/app/src/main/java/com/itsaky/androidide/actions/debug/SuspendResumeVmAction.kt +++ /dev/null @@ -1,43 +0,0 @@ -package com.itsaky.androidide.actions.debug - -import android.content.Context -import androidx.core.content.ContextCompat -import com.itsaky.androidide.R -import com.itsaky.androidide.actions.ActionData -import com.itsaky.androidide.actions.requireContext -import com.itsaky.androidide.idetooltips.TooltipTag - -/** - * @author Akash Yadav - */ -class SuspendResumeVmAction( - context: Context -) : AbstractDebuggerAction(R.drawable.ic_pause) { - - override val id = "ide.debug.suspend-resume" - override var label = context.getString(R.string.debugger_suspend) - override val order = 0 - override var tooltipTag = TooltipTag.DEBUGGER_ACTION_PAUSE_RESUME - - override fun prepare(data: ActionData) { - super.prepare(data) - val context = data.requireContext() - val isSuspended = debugClient?.isVmSuspended() == true - if (isSuspended) { - label = context.getString(R.string.debugger_resume) - icon = ContextCompat.getDrawable(context, R.drawable.ic_run) - } else { - label = context.getString(R.string.debugger_suspend) - icon = ContextCompat.getDrawable(context, R.drawable.ic_pause) - } - } - - override suspend fun execAction(data: ActionData) { - val client = debugClient ?: return - if (client.isVmSuspended()) { - client.resumeVm() - } else { - client.suspendVm() - } - } -} diff --git a/app/src/main/java/com/itsaky/androidide/actions/editor/CopyAction.kt b/app/src/main/java/com/itsaky/androidide/actions/editor/CopyAction.kt deleted file mode 100644 index c9696540ac..0000000000 --- a/app/src/main/java/com/itsaky/androidide/actions/editor/CopyAction.kt +++ /dev/null @@ -1,70 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.actions.editor - -import android.content.Context -import com.itsaky.androidide.actions.ActionData -import com.itsaky.androidide.actions.BaseEditorAction -import com.itsaky.androidide.idetooltips.TooltipTag -import com.itsaky.androidide.resources.R - -/** @author Akash Yadav */ -class CopyAction(context: Context, override val order: Int) : - BaseEditorAction() { - - init { - label = context.getString(R.string.copy) - - val arr = context.obtainStyledAttributes(intArrayOf(android.R.attr.actionModeCopyDrawable)) - icon = arr.getDrawable(0)?.let { tintDrawable(context, it) } - arr.recycle() - } - - companion object { - const val ID = "ide.editor.code.text.copy" - } - - override val id: String = ID - - override fun prepare(data: ActionData) { - super.prepare(data) - - if (!visible) return - - val target = getTextTarget(data) - - visible = target != null - enabled = visible && target?.hasSelection() == true - } - - override suspend fun execAction(data: ActionData): Boolean { - val target = getTextTarget(data) ?: return false - if (!target.hasSelection()) return false - - target.copyText() - return true - } - - override fun retrieveTooltipTag(isAlternateContext: Boolean): String { - return if (isAlternateContext) { - TooltipTag.EDITOR_TOOLBAR_OUTPUT_COPY - } else { - TooltipTag.EDITOR_TOOLBAR_COPY - } - } -} diff --git a/app/src/main/java/com/itsaky/androidide/actions/editor/CutAction.kt b/app/src/main/java/com/itsaky/androidide/actions/editor/CutAction.kt deleted file mode 100644 index 1cac541504..0000000000 --- a/app/src/main/java/com/itsaky/androidide/actions/editor/CutAction.kt +++ /dev/null @@ -1,60 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.actions.editor - -import android.content.Context -import com.itsaky.androidide.actions.ActionData -import com.itsaky.androidide.actions.BaseEditorAction -import com.itsaky.androidide.actions.MutableTextTarget -import com.itsaky.androidide.idetooltips.TooltipTag -/** @author Akash Yadav */ -class CutAction(context: Context, override val order: Int) : BaseEditorAction() { - - init { - label = context.getString(android.R.string.cut) - - val arr = context.obtainStyledAttributes(intArrayOf(android.R.attr.actionModeCutDrawable)) - icon = arr.getDrawable(0)?.let { tintDrawable(context, it) } - arr.recycle() - } - - companion object { - const val ID = "ide.editor.code.text.cut" - } - - override fun prepare(data: ActionData) { - super.prepare(data) - - if (!visible) return - - val target = getTextTarget(data) - visible = (target is MutableTextTarget) && target.isEditable() - enabled = visible && target?.hasSelection() == true - } - - override val id: String = ID - override suspend fun execAction(data: ActionData): Boolean { - val target = getTextTarget(data) ?: return false - if (target is MutableTextTarget) { - target.cut() - return true - } - return false - } - override fun retrieveTooltipTag(isAlternateContext: Boolean) = TooltipTag.EDITOR_TOOLBAR_CUT -} diff --git a/app/src/main/java/com/itsaky/androidide/actions/editor/ExpandSelectionAction.kt b/app/src/main/java/com/itsaky/androidide/actions/editor/ExpandSelectionAction.kt deleted file mode 100644 index 2258745f81..0000000000 --- a/app/src/main/java/com/itsaky/androidide/actions/editor/ExpandSelectionAction.kt +++ /dev/null @@ -1,48 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.actions.editor - -import android.content.Context -import androidx.core.content.ContextCompat -import com.itsaky.androidide.actions.ActionData -import com.itsaky.androidide.actions.ActionItem -import com.itsaky.androidide.actions.EditorRelatedAction -import com.itsaky.androidide.idetooltips.TooltipTag -import com.itsaky.androidide.resources.R - -/** - * Expands the current selection using the language server set in editor. - * - * @author Akash Yadav - */ -class ExpandSelectionAction(context: Context, override val order: Int) : EditorRelatedAction() { - override val id: String = "ide.editor.code.actions.expandSelection" - override var location: ActionItem.Location = ActionItem.Location.EDITOR_TEXT_ACTIONS - - init { - label = context.getString(R.string.action_expand_selection) - icon = ContextCompat.getDrawable(context, R.drawable.ic_expand_selection) - } - - override suspend fun execAction(data: ActionData): Any { - return data.getEditor()?.expandSelection() ?: false - } - - override fun retrieveTooltipTag(isAlternateContext: Boolean) = - TooltipTag.EDITOR_TOOLBAR_EXPAND_SELECTION -} diff --git a/app/src/main/java/com/itsaky/androidide/actions/editor/LongSelectAction.kt b/app/src/main/java/com/itsaky/androidide/actions/editor/LongSelectAction.kt deleted file mode 100644 index 0cc1dadc62..0000000000 --- a/app/src/main/java/com/itsaky/androidide/actions/editor/LongSelectAction.kt +++ /dev/null @@ -1,53 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.actions.editor - -import android.content.Context -import androidx.core.content.ContextCompat -import com.itsaky.androidide.R -import com.itsaky.androidide.actions.ActionData -import com.itsaky.androidide.actions.ActionItem -import com.itsaky.androidide.actions.EditorRelatedAction -import com.itsaky.androidide.actions.markInvisible -import com.itsaky.androidide.idetooltips.TooltipTag -/** - * An action to long select text in the editor. - * - * @author Akash Yadav - */ -class LongSelectAction(context: Context, override val order: Int) : EditorRelatedAction() { - - override val id: String = "ide.editor.code.text.longSelect" - override var location: ActionItem.Location = ActionItem.Location.EDITOR_TEXT_ACTIONS - - init { - label = context.getString(R.string.title_begin_long_select) - icon = ContextCompat.getDrawable(context, R.drawable.editor_text_select_start) - } - - override fun prepare(data: ActionData) { - super.prepare(data) - data.getEditor() ?: markInvisible() - } - - override suspend fun execAction(data: ActionData): Any { - return data.getEditor()?.beginLongSelect() ?: false - } - override fun retrieveTooltipTag(isAlternateContext: Boolean) = - TooltipTag.EDITOR_TOOLBAR_LONG_SELECT -} \ No newline at end of file diff --git a/app/src/main/java/com/itsaky/androidide/actions/editor/PasteAction.kt b/app/src/main/java/com/itsaky/androidide/actions/editor/PasteAction.kt deleted file mode 100644 index b0e467aba8..0000000000 --- a/app/src/main/java/com/itsaky/androidide/actions/editor/PasteAction.kt +++ /dev/null @@ -1,62 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.actions.editor - -import android.content.Context -import com.itsaky.androidide.actions.ActionData -import com.itsaky.androidide.actions.BaseEditorAction -import com.itsaky.androidide.actions.MutableTextTarget -import com.itsaky.androidide.idetooltips.TooltipTag -/** @author Akash Yadav */ -class PasteAction(context: Context, override val order: Int) : BaseEditorAction() { - - init { - label = context.getString(android.R.string.paste) - - val arr = context.obtainStyledAttributes(intArrayOf(android.R.attr.actionModePasteDrawable)) - icon = arr.getDrawable(0)?.let { tintDrawable(context, it) } - arr.recycle() - } - - companion object { - const val ID = "ide.editor.code.text.paste" - } - - override val id: String = ID - - override fun prepare(data: ActionData) { - super.prepare(data) - - if (!visible) return - - val target = getTextTarget(data) - visible = (target is MutableTextTarget) && target.isEditable() - enabled = visible - } - - override suspend fun execAction(data: ActionData): Boolean { - val target = getTextTarget(data) ?: return false - if (target is MutableTextTarget) { - target.paste() - return true - } - return false - } - - override fun retrieveTooltipTag(isAlternateContext: Boolean) = TooltipTag.EDITOR_TOOLBAR_PASTE -} diff --git a/app/src/main/java/com/itsaky/androidide/actions/editor/SelectAllAction.kt b/app/src/main/java/com/itsaky/androidide/actions/editor/SelectAllAction.kt deleted file mode 100644 index 9ca37f8206..0000000000 --- a/app/src/main/java/com/itsaky/androidide/actions/editor/SelectAllAction.kt +++ /dev/null @@ -1,67 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.actions.editor - -import android.content.Context -import com.itsaky.androidide.actions.ActionData -import com.itsaky.androidide.actions.BaseEditorAction -import com.itsaky.androidide.idetooltips.TooltipTag -/** @author Akash Yadav */ -class SelectAllAction(context: Context, override val order: Int) : BaseEditorAction() { - - init { - label = context.getString(android.R.string.selectAll) - - val arr = context.obtainStyledAttributes(intArrayOf(android.R.attr.actionModeSelectAllDrawable)) - icon = arr.getDrawable(0)?.let { tintDrawable(context, it) } - arr.recycle() - } - - companion object { - const val ID = "ide.editor.code.text.selectAll" - } - - override val id: String = ID - - override fun prepare(data: ActionData) { - super.prepare(data) - - if (!visible) return - - val target = getTextTarget(data) - - visible = target != null - enabled = visible - } - - override suspend fun execAction(data: ActionData): Boolean { - val target = getTextTarget(data) ?: return false - target.selectAll() - return true - } - - override fun dismissOnAction() = false - - override fun retrieveTooltipTag(isAlternateContext: Boolean): String { - return if (isAlternateContext) { - TooltipTag.EDITOR_TOOLBAR_OUTPUT_SELECT_ALL - } else { - TooltipTag.EDITOR_TOOLBAR_SELECT_ALL - } - } -} diff --git a/app/src/main/java/com/itsaky/androidide/actions/etc/DisconnectLogSendersAction.kt b/app/src/main/java/com/itsaky/androidide/actions/etc/DisconnectLogSendersAction.kt deleted file mode 100644 index 4dc5b669ce..0000000000 --- a/app/src/main/java/com/itsaky/androidide/actions/etc/DisconnectLogSendersAction.kt +++ /dev/null @@ -1,66 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.actions.etc - -import android.content.Context -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.idetooltips.TooltipTag -import com.itsaky.androidide.services.log.lookupLogService - -/** - * An action to disconnect all connected LogSenders at once. - * - * @author Akash Yadav - */ -class DisconnectLogSendersAction(context: Context, override val order: Int) : EditorActivityAction() { - - override val id: String = "ide.editor.service.logreceiver.disconnectSenders" - override fun retrieveTooltipTag(isReadOnlyContext: Boolean): String = TooltipTag.EDITOR_TOOLBAR_LOG_SENDER - - init { - label = context.getString(R.string.title_disconnect_log_senders) - icon = ContextCompat.getDrawable(context, R.drawable.ic_logs_disconnect) - } - - override fun prepare(data: ActionData) { - super.prepare(data) - data.getActivity() ?: run { - markInvisible() - return - } - - val receiverService = lookupLogService() - if (receiverService == null) { - markInvisible() - return - } - } - - override suspend fun execAction(data: ActionData): Any { - val receiverService = lookupLogService() - receiverService?.disconnectAll() - - markInvisible() - data.getActivity()?.invalidateOptionsMenu() - return true - } -} \ No newline at end of file diff --git a/app/src/main/java/com/itsaky/androidide/actions/etc/FindAction.kt b/app/src/main/java/com/itsaky/androidide/actions/etc/FindAction.kt deleted file mode 100644 index 2e36efc844..0000000000 --- a/app/src/main/java/com/itsaky/androidide/actions/etc/FindAction.kt +++ /dev/null @@ -1,59 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.actions.etc - -import android.content.Context -import androidx.core.content.ContextCompat -import com.itsaky.androidide.actions.ActionData -import com.itsaky.androidide.actions.EditorActivityAction -import com.itsaky.androidide.actions.build.AbstractCancellableRunAction.Companion.isBuildInProgress -import com.itsaky.androidide.idetooltips.TooltipTag -import com.itsaky.androidide.resources.R - -/** @author Akash Yadav */ -class FindAction() : EditorActivityAction() { - - override var requiresUIThread: Boolean = true - override var order: Int = 0 - override fun retrieveTooltipTag(isReadOnlyContext: Boolean): String { - return TooltipTag.EDITOR_TOOLBAR_FIND - } - - constructor(context: Context, order: Int) : this() { - this.label = context.getString(R.string.menu_find) - this.icon = ContextCompat.getDrawable(context, R.drawable.ic_search) - this.order = order - } - - override val id: String = "ide.editor.find" - - override fun prepare(data: ActionData) { - super.prepare(data) - enabled = data.getActivity().isBuildInProgress().not() - } - - override suspend fun execAction(data: ActionData): Boolean { - val context = data.getActivity() ?: return false - val dialog = context.findActionDialog(data) - - return run { - dialog.show() - true - } - } -} diff --git a/app/src/main/java/com/itsaky/androidide/actions/etc/FindInFileAction.kt b/app/src/main/java/com/itsaky/androidide/actions/etc/FindInFileAction.kt deleted file mode 100644 index 4c953bd7ad..0000000000 --- a/app/src/main/java/com/itsaky/androidide/actions/etc/FindInFileAction.kt +++ /dev/null @@ -1,52 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.actions.etc - -import android.content.Context -import androidx.core.content.ContextCompat -import com.itsaky.androidide.actions.ActionData -import com.itsaky.androidide.actions.ActionItem -import com.itsaky.androidide.actions.EditorRelatedAction -import com.itsaky.androidide.idetooltips.TooltipTag -import com.itsaky.androidide.resources.R - -/** @author Akash Yadav */ -class FindInFileAction() : EditorRelatedAction() { - - override val id: String = ID - override var requiresUIThread: Boolean = true - override var location: ActionItem.Location = ActionItem.Location.EDITOR_FIND_ACTION_MENU - override var order: Int = 0 - override fun retrieveTooltipTag(isReadOnlyContext: Boolean): String = TooltipTag.EDITOR_TOOLBAR_FIND_IN_FILE - - companion object{ - const val ID = "ide.editor.find.inFile" - } - - constructor(context: Context, order: Int) : this() { - this.label = context.getString(R.string.menu_find_file) - this.icon = ContextCompat.getDrawable(context, R.drawable.ic_search_file) - this.order = order - } - - override suspend fun execAction(data: ActionData): Boolean { - val editor = data.getEditorView() ?: return false - editor.beginSearch() - return true - } -} diff --git a/app/src/main/java/com/itsaky/androidide/actions/etc/LaunchAppAction.kt b/app/src/main/java/com/itsaky/androidide/actions/etc/LaunchAppAction.kt deleted file mode 100644 index a84e904b60..0000000000 --- a/app/src/main/java/com/itsaky/androidide/actions/etc/LaunchAppAction.kt +++ /dev/null @@ -1,103 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.actions.etc - -import android.content.Context -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.idetooltips.TooltipTag.EDITOR_TOOLBAR_LAUNCH_APP -import com.itsaky.androidide.projects.IProjectManager -import com.itsaky.androidide.utils.IntentUtils -import com.itsaky.androidide.utils.flashError -import kotlinx.coroutines.launch -import org.slf4j.LoggerFactory - -/** - * 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( - context = activity, - packageName = applicationId, - logError = false - ) - } - } - } - - override fun getShowAsActionFlags(data: ActionData): Int { - // prefer showing this in the overflow menu - return MenuItem.SHOW_AS_ACTION_IF_ROOM - } -} \ No newline at end of file diff --git a/app/src/main/java/com/itsaky/androidide/actions/file/CloseAllFilesAction.kt b/app/src/main/java/com/itsaky/androidide/actions/file/CloseAllFilesAction.kt deleted file mode 100644 index c4bc1311f7..0000000000 --- a/app/src/main/java/com/itsaky/androidide/actions/file/CloseAllFilesAction.kt +++ /dev/null @@ -1,46 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.actions.file - -import android.content.Context -import androidx.core.content.ContextCompat -import com.itsaky.androidide.R -import com.itsaky.androidide.actions.ActionData -import com.itsaky.androidide.activities.editor.EditorHandlerActivity - -/** - * Closes all opened files. - * - * @author Akash Yadav - */ -class CloseAllFilesAction(context: Context, override val order: Int) : FileTabAction() { - - override val id: String = "ide.editor.fileTab.close.all" - - init { - label = context.getString(R.string.action_closeAll) - icon = ContextCompat.getDrawable(context, R.drawable.ic_close_all) - } - - override fun EditorHandlerActivity.doAction(data: ActionData): Boolean { - closeAll { - invalidateOptionsMenu() - } - return true - } -} diff --git a/app/src/main/java/com/itsaky/androidide/actions/file/CloseFileAction.kt b/app/src/main/java/com/itsaky/androidide/actions/file/CloseFileAction.kt deleted file mode 100644 index ba3e0e1a71..0000000000 --- a/app/src/main/java/com/itsaky/androidide/actions/file/CloseFileAction.kt +++ /dev/null @@ -1,48 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.actions.file - -import android.content.Context -import androidx.core.content.ContextCompat -import com.itsaky.androidide.R -import com.itsaky.androidide.actions.ActionData -import com.itsaky.androidide.activities.editor.EditorHandlerActivity - -/** - * Closes the current file. - * - * @author Akash Yadav - */ -class CloseFileAction(context: Context, override val order: Int) : FileTabAction() { - - override val id: String = ID - - companion object { - const val ID = "ide.editor.fileTab.close.current" - } - - init { - label = context.getString(R.string.action_closeThis) - icon = ContextCompat.getDrawable(context, R.drawable.ic_close_this) - } - - override fun EditorHandlerActivity.doAction(data: ActionData): Boolean { - data.getActivity()?.closeCurrentFile() - return true - } -} diff --git a/app/src/main/java/com/itsaky/androidide/actions/file/CloseOtherFilesAction.kt b/app/src/main/java/com/itsaky/androidide/actions/file/CloseOtherFilesAction.kt deleted file mode 100644 index cb0e5f8845..0000000000 --- a/app/src/main/java/com/itsaky/androidide/actions/file/CloseOtherFilesAction.kt +++ /dev/null @@ -1,44 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.actions.file - -import android.content.Context -import androidx.core.content.ContextCompat -import com.itsaky.androidide.R -import com.itsaky.androidide.actions.ActionData -import com.itsaky.androidide.activities.editor.EditorHandlerActivity - -/** - * Closes all opened files except the selected one. - * - * @author Akash Yadav - */ -class CloseOtherFilesAction(context: Context, override val order: Int) : FileTabAction() { - - override val id: String = "ide.editor.fileTab.close.others" - - init { - label = context.getString(R.string.action_closeOthers) - icon = ContextCompat.getDrawable(context, R.drawable.ic_close_others) - } - - override fun EditorHandlerActivity.doAction(data: ActionData): Boolean { - closeOthers() - return true - } -} diff --git a/app/src/main/java/com/itsaky/androidide/actions/file/FileTabAction.kt b/app/src/main/java/com/itsaky/androidide/actions/file/FileTabAction.kt deleted file mode 100644 index d863a082c9..0000000000 --- a/app/src/main/java/com/itsaky/androidide/actions/file/FileTabAction.kt +++ /dev/null @@ -1,61 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.actions.file - -import com.itsaky.androidide.actions.ActionData -import com.itsaky.androidide.actions.ActionItem.Location -import com.itsaky.androidide.actions.ActionItem.Location.EDITOR_FILE_TABS -import com.itsaky.androidide.actions.EditorActivityAction -import com.itsaky.androidide.actions.markInvisible -import com.itsaky.androidide.activities.editor.EditorHandlerActivity - -/** - * Action related to file tabs. Shown only when there is at least one file opened. - * - * @author Akash Yadav - */ -abstract class FileTabAction : EditorActivityAction() { - - override var location: Location = EDITOR_FILE_TABS - override var requiresUIThread: Boolean = true - - override fun prepare(data: ActionData) { - super.prepare(data) - - if (!visible) { - return - } - - val activity = - data.getActivity() - ?: run { - markInvisible() - return - } - - visible = activity.editorViewModel.getOpenedFiles().isNotEmpty() - enabled = visible - } - - override suspend fun execAction(data: ActionData): Any { - val activity = data.getActivity() ?: return false - return activity.doAction(data) - } - - abstract fun EditorHandlerActivity.doAction(data: ActionData): Boolean -} diff --git a/app/src/main/java/com/itsaky/androidide/actions/file/FormatCodeAction.kt b/app/src/main/java/com/itsaky/androidide/actions/file/FormatCodeAction.kt deleted file mode 100644 index e1875860fd..0000000000 --- a/app/src/main/java/com/itsaky/androidide/actions/file/FormatCodeAction.kt +++ /dev/null @@ -1,55 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.actions.file - -import android.content.Context -import androidx.core.content.ContextCompat -import com.itsaky.androidide.actions.ActionData -import com.itsaky.androidide.actions.ActionItem -import com.itsaky.androidide.actions.EditorRelatedAction -import com.itsaky.androidide.idetooltips.TooltipTag -import com.itsaky.androidide.resources.R - -/** - * Action that formats the code in the editor. - * - * @author Akash Yadav - */ -class FormatCodeAction(context: Context, override val order: Int) : EditorRelatedAction() { - override val id: String = "ide.editor.code.text.format" - override var location: ActionItem.Location = ActionItem.Location.EDITOR_TEXT_ACTIONS - override fun retrieveTooltipTag(isReadOnlyContext: Boolean) = - TooltipTag.EDITOR_TOOLBAR_FORMAT_CODE - - init { - label = context.getString(R.string.title_format_code) - icon = ContextCompat.getDrawable(context, R.drawable.ic_format_code) - } - - override suspend fun execAction(data: ActionData): Any { - val editor = data.getEditor()!! - val cursor = editor.text.cursor - - if (cursor.isSelected) { - editor.formatCodeAsync(cursor.left(), cursor.right()) - } else { - editor.formatCodeAsync() - } - return true - } -} diff --git a/app/src/main/java/com/itsaky/androidide/actions/filetree/BaseDirNodeAction.kt b/app/src/main/java/com/itsaky/androidide/actions/filetree/BaseDirNodeAction.kt deleted file mode 100644 index 1244c9141d..0000000000 --- a/app/src/main/java/com/itsaky/androidide/actions/filetree/BaseDirNodeAction.kt +++ /dev/null @@ -1,52 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.actions.filetree - -import android.content.Context -import androidx.annotation.DrawableRes -import androidx.annotation.StringRes -import com.itsaky.androidide.actions.ActionData -import com.itsaky.androidide.actions.markInvisible -import com.itsaky.androidide.actions.requireFile - -/** - * Base class for action items for directory nodes. - * - * @author Akash Yadav - */ -abstract class BaseDirNodeAction(context: Context, - @StringRes labelRes: Int? = null, - @DrawableRes iconRes: Int? = null) : BaseFileTreeAction(context, labelRes, iconRes) { - - override fun prepare(data: ActionData) { - super.prepare(data) - if (!data.hasFileTreeData()) { - markInvisible() - return - } - - val file = data.requireFile() - if (!file.isDirectory) { - markInvisible() - return - } - - visible = true - enabled = true - } -} diff --git a/app/src/main/java/com/itsaky/androidide/actions/filetree/BaseFileTreeAction.kt b/app/src/main/java/com/itsaky/androidide/actions/filetree/BaseFileTreeAction.kt deleted file mode 100644 index 2f206a62e7..0000000000 --- a/app/src/main/java/com/itsaky/androidide/actions/filetree/BaseFileTreeAction.kt +++ /dev/null @@ -1,95 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.actions.filetree - -import android.content.Context -import androidx.annotation.DrawableRes -import androidx.annotation.StringRes -import androidx.core.content.ContextCompat -import com.itsaky.androidide.actions.ActionData -import com.itsaky.androidide.actions.ActionItem -import com.itsaky.androidide.actions.EditorActivityAction -import com.itsaky.androidide.actions.hasRequiredData -import com.itsaky.androidide.actions.markInvisible -import com.itsaky.androidide.eventbus.events.Event -import com.itsaky.androidide.events.CollapseTreeNodeRequestEvent -import com.itsaky.androidide.events.ExpandTreeNodeRequestEvent -import com.itsaky.androidide.events.ListProjectFilesRequestEvent -import com.unnamed.b.atv.model.TreeNode -import org.greenrobot.eventbus.EventBus -import java.io.File - -/** - * Base class for actions related to the file tree. - * - * @author Akash Yadav - */ -abstract class BaseFileTreeAction( - context: Context, - @StringRes labelRes: Int? = null, - @DrawableRes iconRes: Int? = null -) : EditorActivityAction() { - - override var requiresUIThread: Boolean = true - override var location: ActionItem.Location = ActionItem.Location.EDITOR_FILE_TREE - - init { - labelRes?.let { label = context.getString(it) } - iconRes?.let { icon = ContextCompat.getDrawable(context, it) } - } - - override fun prepare(data: ActionData) { - super.prepare(data) - if (!data.hasFileTreeData()) { - markInvisible() - return - } - - visible = true - enabled = true - } - - protected open fun ActionData.hasFileTreeData(): Boolean { - return hasRequiredData(Context::class.java, File::class.java, TreeNode::class.java) - } - - protected fun ActionData.getTreeNode() : TreeNode? { - return this[TreeNode::class.java] - } - - protected fun ActionData.requireTreeNode() : TreeNode { - return getTreeNode()!! - } - - protected fun Event.putData(context: Context): Event { - put(Context::class.java, context) - return this - } - - protected fun requestFileListing() { - EventBus.getDefault().post(ListProjectFilesRequestEvent()) - } - - protected fun requestExpandNode(node: TreeNode) { - EventBus.getDefault().post(ExpandTreeNodeRequestEvent(node)) - } - - protected fun requestCollapseNode(node: TreeNode, includeSubnodes: Boolean) { - EventBus.getDefault().post(CollapseTreeNodeRequestEvent(node, includeSubnodes)) - } -} diff --git a/app/src/main/java/com/itsaky/androidide/actions/filetree/HelpAction.kt b/app/src/main/java/com/itsaky/androidide/actions/filetree/HelpAction.kt deleted file mode 100644 index 4ec1c5d527..0000000000 --- a/app/src/main/java/com/itsaky/androidide/actions/filetree/HelpAction.kt +++ /dev/null @@ -1,35 +0,0 @@ -package com.itsaky.androidide.actions.filetree - -import android.content.Context -import com.itsaky.androidide.R -import com.itsaky.androidide.actions.ActionData -import com.itsaky.androidide.actions.requireContext -import com.itsaky.androidide.idetooltips.TooltipManager -import com.itsaky.androidide.idetooltips.TooltipTag - -class HelpAction(context: Context, override val order: Int) : - BaseFileTreeAction( - context = context, - labelRes = R.string.help, - iconRes = R.drawable.ic_action_help_outlined - ) { - override val id: String = "ide.editor.fileTree.help" - override fun retrieveTooltipTag(isReadOnlyContext: Boolean): String { - return if (isReadOnlyContext) { - TooltipTag.PROJECT_FOLDER_HELP - } else { - TooltipTag.PROJECT_FILE_HELP - } - } - - override suspend fun execAction(data: ActionData) { - val context = data.requireContext() - - TooltipManager.showIdeCategoryTooltip( - context = context, - anchorView = data.requireTreeNode().viewHolder.view, - tag = TooltipTag.PROJECT_FILE_HELP, - ) - } - -} \ No newline at end of file diff --git a/app/src/main/java/com/itsaky/androidide/actions/filetree/OpenWithAction.kt b/app/src/main/java/com/itsaky/androidide/actions/filetree/OpenWithAction.kt deleted file mode 100644 index 791a02d53d..0000000000 --- a/app/src/main/java/com/itsaky/androidide/actions/filetree/OpenWithAction.kt +++ /dev/null @@ -1,59 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.actions.filetree - -import android.content.Context -import android.content.Intent -import com.itsaky.androidide.actions.ActionData -import com.itsaky.androidide.actions.markInvisible -import com.itsaky.androidide.actions.requireFile -import com.itsaky.androidide.idetooltips.TooltipTag -import com.itsaky.androidide.resources.R -import com.itsaky.androidide.utils.IntentUtils - -/** - * File tree action to open files with external applications. - * - * @author Akash Yadav - */ -class OpenWithAction(context: Context, override val order: Int) : - BaseFileTreeAction( - context = context, - labelRes = R.string.open_with, - iconRes = R.drawable.ic_open_with - ) { - - override val id: String = "ide.editor.fileTree.openWith" - - override fun retrieveTooltipTag(isAlternateContext: Boolean): String = - TooltipTag.PROJECT_FILE_OPENWITH - - override fun prepare(data: ActionData) { - super.prepare(data) - - // Hide "Open with" option for directories - val file = data.requireFile() - if (file.isDirectory) { - markInvisible() - } - } - - override suspend fun execAction(data: ActionData) { - IntentUtils.startIntent(data.requireActivity(), data.requireFile(), "*/*", Intent.ACTION_VIEW) - } -} diff --git a/app/src/main/java/com/itsaky/androidide/actions/internalActionUtils.kt b/app/src/main/java/com/itsaky/androidide/actions/internalActionUtils.kt deleted file mode 100644 index ff7b40ee4f..0000000000 --- a/app/src/main/java/com/itsaky/androidide/actions/internalActionUtils.kt +++ /dev/null @@ -1,71 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.actions - -import android.content.Context -import com.itsaky.androidide.R -import com.itsaky.androidide.projects.IProjectManager -import com.itsaky.androidide.projects.api.AndroidModule -import com.itsaky.androidide.utils.DialogUtils -import com.itsaky.androidide.utils.ILogger -import com.itsaky.androidide.utils.flashError - -/** - * @see openApplicationModuleChooser - */ -inline fun openApplicationModuleChooser(data: ActionData, - crossinline callback: (AndroidModule) -> Unit) = - openApplicationModuleChooser(data.requireContext(), callback) - -/** - * Shows a dialog to let the user choose between Android application modules in case the project has - * multiple subproject with `com.android.application` plugin. If the project contains only a single - * application module, it is selected by default and the dialog is not shown to the user. - * - * @param - */ -inline fun openApplicationModuleChooser(context: Context, - crossinline callback: (AndroidModule) -> Unit) { - val projectManager = IProjectManager.getInstance() - val applications = projectManager.getAndroidAppModules() - if (applications.isEmpty()) { - flashError(R.string.msg_launch_failure_no_app_module) - ILogger.ROOT.error("Cannot run application. No application modules found in project.") - return - } - - if (applications.size == 1) { - // Only one application module in available in the project. - callback(applications.first()) - return - } - - // there are multiple application modules in the project - // ask the user to select the application module to build - val builder = DialogUtils.newSingleChoiceDialog( - context, - context.getString(R.string.title_choose_application), - applications.map { it.path }.toTypedArray(), - 0) { selection -> - val app = applications[selection] - ILogger.ROOT.info("Selected application: '{}'", app.path) - callback(app) - } - - builder.show() -} \ No newline at end of file diff --git a/app/src/main/java/com/itsaky/androidide/actions/main/CloneRepositoryAction.kt b/app/src/main/java/com/itsaky/androidide/actions/main/CloneRepositoryAction.kt deleted file mode 100644 index 369e5b5abb..0000000000 --- a/app/src/main/java/com/itsaky/androidide/actions/main/CloneRepositoryAction.kt +++ /dev/null @@ -1,44 +0,0 @@ -package com.itsaky.androidide.actions.main - -import android.content.Context -import android.graphics.drawable.Drawable -import androidx.core.content.ContextCompat -import com.itsaky.androidide.R -import com.itsaky.androidide.actions.ActionData -import com.itsaky.androidide.actions.ActionItem -import com.itsaky.androidide.actions.markInvisible -import com.itsaky.androidide.activities.MainActivity -import com.itsaky.androidide.idetooltips.TooltipTag -import com.itsaky.androidide.utils.FeatureFlags - -class CloneRepositoryAction(context: Context) : ActionItem { - - override val id: String = ID - - companion object { - const val ID = "ide.main.cloneRepository" - } - - override var label: String = context.getString(R.string.clone_git_project) - override var visible: Boolean = true - override var enabled: Boolean = true - override var icon: Drawable? = ContextCompat.getDrawable(context, R.drawable.ic_clone_repo) - override var requiresUIThread: Boolean = true - override var location: ActionItem.Location = ActionItem.Location.MAIN_SCREEN - override val order: Int = 2 - - override fun retrieveTooltipTag(isReadOnlyContext: Boolean): String = TooltipTag.MAIN_GIT - - override fun prepare(data: ActionData) { - super.prepare(data) - val context = data.get(Context::class.java) - if (context !is MainActivity) { - markInvisible() - } - } - - override suspend fun execAction(data: ActionData): Any { - val context = data.get(Context::class.java) as? MainActivity ?: return false - return context.showCloneRepository() - } -} diff --git a/app/src/main/java/com/itsaky/androidide/actions/main/CreateProjectAction.kt b/app/src/main/java/com/itsaky/androidide/actions/main/CreateProjectAction.kt deleted file mode 100644 index 42b405ef51..0000000000 --- a/app/src/main/java/com/itsaky/androidide/actions/main/CreateProjectAction.kt +++ /dev/null @@ -1,43 +0,0 @@ -package com.itsaky.androidide.actions.main - -import android.content.Context -import android.graphics.drawable.Drawable -import androidx.core.content.ContextCompat -import com.itsaky.androidide.R -import com.itsaky.androidide.actions.ActionData -import com.itsaky.androidide.actions.ActionItem -import com.itsaky.androidide.actions.markInvisible -import com.itsaky.androidide.activities.MainActivity -import com.itsaky.androidide.idetooltips.TooltipTag - -class CreateProjectAction(context: Context) : ActionItem { - - override val id: String = ID - - companion object { - const val ID = "ide.main.createProject" - } - - override var label: String = context.getString(R.string.create_project) - override var visible: Boolean = true - override var enabled: Boolean = true - override var icon: Drawable? = ContextCompat.getDrawable(context, R.drawable.ic_add) - override var requiresUIThread: Boolean = true - override var location: ActionItem.Location = ActionItem.Location.MAIN_SCREEN - override val order: Int = 0 - - override fun retrieveTooltipTag(isReadOnlyContext: Boolean): String = TooltipTag.PROJECT_NEW - - override fun prepare(data: ActionData) { - super.prepare(data) - val context = data.get(Context::class.java) - if (context !is MainActivity) { - markInvisible() - } - } - - override suspend fun execAction(data: ActionData): Any { - val context = data.get(Context::class.java) as? MainActivity ?: return false - return context.showCreateProject() - } -} diff --git a/app/src/main/java/com/itsaky/androidide/actions/main/DeleteProjectAction.kt b/app/src/main/java/com/itsaky/androidide/actions/main/DeleteProjectAction.kt deleted file mode 100644 index 23fc18802f..0000000000 --- a/app/src/main/java/com/itsaky/androidide/actions/main/DeleteProjectAction.kt +++ /dev/null @@ -1,43 +0,0 @@ -package com.itsaky.androidide.actions.main - -import android.content.Context -import android.graphics.drawable.Drawable -import androidx.core.content.ContextCompat -import com.itsaky.androidide.R -import com.itsaky.androidide.actions.ActionData -import com.itsaky.androidide.actions.ActionItem -import com.itsaky.androidide.actions.markInvisible -import com.itsaky.androidide.idetooltips.TooltipTag -import com.itsaky.androidide.viewmodel.MainViewModel - -class DeleteProjectAction(context: Context) : ActionItem { - - override val id: String = ID - - companion object { - const val ID = "ide.main.deleteProject" - } - - override var label: String = context.getString(R.string.msg_delete_existing_project) - override var visible: Boolean = true - override var enabled: Boolean = true - override var icon: Drawable? = ContextCompat.getDrawable(context, R.drawable.ic_delete) - override var requiresUIThread: Boolean = true - override var location: ActionItem.Location = ActionItem.Location.MAIN_SCREEN - override val order: Int = 3 - - override fun retrieveTooltipTag(isReadOnlyContext: Boolean): String = TooltipTag.MAIN_PROJECT_DELETE - - override fun prepare(data: ActionData) { - super.prepare(data) - if (data.get(MainViewModel::class.java) == null || data.get(Context::class.java) == null) { - markInvisible() - } - } - - override suspend fun execAction(data: ActionData): Any { - val viewModel = data.get(MainViewModel::class.java) ?: return false - viewModel.setScreen(MainViewModel.SCREEN_DELETE_PROJECTS) - return true - } -} diff --git a/app/src/main/java/com/itsaky/androidide/actions/main/DocsAction.kt b/app/src/main/java/com/itsaky/androidide/actions/main/DocsAction.kt deleted file mode 100644 index 349107e487..0000000000 --- a/app/src/main/java/com/itsaky/androidide/actions/main/DocsAction.kt +++ /dev/null @@ -1,52 +0,0 @@ -package com.itsaky.androidide.actions.main - -import android.content.Context -import android.content.Intent -import android.graphics.drawable.Drawable -import androidx.core.content.ContextCompat -import com.itsaky.androidide.R -import com.itsaky.androidide.actions.ActionData -import com.itsaky.androidide.actions.ActionItem -import com.itsaky.androidide.actions.markInvisible -import com.itsaky.androidide.activities.editor.HelpActivity -import com.itsaky.androidide.idetooltips.TooltipTag -import com.itsaky.androidide.resources.R.string -import org.adfa.constants.CONTENT_KEY -import org.adfa.constants.CONTENT_TITLE_KEY - -class DocsAction(context: Context) : ActionItem { - - override val id: String = ID - - companion object { - const val ID = "ide.main.docs" - } - - override var label: String = context.getString(R.string.btn_docs) - override var visible: Boolean = true - override var enabled: Boolean = true - override var icon: Drawable? = ContextCompat.getDrawable(context, R.drawable.ic_action_help_outlined) - override var requiresUIThread: Boolean = true - override var location: ActionItem.Location = ActionItem.Location.MAIN_SCREEN - override val order: Int = 7 - - override fun retrieveTooltipTag(isReadOnlyContext: Boolean): String = TooltipTag.MAIN_HELP - - override fun prepare(data: ActionData) { - super.prepare(data) - if (data.get(Context::class.java) == null) { - markInvisible() - } - } - - override suspend fun execAction(data: ActionData): Any { - val context = data.get(Context::class.java) ?: return false - val intent = - Intent(context, HelpActivity::class.java).apply { - putExtra(CONTENT_KEY, context.getString(string.docs_url)) - putExtra(CONTENT_TITLE_KEY, context.getString(string.back_to_cogo)) - } - context.startActivity(intent) - return true - } -} diff --git a/app/src/main/java/com/itsaky/androidide/actions/main/DonateAction.kt b/app/src/main/java/com/itsaky/androidide/actions/main/DonateAction.kt deleted file mode 100644 index caa6f6852d..0000000000 --- a/app/src/main/java/com/itsaky/androidide/actions/main/DonateAction.kt +++ /dev/null @@ -1,42 +0,0 @@ -package com.itsaky.androidide.actions.main - -import android.content.Context -import android.graphics.drawable.Drawable -import androidx.core.content.ContextCompat -import com.itsaky.androidide.R -import com.itsaky.androidide.actions.ActionData -import com.itsaky.androidide.actions.ActionItem -import com.itsaky.androidide.actions.markInvisible -import com.itsaky.androidide.actions.requireContext -import com.itsaky.androidide.utils.UrlManager - -class DonateAction(context: Context) : ActionItem { - - override val id: String = ID - - companion object { - const val ID = "ide.main.donate" - } - - override var label: String = context.getString(R.string.btn_donate) - override var visible: Boolean = true - override var enabled: Boolean = true - override var icon: Drawable? = ContextCompat.getDrawable(context, R.drawable.ic_heart) - override var requiresUIThread: Boolean = true - override var location: ActionItem.Location = ActionItem.Location.MAIN_SCREEN - override val order: Int = 6 - - override fun prepare(data: ActionData) { - super.prepare(data) - if (data.get(Context::class.java) == null) { - markInvisible() - } - markInvisible() // Until we allow donations - } - - override suspend fun execAction(data: ActionData): Any { - val context = data.requireContext() - UrlManager.openUrl(context.getString(R.string.sponsor_url), null, context) - return true - } -} diff --git a/app/src/main/java/com/itsaky/androidide/actions/main/OpenProjectAction.kt b/app/src/main/java/com/itsaky/androidide/actions/main/OpenProjectAction.kt deleted file mode 100644 index 1120fdd629..0000000000 --- a/app/src/main/java/com/itsaky/androidide/actions/main/OpenProjectAction.kt +++ /dev/null @@ -1,43 +0,0 @@ -package com.itsaky.androidide.actions.main - -import android.content.Context -import android.graphics.drawable.Drawable -import androidx.core.content.ContextCompat -import com.itsaky.androidide.R -import com.itsaky.androidide.actions.ActionData -import com.itsaky.androidide.actions.ActionItem -import com.itsaky.androidide.actions.markInvisible -import com.itsaky.androidide.activities.MainActivity -import com.itsaky.androidide.idetooltips.TooltipTag - -class OpenProjectAction(context: Context) : ActionItem { - - override val id: String = ID - - companion object { - const val ID = "ide.main.openProject" - } - - override var label: String = context.getString(R.string.msg_open_existing_project) - override var visible: Boolean = true - override var enabled: Boolean = true - override var icon: Drawable? = ContextCompat.getDrawable(context, R.drawable.ic_folder_open) - override var requiresUIThread: Boolean = true - override var location: ActionItem.Location = ActionItem.Location.MAIN_SCREEN - override val order: Int = 1 - - override fun retrieveTooltipTag(isReadOnlyContext: Boolean): String = TooltipTag.PROJECT_OPEN - - override fun prepare(data: ActionData) { - super.prepare(data) - val context = data.get(Context::class.java) - if (context !is MainActivity) { - markInvisible() - } - } - - override suspend fun execAction(data: ActionData): Any { - val context = data.get(Context::class.java) as? MainActivity ?: return false - return context.showOpenProject() - } -} diff --git a/app/src/main/java/com/itsaky/androidide/actions/main/OpenTerminalAction.kt b/app/src/main/java/com/itsaky/androidide/actions/main/OpenTerminalAction.kt deleted file mode 100644 index 93a9986101..0000000000 --- a/app/src/main/java/com/itsaky/androidide/actions/main/OpenTerminalAction.kt +++ /dev/null @@ -1,47 +0,0 @@ -package com.itsaky.androidide.actions.main - -import android.content.Context -import android.content.Intent -import android.graphics.drawable.Drawable -import androidx.core.content.ContextCompat -import com.itsaky.androidide.R -import com.itsaky.androidide.actions.ActionData -import com.itsaky.androidide.actions.ActionItem -import com.itsaky.androidide.actions.markInvisible -import com.itsaky.androidide.activities.TerminalActivity -import com.itsaky.androidide.idetooltips.TooltipTag -import com.itsaky.androidide.utils.applyMultiWindowFlags - -class OpenTerminalAction(context: Context) : ActionItem { - - override val id: String = ID - - companion object { - const val ID = "ide.main.openTerminal" - } - - override var label: String = context.getString(R.string.title_terminal) - override var visible: Boolean = true - override var enabled: Boolean = true - override var icon: Drawable? = ContextCompat.getDrawable(context, R.drawable.ic_terminal) - override var requiresUIThread: Boolean = true - override var location: ActionItem.Location = ActionItem.Location.MAIN_SCREEN - override val order: Int = 4 - - override fun retrieveTooltipTag(isReadOnlyContext: Boolean): String = TooltipTag.MAIN_TERMINAL - - override fun prepare(data: ActionData) { - super.prepare(data) - if (data.get(Context::class.java) == null) { - markInvisible() - } - } - - override suspend fun execAction(data: ActionData): Any { - val context = data.get(Context::class.java) ?: return false - val intent = Intent(context, TerminalActivity::class.java) - .applyMultiWindowFlags(context) - context.startActivity(intent) - return true - } -} diff --git a/app/src/main/java/com/itsaky/androidide/actions/main/PreferencesAction.kt b/app/src/main/java/com/itsaky/androidide/actions/main/PreferencesAction.kt deleted file mode 100644 index 6e70f4c511..0000000000 --- a/app/src/main/java/com/itsaky/androidide/actions/main/PreferencesAction.kt +++ /dev/null @@ -1,44 +0,0 @@ -package com.itsaky.androidide.actions.main - -import android.content.Context -import android.content.Intent -import android.graphics.drawable.Drawable -import androidx.core.content.ContextCompat -import com.itsaky.androidide.R -import com.itsaky.androidide.actions.ActionData -import com.itsaky.androidide.actions.ActionItem -import com.itsaky.androidide.actions.markInvisible -import com.itsaky.androidide.activities.PreferencesActivity -import com.itsaky.androidide.idetooltips.TooltipTag - -class PreferencesAction(context: Context) : ActionItem { - - override val id: String = ID - - companion object { - const val ID = "ide.main.preferences" - } - - override var label: String = context.getString(R.string.msg_preferences) - override var visible: Boolean = true - override var enabled: Boolean = true - override var icon: Drawable? = ContextCompat.getDrawable(context, R.drawable.ic_settings) - override var requiresUIThread: Boolean = true - override var location: ActionItem.Location = ActionItem.Location.MAIN_SCREEN - override val order: Int = 5 - - override fun retrieveTooltipTag(isReadOnlyContext: Boolean): String = TooltipTag.MAIN_PREFERENCES - - override fun prepare(data: ActionData) { - super.prepare(data) - if (data.get(Context::class.java) == null) { - markInvisible() - } - } - - override suspend fun execAction(data: ActionData): Any { - val context = data.get(Context::class.java) ?: return false - context.startActivity(Intent(context, PreferencesActivity::class.java)) - return true - } -} diff --git a/app/src/main/java/com/itsaky/androidide/actions/observers/FileActionObserver.kt b/app/src/main/java/com/itsaky/androidide/actions/observers/FileActionObserver.kt deleted file mode 100644 index 032117d1d1..0000000000 --- a/app/src/main/java/com/itsaky/androidide/actions/observers/FileActionObserver.kt +++ /dev/null @@ -1,12 +0,0 @@ -package com.itsaky.androidide.actions.observers - -import java.io.File - -/** - * An observer to receive feedback on file action results. - * Implement this in your Fragment or Activity to show UI feedback. - */ -interface FileActionObserver { - fun onActionSuccess(message: String, createdFile: File?) - fun onActionFailure(errorMessage: String) -} \ No newline at end of file diff --git a/app/src/main/java/com/itsaky/androidide/actions/sidebar/AbstractSidebarAction.kt b/app/src/main/java/com/itsaky/androidide/actions/sidebar/AbstractSidebarAction.kt deleted file mode 100644 index b9885b151e..0000000000 --- a/app/src/main/java/com/itsaky/androidide/actions/sidebar/AbstractSidebarAction.kt +++ /dev/null @@ -1,46 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.actions.sidebar - -import android.graphics.drawable.Drawable -import com.itsaky.androidide.actions.ActionData -import com.itsaky.androidide.actions.ActionItem -import com.itsaky.androidide.actions.SidebarActionItem - -/** - * @author Akash Yadav - */ -abstract class AbstractSidebarAction : SidebarActionItem { - - // sidebar actions should always be executed on UI thread - override var requiresUIThread = true - override var visible = true - override var enabled = true - - // should never change - override var location = ActionItem.Location.EDITOR_SIDEBAR - - // Subclasses should accept a Context in their constructor and initialize these values - // when the object instance is initialized - override var icon: Drawable? = null - override var label: String = "" - - override suspend fun execAction(data: ActionData): Any { - return false - } -} \ No newline at end of file diff --git a/app/src/main/java/com/itsaky/androidide/actions/sidebar/BuildVariantsSidebarAction.kt b/app/src/main/java/com/itsaky/androidide/actions/sidebar/BuildVariantsSidebarAction.kt deleted file mode 100644 index d4e9b3f1e7..0000000000 --- a/app/src/main/java/com/itsaky/androidide/actions/sidebar/BuildVariantsSidebarAction.kt +++ /dev/null @@ -1,51 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.actions.sidebar - -import android.content.Context -import androidx.core.content.ContextCompat -import androidx.fragment.app.Fragment -import com.itsaky.androidide.R -import com.itsaky.androidide.actions.ActionItem -import com.itsaky.androidide.fragments.sidebar.BuildVariantsFragment -import com.itsaky.androidide.idetooltips.TooltipTag -import kotlin.reflect.KClass - -/** - * Sidebar action for showing the build variants of Android modules in the project. - * - * @author Akash Yadav - */ -class BuildVariantsSidebarAction(context: Context, override val order: Int) : - AbstractSidebarAction() { - - override val fragmentClass: KClass = BuildVariantsFragment::class - override val id: String = "ide.editor.sidebar.buildVariants" - override var location: ActionItem.Location = ActionItem.Location.EDITOR_SIDEBAR - - - companion object { - const val ID ="ide.editor.sidebar.buildVariants" - } - init { - label = context.getString(R.string.title_build_variants) - icon = ContextCompat.getDrawable(context, R.drawable.ic_android) - } - - override fun retrieveTooltipTag(isAlternateContext: Boolean) = TooltipTag.BUILD_VARIANT_SIDEBAR -} \ No newline at end of file diff --git a/app/src/main/java/com/itsaky/androidide/actions/sidebar/CloseProjectSidebarAction.kt b/app/src/main/java/com/itsaky/androidide/actions/sidebar/CloseProjectSidebarAction.kt deleted file mode 100644 index f9299aed9e..0000000000 --- a/app/src/main/java/com/itsaky/androidide/actions/sidebar/CloseProjectSidebarAction.kt +++ /dev/null @@ -1,52 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.actions.sidebar - -import android.content.Context -import androidx.core.content.ContextCompat -import androidx.fragment.app.Fragment -import com.itsaky.androidide.actions.ActionData -import com.itsaky.androidide.actions.requireContext -import com.itsaky.androidide.activities.editor.BaseEditorActivity -import com.itsaky.androidide.idetooltips.TooltipTag -import com.itsaky.androidide.resources.R -import kotlin.reflect.KClass - -/** - * Sidebar action for closing the project. - * - * @author Akash Yadav - */ -class CloseProjectSidebarAction(context: Context, override val order: Int) : - AbstractSidebarAction() { - - override val id: String = "ide.editor.sidebar.closeProject" - override val fragmentClass: KClass? = null - - init { - label = context.getString(R.string.title_close_project) - icon = ContextCompat.getDrawable(context, R.drawable.ic_folder_close) - } - - override suspend fun execAction(data: ActionData): Any { - val context = data.requireContext() as BaseEditorActivity - context.doConfirmProjectClose() - return true - } - override fun retrieveTooltipTag(isAlternateContext: Boolean) = TooltipTag.CLOSE_PROJECT_SIDEBAR -} \ No newline at end of file diff --git a/app/src/main/java/com/itsaky/androidide/actions/sidebar/FileTreeSidebarAction.kt b/app/src/main/java/com/itsaky/androidide/actions/sidebar/FileTreeSidebarAction.kt deleted file mode 100644 index 732c868841..0000000000 --- a/app/src/main/java/com/itsaky/androidide/actions/sidebar/FileTreeSidebarAction.kt +++ /dev/null @@ -1,48 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.actions.sidebar - -import android.content.Context -import androidx.core.content.ContextCompat -import androidx.fragment.app.Fragment -import com.itsaky.androidide.R -import com.itsaky.androidide.fragments.sidebar.FileTreeFragment -import com.itsaky.androidide.idetooltips.TooltipTag -import kotlin.reflect.KClass - -/** - * Sidebar action for showing file tree. - * - * @author Akash Yadav - */ -class FileTreeSidebarAction(context: Context, override val order: Int) : AbstractSidebarAction() { - - companion object { - const val ID ="ide.editor.sidebar.fileTree" - } - - override val id: String = ID - override val fragmentClass: KClass = FileTreeFragment::class - - init { - label = context.getString(R.string.msg_file_tree) - icon = ContextCompat.getDrawable(context, R.drawable.ic_folder) - } - - override fun retrieveTooltipTag(isAlternateContext: Boolean) = TooltipTag.FILE_TREE_SIDEBAR -} \ No newline at end of file diff --git a/app/src/main/java/com/itsaky/androidide/actions/sidebar/HelpSideBarAction.kt b/app/src/main/java/com/itsaky/androidide/actions/sidebar/HelpSideBarAction.kt deleted file mode 100644 index 4d3445d5a7..0000000000 --- a/app/src/main/java/com/itsaky/androidide/actions/sidebar/HelpSideBarAction.kt +++ /dev/null @@ -1,52 +0,0 @@ -package com.itsaky.androidide.actions.sidebar - -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -import android.content.Context -import androidx.core.content.ContextCompat -import androidx.fragment.app.Fragment -import com.itsaky.androidide.actions.ActionData -import com.itsaky.androidide.actions.requireContext -import com.itsaky.androidide.activities.editor.BaseEditorActivity -import com.itsaky.androidide.idetooltips.TooltipTag -import com.itsaky.androidide.resources.R -import kotlin.reflect.KClass - -/** - * Sidebar action for opening the help section. - * - * @author Daniel Alome - */ -class HelpSideBarAction(context: Context, override val order: Int) : - AbstractSidebarAction() { - - override val id: String = "ide.editor.sidebar.help" - override val fragmentClass: KClass? = null - - init { - label = context.getString(R.string.action_open_help) - icon = ContextCompat.getDrawable(context, R.drawable.ic_action_help_outlined) - } - - override suspend fun execAction(data: ActionData): Any { - val context = data.requireContext() as BaseEditorActivity - context.doOpenHelp() - return true - } - override fun retrieveTooltipTag(isAlternateContext: Boolean) = TooltipTag.HELP_SIDEBAR -} \ No newline at end of file diff --git a/app/src/main/java/com/itsaky/androidide/actions/sidebar/PreferencesSidebarAction.kt b/app/src/main/java/com/itsaky/androidide/actions/sidebar/PreferencesSidebarAction.kt deleted file mode 100644 index 69cf782a8d..0000000000 --- a/app/src/main/java/com/itsaky/androidide/actions/sidebar/PreferencesSidebarAction.kt +++ /dev/null @@ -1,58 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.actions.sidebar - -import android.content.Context -import android.content.Intent -import androidx.core.content.ContextCompat -import androidx.fragment.app.Fragment -import com.itsaky.androidide.R -import com.itsaky.androidide.actions.ActionData -import com.itsaky.androidide.actions.requireContext -import com.itsaky.androidide.activities.PreferencesActivity -import com.itsaky.androidide.idetooltips.TooltipTag -import kotlin.reflect.KClass - -/** - * A sidebar action to navigate the user to IDE Preferences. - * - * @author Akash Yadav - */ -class PreferencesSidebarAction(context: Context, override val order: Int) : AbstractSidebarAction() { - - override val id: String = ID - - companion object { - const val ID = "ide.editor.sidebar.preferences" - } - - // TODO : Should we show the preferences in the sidebar itself? - override val fragmentClass: KClass? = null - - init { - label = context.getString(R.string.ide_preferences) - icon = ContextCompat.getDrawable(context, R.drawable.ic_settings) - } - - override suspend fun execAction(data: ActionData): Any { - val context = data.requireContext() - return context.startActivity(Intent(context, PreferencesActivity::class.java)) - } - override fun retrieveTooltipTag(isAlternateContext: Boolean) = TooltipTag.PREFERENCES_SIDEBAR - -} diff --git a/app/src/main/java/com/itsaky/androidide/actions/sidebar/TerminalSidebarAction.kt b/app/src/main/java/com/itsaky/androidide/actions/sidebar/TerminalSidebarAction.kt deleted file mode 100644 index 9f346c01cd..0000000000 --- a/app/src/main/java/com/itsaky/androidide/actions/sidebar/TerminalSidebarAction.kt +++ /dev/null @@ -1,86 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.actions.sidebar - -import android.content.Context -import android.content.Intent -import androidx.core.content.ContextCompat -import androidx.fragment.app.Fragment -import com.itsaky.androidide.R -import com.itsaky.androidide.actions.ActionData -import com.itsaky.androidide.actions.requireContext -import com.itsaky.androidide.activities.TerminalActivity -import com.itsaky.androidide.idetooltips.TooltipTag -import com.itsaky.androidide.projects.IProjectManager -import com.itsaky.androidide.utils.applyMultiWindowFlags -import com.termux.shared.termux.TermuxConstants.TERMUX_APP.TERMUX_ACTIVITY -import java.util.Objects -import kotlin.reflect.KClass - -/** - * Sidebar action for opening the terminal. - * - * @author Akash Yadav - */ -class TerminalSidebarAction( - context: Context, - override val order: Int, -) : AbstractSidebarAction() { - override val id: String = ID - override val fragmentClass: KClass? = null - - init { - label = context.getString(R.string.title_terminal) - icon = ContextCompat.getDrawable(context, R.drawable.ic_terminal) - } - - companion object { - const val ID = "ide.editor.sidebar.terminal" - - fun startTerminalActivity( - data: ActionData, - isFailsafe: Boolean, - ) { - val context = data.requireContext() - val intent = - Intent(context, TerminalActivity::class.java).apply { - putExtra( - TERMUX_ACTIVITY.EXTRA_SESSION_WORKING_DIR, - Objects.requireNonNull(IProjectManager.getInstance().projectDirPath), - ) - putExtra( - TERMUX_ACTIVITY.EXTRA_SESSION_NAME, - IProjectManager - .getInstance() - .workspace - ?.rootProject - ?.name, - ) - putExtra(TERMUX_ACTIVITY.EXTRA_FAILSAFE_SESSION, isFailsafe) - }.applyMultiWindowFlags(context) - context.startActivity(intent) - } - } - - override suspend fun execAction(data: ActionData): Any { - startTerminalActivity(data, false) - return true - } - - override fun retrieveTooltipTag(isAlternateContext: Boolean) = TooltipTag.TERMINAL_SIDEBAR -} diff --git a/app/src/main/java/com/itsaky/androidide/actions/text/RedoAction.kt b/app/src/main/java/com/itsaky/androidide/actions/text/RedoAction.kt deleted file mode 100644 index ed4fd5a1b7..0000000000 --- a/app/src/main/java/com/itsaky/androidide/actions/text/RedoAction.kt +++ /dev/null @@ -1,83 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.actions.text - -import android.app.Activity -import android.content.Context -import android.view.MenuItem -import androidx.core.content.ContextCompat -import com.itsaky.androidide.actions.ActionData -import com.itsaky.androidide.actions.EditorRelatedAction -import com.itsaky.androidide.actions.markInvisible -import com.itsaky.androidide.idetooltips.TooltipTag -import com.itsaky.androidide.resources.R -import com.itsaky.androidide.utils.isSoftInputVisible - -/** @author Akash Yadav */ -class RedoAction( - context: Context, - override val order: Int, -) : EditorRelatedAction() { - override fun retrieveTooltipTag(isReadOnlyContext: Boolean): String = TooltipTag.EDITOR_TOOLBAR_REDO - - override val id: String = ID - - companion object { - const val ID = "ide.editor.code.text.redo" - } - - init { - label = context.getString(R.string.redo) - icon = ContextCompat.getDrawable(context, R.drawable.ic_redo) - } - - override fun prepare(data: ActionData) { - super.prepare(data) - - if (!visible) { - return - } - - val editor = - data.getEditor() ?: run { - markInvisible() - return - } - - enabled = editor.canRedo() - } - - override suspend fun execAction(data: ActionData): Boolean { - val editor = - data.getEditor() ?: run { - markInvisible() - return false - } - - editor.redo() - data.getActivity()?.invalidateOptionsMenu() - return true - } - - override fun getShowAsActionFlags(data: ActionData): Int = - if ((data.get(Context::class.java) as Activity).isSoftInputVisible()) { - MenuItem.SHOW_AS_ACTION_IF_ROOM - } else { - MenuItem.SHOW_AS_ACTION_NEVER - } -} diff --git a/app/src/main/java/com/itsaky/androidide/actions/text/UndoAction.kt b/app/src/main/java/com/itsaky/androidide/actions/text/UndoAction.kt deleted file mode 100644 index 9993aab707..0000000000 --- a/app/src/main/java/com/itsaky/androidide/actions/text/UndoAction.kt +++ /dev/null @@ -1,63 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.actions.text - -import android.content.Context -import androidx.core.content.ContextCompat -import com.itsaky.androidide.actions.ActionData -import com.itsaky.androidide.actions.EditorRelatedAction -import com.itsaky.androidide.idetooltips.TooltipTag -import com.itsaky.androidide.resources.R - -/** @author Akash Yadav */ -class UndoAction(context: Context, override val order: Int) : EditorRelatedAction() { - - override fun retrieveTooltipTag(isReadOnlyContext: Boolean): String = TooltipTag.EDITOR_TOOLBAR_UNDO - override val id: String = ID - - companion object { - const val ID = "ide.editor.code.text.undo" - } - - init { - label = context.getString(R.string.undo) - icon = ContextCompat.getDrawable(context, R.drawable.ic_undo) - } - - override fun prepare(data: ActionData) { - super.prepare(data) - - if (!visible) { - return - } - - val editor = data.getEditor()!! - enabled = editor.canUndo() - } - - override suspend fun execAction(data: ActionData): Any { - val editor = data.getEditor() - return if (editor != null) { - editor.undo() - data.getActivity()?.invalidateOptionsMenu() - true - } else { - false - } - } -} diff --git a/app/src/main/java/com/itsaky/androidide/activities/CrashHandlerActivity.java b/app/src/main/java/com/itsaky/androidide/activities/CrashHandlerActivity.java deleted file mode 100644 index cb288a0b78..0000000000 --- a/app/src/main/java/com/itsaky/androidide/activities/CrashHandlerActivity.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.activities; - -import android.os.Bundle; -import android.view.View; - -import androidx.annotation.NonNull; - -import com.itsaky.androidide.app.IDEActivity; -import com.itsaky.androidide.databinding.ActivityCrashHandlerBinding; -import com.itsaky.androidide.fragments.CrashReportFragment; - -public class CrashHandlerActivity extends IDEActivity { - - public static final String REPORT_ACTION = "com.itsaky.androidide.REPORT_CRASH"; - public static final String TRACE_KEY = "crash_trace"; - private ActivityCrashHandlerBinding binding; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - final var extra = getIntent().getExtras(); - if (extra == null) { - finishAffinity(); - return; - } - - final var fragment = CrashReportFragment.newInstance(); - - getSupportFragmentManager() - .beginTransaction() - .replace(binding.getRoot().getId(), fragment, "crash_report_fragment") - .addToBackStack(null) - .commit(); - } - - @Override - @NonNull - protected View bindLayout() { - binding = ActivityCrashHandlerBinding.inflate(getLayoutInflater()); - return binding.getRoot(); - } - - @Override - protected void onDestroy() { - super.onDestroy(); - binding = null; - } -} diff --git a/app/src/main/java/com/itsaky/androidide/activities/editor/IDELogcatReader.kt b/app/src/main/java/com/itsaky/androidide/activities/editor/IDELogcatReader.kt deleted file mode 100644 index 79f7dd2bf7..0000000000 --- a/app/src/main/java/com/itsaky/androidide/activities/editor/IDELogcatReader.kt +++ /dev/null @@ -1,134 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ -package com.itsaky.androidide.activities.editor - -import android.os.Process -import com.itsaky.androidide.preferences.internal.GeneralPreferences -import com.itsaky.androidide.utils.Environment -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.Job -import kotlinx.coroutines.cancel -import kotlinx.coroutines.launch -import org.slf4j.LoggerFactory -import java.io.File -import java.text.SimpleDateFormat -import java.util.Date -import java.util.Locale - -/** - * Reads the logs from AndroidIDE and saves it to a file in the projects directory. - * - * @author Akash Yadav - */ -class IDELogcatReader { - - private var job: Job? = null - private var shouldRun = false - - companion object { - - private val log = LoggerFactory.getLogger(IDELogcatReader::class.java) - private const val MAX_LOG_BYTES: Long = 5L * 1024L * 1024L - } - - /** - * Start reading the logs. - */ - fun start() { - shouldRun = true - - check(job == null) { - "Logcat reader is already running" - } - - job = CoroutineScope(Dispatchers.IO).launch { - run() - } - } - - /** - * Stop the log reader. - */ - fun stop() { - shouldRun = false - job?.cancel("User requested cancellation") - job = null - } - - private fun run() { - val date = Date() - val dateFormat = SimpleDateFormat("yyyy-MM-dd_HH:mm:ss.SSS", Locale.US) - val outputFile = File(Environment.ANDROIDIDE_HOME, - "logs/CodeOnTheGo-LOG-${dateFormat.format(date)}.txt") - - log.debug("Creating output file: {}", outputFile) - - outputFile.parentFile!!.mkdirs() - try { - outputFile.createNewFile() - } catch (e: Exception) { - log.error("Failed to create output file for log", e) - return - } - - outputFile.outputStream().buffered().use { writer -> - try { - val captureAllBuffers = GeneralPreferences.logcatCaptureAll - val args = mutableListOf("logcat") - if (captureAllBuffers) { - args.addAll(listOf("-b", "all")) - } - args.addAll(listOf("--pid", Process.myPid().toString(), "-v", "threadtime")) - - val process = ProcessBuilder(args).let { builder -> - builder.redirectErrorStream(true) - builder.start() - } - try { - val buffer = ByteArray(8 * 1024) - var written = 0L - process.inputStream.use { input -> - while (shouldRun) { - val read = input.read(buffer) - if (read <= 0) break - val remaining = MAX_LOG_BYTES - written - if (remaining <= 0) break - val toWrite = if (read > remaining) remaining.toInt() else read - writer.write(buffer, 0, toWrite) - written += toWrite - if (written >= MAX_LOG_BYTES) break - } - } - - writer.flush() - if (written >= MAX_LOG_BYTES) { - log.warn( - "Logcat capture reached max size ({} bytes). Truncating output.", - MAX_LOG_BYTES - ) - } - } finally { - process.destroy() - log.info("Process ended with exit code: {}", process.waitFor()) - } - } catch (err: Throwable) { - log.error("Failed to read logs", err) - } - } - } -} diff --git a/app/src/main/java/com/itsaky/androidide/adapters/BuildVariantsAdapter.kt b/app/src/main/java/com/itsaky/androidide/adapters/BuildVariantsAdapter.kt deleted file mode 100644 index 7aa7b67a09..0000000000 --- a/app/src/main/java/com/itsaky/androidide/adapters/BuildVariantsAdapter.kt +++ /dev/null @@ -1,100 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.adapters - -import android.view.LayoutInflater -import android.view.ViewGroup -import android.widget.ArrayAdapter -import androidx.core.widget.addTextChangedListener -import androidx.recyclerview.widget.RecyclerView -import com.itsaky.androidide.R -import com.itsaky.androidide.databinding.LayoutBuildVariantItemBinding -import com.itsaky.androidide.tooling.api.IAndroidProject -import com.itsaky.androidide.tooling.api.models.BuildVariantInfo -import com.itsaky.androidide.tooling.api.models.BuildVariantInfo.Companion.withSelection -import com.itsaky.androidide.viewmodel.BuildVariantsViewModel -import java.util.Objects - -/** - * [RecyclerView] adapter for showing the list of Android modules and their selected build variant. - * - * @property items - * @author Akash Yadav - */ -class BuildVariantsAdapter( - private val viewModel: BuildVariantsViewModel, - private var items: List -) : RecyclerView.Adapter() { - - class ViewHolder(internal val binding: LayoutBuildVariantItemBinding) : - RecyclerView.ViewHolder(binding.root) - - override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { - val binding = LayoutBuildVariantItemBinding.inflate(LayoutInflater.from(parent.context), parent, - false) - return ViewHolder(binding) - } - - override fun getItemCount(): Int { - return items.size - } - - override fun onBindViewHolder(holder: ViewHolder, position: Int) { - val binding = holder.binding - val variantInfo = items[position] - - binding.moduleName.text = variantInfo.projectPath - - binding.variantName.apply { - - val viewModel = viewModel - - setAdapter( - ArrayAdapter(binding.root.context, R.layout.support_simple_spinner_dropdown_item, - variantInfo.buildVariants - ) - ) - - var listSelection = variantInfo.buildVariants.indexOf(variantInfo.selectedVariant) - if (listSelection < 0 || listSelection >= variantInfo.buildVariants.size) { - listSelection = 0 - } - - this.listSelection = listSelection - setText(variantInfo.selectedVariant, false) - - addTextChangedListener { editable -> - // update the changed build variants map - viewModel.updatedBuildVariants = viewModel.updatedBuildVariants.also { variants -> - - // the newly selected build variant - // if this is different that the variant that was used while initializing the project, - // then the user is notified to re-sync the project - // else the selection is cleared - val newSelection = editable?.toString() ?: IAndroidProject.DEFAULT_VARIANT - - if (!Objects.equals(variantInfo.selectedVariant, newSelection)) { - variants[variantInfo.projectPath] = variantInfo.withSelection(newSelection) - } else { - variants.remove(variantInfo.projectPath) - } - } - } - } - } -} \ No newline at end of file diff --git a/app/src/main/java/com/itsaky/androidide/adapters/DeleteProjectListAdapter.kt b/app/src/main/java/com/itsaky/androidide/adapters/DeleteProjectListAdapter.kt deleted file mode 100644 index aedcc2b2e0..0000000000 --- a/app/src/main/java/com/itsaky/androidide/adapters/DeleteProjectListAdapter.kt +++ /dev/null @@ -1,71 +0,0 @@ -package com.itsaky.androidide.adapters - -import android.view.LayoutInflater -import android.view.View -import android.view.ViewGroup -import androidx.recyclerview.widget.RecyclerView -import com.itsaky.androidide.databinding.DeleteProjectsItemBinding -import com.itsaky.androidide.models.Checkable -import com.itsaky.androidide.models.ProjectFile - -class DeleteProjectListAdapter( - private var projects: List>, - private val onSelectionChange: (Boolean) -> Unit, - private val onCheckboxLongPress: () -> Boolean -) : RecyclerView.Adapter() { - - override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProjectViewHolder { - val binding = - DeleteProjectsItemBinding.inflate(LayoutInflater.from(parent.context), parent, false) - return ProjectViewHolder(binding) - } - - override fun onBindViewHolder(holder: ProjectViewHolder, position: Int) { - holder.bind(projects[position]) - } - - override fun getItemCount(): Int = projects.size - - fun getSelectedProjects(): List = projects.filter { it.isChecked }.map { it.data } - - fun updateProjects(newProjects: List>) { - projects = newProjects - notifyDataSetChanged() - } - - private fun hasSelection(): Boolean = projects.any { it.isChecked } - - private fun renderDate(binding: DeleteProjectsItemBinding, project: ProjectFile) { - binding.projectDate.text = project.renderDateText(binding.root.context) - } - - inner class ProjectViewHolder(private val binding: DeleteProjectsItemBinding) : - RecyclerView.ViewHolder(binding.root) { - - fun bind(item: Checkable) { - val project = item.data - - binding.projectName.text = project.name - renderDate(binding, project) - binding.icon.text = project.name.take(2).uppercase() - - binding.checkbox.visibility = View.VISIBLE - binding.checkbox.isChecked = item.isChecked - - binding.root.setOnClickListener { - item.isChecked = !item.isChecked - binding.checkbox.isChecked = item.isChecked - onSelectionChange(hasSelection()) - } - - binding.checkbox.setOnClickListener { - binding.root.performClick() - } - - binding.checkbox.setOnLongClickListener { - onCheckboxLongPress() - } - } - } -} - diff --git a/app/src/main/java/com/itsaky/androidide/adapters/DiagnosticItemAdapter.java b/app/src/main/java/com/itsaky/androidide/adapters/DiagnosticItemAdapter.java deleted file mode 100644 index 330220c26b..0000000000 --- a/app/src/main/java/com/itsaky/androidide/adapters/DiagnosticItemAdapter.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - * - */ -package com.itsaky.androidide.adapters; - -import android.graphics.PorterDuff; -import android.view.LayoutInflater; -import android.view.ViewGroup; -import androidx.annotation.NonNull; -import androidx.core.content.ContextCompat; -import androidx.recyclerview.widget.RecyclerView; -import com.itsaky.androidide.databinding.LayoutDiagnosticItemBinding; -import com.itsaky.androidide.interfaces.DiagnosticClickListener; -import com.itsaky.androidide.lsp.models.DiagnosticItem; -import com.itsaky.androidide.lsp.models.DiagnosticSeverity; -import com.itsaky.androidide.resources.R; -import java.io.File; -import java.util.List; -import java.util.Objects; - -public class DiagnosticItemAdapter extends RecyclerView.Adapter { - - private final List diagnostics; - private final File file; - private final DiagnosticClickListener listener; - - public DiagnosticItemAdapter( - List diagnostics, File file, DiagnosticClickListener listener) { - this.diagnostics = Objects.requireNonNull(diagnostics); - this.file = file; - this.listener = listener; - } - - @NonNull - @Override - public DiagnosticItemAdapter.VH onCreateViewHolder(@NonNull ViewGroup p1, int p2) { - return new VH( - LayoutDiagnosticItemBinding.inflate(LayoutInflater.from(p1.getContext()), p1, false)); - } - - @Override - public void onBindViewHolder(DiagnosticItemAdapter.VH p1, int p2) { - final DiagnosticItem diagnostic = diagnostics.get(p2); - final LayoutDiagnosticItemBinding binding = p1.binding; - - binding.icon.setImageResource(getDiagnosticIconId(diagnostic)); - binding.icon.setContentDescription( - binding.icon.getContext().getString( - diagnostic.getSeverity() == DiagnosticSeverity.ERROR - ? R.string.cd_diagnostic_error - : R.string.cd_diagnostic_warning)); - binding.icon.setColorFilter( - ContextCompat.getColor( - binding.icon.getContext(), - diagnostic.getSeverity() == DiagnosticSeverity.ERROR - ? R.color.diagnostic_error - : R.color.diagnostic_warning), - PorterDuff.Mode.SRC_ATOP); - binding.title.setText(diagnostic.getMessage()); - - binding - .getRoot() - .setOnClickListener( - v -> { - if (listener != null) { - listener.onDiagnosticClick(file, diagnostic); - } - }); - } - - @Override - public int getItemCount() { - return diagnostics.size(); - } - - private int getDiagnosticIconId(DiagnosticItem diagnostic) { - if (diagnostic.getSeverity() == DiagnosticSeverity.ERROR) - return R.drawable.ic_compilation_error; - return R.drawable.ic_info; - } - - public static class VH extends RecyclerView.ViewHolder { - private LayoutDiagnosticItemBinding binding; - - public VH(LayoutDiagnosticItemBinding binding) { - super(binding.getRoot()); - this.binding = binding; - } - } -} diff --git a/app/src/main/java/com/itsaky/androidide/adapters/DiagnosticsAdapter.java b/app/src/main/java/com/itsaky/androidide/adapters/DiagnosticsAdapter.java deleted file mode 100755 index 8581065eb5..0000000000 --- a/app/src/main/java/com/itsaky/androidide/adapters/DiagnosticsAdapter.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - * - */ - -package com.itsaky.androidide.adapters; - -import android.view.LayoutInflater; -import android.view.ViewGroup; -import androidx.annotation.NonNull; -import androidx.recyclerview.widget.LinearLayoutManager; -import androidx.recyclerview.widget.RecyclerView; -import com.itsaky.androidide.databinding.LayoutDiagnosticGroupBinding; -import com.itsaky.androidide.interfaces.DiagnosticClickListener; -import com.itsaky.androidide.models.DiagnosticGroup; -import java.util.List; -import java.util.Objects; - -public class DiagnosticsAdapter extends RecyclerView.Adapter { - - private final List diagnostics; - private final DiagnosticClickListener listener; - - public DiagnosticsAdapter(List diagnostics, DiagnosticClickListener listener) { - this.diagnostics = Objects.requireNonNull(diagnostics); - this.listener = listener; - } - - @NonNull - @Override - public DiagnosticsAdapter.VH onCreateViewHolder(ViewGroup p1, int p2) { - return new VH( - LayoutDiagnosticGroupBinding.inflate(LayoutInflater.from(p1.getContext()), p1, false)); - } - - @Override - public void onBindViewHolder(DiagnosticsAdapter.VH p1, int p2) { - final DiagnosticGroup group = diagnostics.get(p2); - final LayoutDiagnosticGroupBinding binding = p1.binding; - - binding.info.icon.setImageResource(group.icon); - binding.info.title.setText(group.text); - binding.diagnostics.setLayoutManager(new LinearLayoutManager(binding.diagnostics.getContext())); - binding.diagnostics.setAdapter( - new DiagnosticItemAdapter(group.diagnostics, group.file, listener)); - - binding - .info - .getRoot() - .setOnClickListener( - v -> { - if (listener != null) { - listener.onGroupClick(group); - } - }); - } - - @Override - public int getItemCount() { - return diagnostics.size(); - } - - public class VH extends RecyclerView.ViewHolder { - private LayoutDiagnosticGroupBinding binding; - - public VH(LayoutDiagnosticGroupBinding binding) { - super(binding.getRoot()); - this.binding = binding; - } - } -} diff --git a/app/src/main/java/com/itsaky/androidide/adapters/FilterableRecyclerViewAdapter.kt b/app/src/main/java/com/itsaky/androidide/adapters/FilterableRecyclerViewAdapter.kt deleted file mode 100644 index 07f8d44928..0000000000 --- a/app/src/main/java/com/itsaky/androidide/adapters/FilterableRecyclerViewAdapter.kt +++ /dev/null @@ -1,122 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.adapters - -import android.annotation.SuppressLint -import androidx.recyclerview.widget.DiffUtil -import androidx.recyclerview.widget.DiffUtil.Callback -import androidx.recyclerview.widget.DiffUtil.DiffResult -import androidx.recyclerview.widget.RecyclerView -import kotlinx.coroutines.CancellationException -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.Job -import kotlinx.coroutines.launch -import kotlinx.coroutines.withContext - -/** - * Filterable [RecyclerView.Adapter]. - * - * @author Akash Yadav - */ -abstract class FilterableRecyclerViewAdapter(val items: List) : - RecyclerView.Adapter() { - - protected var filtered: List = mutableListOf().apply { addAll(items) } - private var filterJob: Job? = null - - /** - * Filter the list with the given query. - * - * @param query The query. - */ - @SuppressLint("NotifyDataSetChanged") - fun filter(query: String?) { - filterJob?.cancel(CancellationException("A new query has been submitted for filtering")) - - val items = this.items - filterJob = CoroutineScope(Dispatchers.Default).launch { - val (filtered, result) = doFilter(query?.trim(), items) - - withContext(Dispatchers.Main) { - val adapter = this@FilterableRecyclerViewAdapter - if (result == null) { - adapter.filtered = adapter.items - notifyDataSetChanged() - return@withContext - } - - adapter.filtered = filtered - result.dispatchUpdatesTo(adapter) - } - } - } - - private fun doFilter( - query: String?, - items: List, - ): Pair, DiffResult?> { - if (query.isNullOrBlank()) { - return items to null - } - - val filtered = items.filter { - onFilter(it, query) - } - - val result = - DiffUtil.calculateDiff( - object : Callback() { - override fun getOldListSize(): Int { - return items.size - } - - override fun getNewListSize(): Int { - return filtered.size - } - - override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { - return items[oldItemPosition] == filtered[newItemPosition] - } - - override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { - return items[oldItemPosition] == filtered[newItemPosition] - } - } - ) - - return filtered to result - } - - /** Get the list item at given index. */ - fun getItem(index: Int): D { - return filtered[index] - } - - override fun getItemCount(): Int { - return filtered.size - } - - /** Get the query candidate for the given list item. */ - abstract fun getQueryCandidate(item: D): String - - /** Called on every item when filtering the data. */ - protected open fun onFilter(item: D, query: String): Boolean { - return getQueryCandidate(item).contains(query, ignoreCase = true) - } -} diff --git a/app/src/main/java/com/itsaky/androidide/adapters/MainActionsListAdapter.kt b/app/src/main/java/com/itsaky/androidide/adapters/MainActionsListAdapter.kt deleted file mode 100644 index 620cb53b6b..0000000000 --- a/app/src/main/java/com/itsaky/androidide/adapters/MainActionsListAdapter.kt +++ /dev/null @@ -1,79 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.adapters - -import android.view.LayoutInflater -import android.view.View -import android.view.ViewGroup -import androidx.recyclerview.widget.RecyclerView -import com.google.android.material.button.MaterialButton -import com.itsaky.androidide.actions.ActionItem -import com.itsaky.androidide.databinding.LayoutMainActionItemBinding - -/** - * Adapter for the actions available on the main screen. - * - * @author Akash Yadav - */ -class MainActionsListAdapter -@JvmOverloads -constructor( - val actions: List = emptyList(), - private val onClick: ((ActionItem, View) -> Unit)? = null, - private val onLongClick: ((ActionItem, View) -> Boolean)? = null, -) : - RecyclerView.Adapter() { - inner class VH(val binding: LayoutMainActionItemBinding) : RecyclerView.ViewHolder(binding.root) - - override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = - VH(LayoutMainActionItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)) - - override fun getItemCount(): Int = actions.size - - fun getAction(index: Int) = actions[index] - - override fun onBindViewHolder(holder: VH, position: Int) { - val action = getAction(index = position) - val binding = holder.binding - - binding.root.apply { - val originalText = action.label - text = originalText - isEnabled = action.enabled - icon = action.icon - contentDescription = originalText - setOnClickListener { - onClick?.invoke(action, it) - } - setOnLongClickListener { - onLongClick?.invoke(action, it) ?: true - } - } - (binding.root as? MaterialButton)?.findViewById(com.google.android.material.R.id.icon) - ?.importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO - if (binding.root is ViewGroup) { - for (i in 0 until (binding.root as ViewGroup).childCount) { - val child = (binding.root as ViewGroup).getChildAt(i) - if (child is android.widget.ImageView) { - child.importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO - break - } - } - } - } -} diff --git a/app/src/main/java/com/itsaky/androidide/adapters/OptionsSheetAdapter.java b/app/src/main/java/com/itsaky/androidide/adapters/OptionsSheetAdapter.java deleted file mode 100755 index 955c07384b..0000000000 --- a/app/src/main/java/com/itsaky/androidide/adapters/OptionsSheetAdapter.java +++ /dev/null @@ -1,91 +0,0 @@ -/************************************************************************************ - * This file is part of AndroidIDE. - * - * - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - * - **************************************************************************************/ - -package com.itsaky.androidide.adapters; - -import android.view.LayoutInflater; -import android.view.ViewGroup; - -import androidx.recyclerview.widget.RecyclerView; - -import com.itsaky.androidide.databinding.LayoutOptionssheetItemBinding; -import com.itsaky.androidide.models.SheetOption; - -import java.util.List; - -public class OptionsSheetAdapter extends RecyclerView.Adapter { - - private OnOptionsClickListener listener; - private List options; - - public OptionsSheetAdapter(List options, OnOptionsClickListener listener) { - this.options = options; - this.listener = listener; - } - - @Override - public OptionsSheetAdapter.VH onCreateViewHolder(ViewGroup p1, int p2) { - return new VH( - LayoutOptionssheetItemBinding.inflate(LayoutInflater.from(p1.getContext()), p1, false)); - } - - @Override - public void onBindViewHolder(OptionsSheetAdapter.VH p1, int p2) { - final LayoutOptionssheetItemBinding binding = p1.binding; - final SheetOption option = options.get(p2); - - binding.text.setText(option.title); - binding.icon.setImageDrawable(option.icon); - - binding - .getRoot() - .setOnClickListener( - v -> { - if (listener != null) listener.onOptionClick(option); - }); - binding - .getRoot() - .setOnLongClickListener( - v -> { - if (listener != null) listener.onOptionLongClick(option); - return true; - }); - } - - @Override - public int getItemCount() { - return options.size(); - } - - public class VH extends RecyclerView.ViewHolder { - private LayoutOptionssheetItemBinding binding; - - public VH(LayoutOptionssheetItemBinding binding) { - super(binding.getRoot()); - this.binding = binding; - } - } - - public static interface OnOptionsClickListener { - public void onOptionClick(SheetOption option); - - public void onOptionLongClick(SheetOption option); - } -} diff --git a/app/src/main/java/com/itsaky/androidide/adapters/onboarding/DefaultOnboardingItemAdapter.kt b/app/src/main/java/com/itsaky/androidide/adapters/onboarding/DefaultOnboardingItemAdapter.kt deleted file mode 100644 index c4a54daa3a..0000000000 --- a/app/src/main/java/com/itsaky/androidide/adapters/onboarding/DefaultOnboardingItemAdapter.kt +++ /dev/null @@ -1,103 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.adapters.onboarding - -import android.content.res.ColorStateList -import android.view.LayoutInflater -import android.view.View -import android.view.ViewGroup -import androidx.recyclerview.widget.RecyclerView -import com.itsaky.androidide.databinding.LayoutOnboardingItemBinding -import com.itsaky.androidide.models.OnboardingItem - -/** - * Default implmentation of [RecyclerView.Adapter] for showing [OnboardingItem]s. - * - * @author Akash Yadav - */ -open class DefaultOnboardingItemAdapter( - protected val items: List, - protected val onItemClickListener: OnItemClickListener? = null, - protected val onItemLongClickListener: OnItemLongClickListener? = null -) : RecyclerView.Adapter() { - - override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { - return ViewHolder( - LayoutOnboardingItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)) - } - - override fun onBindViewHolder(holder: ViewHolder, position: Int) { - doBindViewHolder(holder, position, getItem(position), holder.binding) - } - - protected open fun doBindViewHolder( - holder: ViewHolder, - position: Int, - item: T, - binding: LayoutOnboardingItemBinding - ) { - binding.content.title.text = item.title - - if (item.description.isNotBlank()) { - binding.content.description.text = item.description - } else { - binding.content.description.visibility = View.INVISIBLE - } - - if (item.icon != 0) { - binding.content.icon.setImageResource(item.icon) - if (item.iconTint != 0) { - binding.content.icon.supportImageTintList = ColorStateList.valueOf(item.iconTint) - } - } else { - binding.content.icon.visibility = View.INVISIBLE - } - - binding.root.isClickable = item.isClickable - binding.root.isFocusable = item.isClickable - - if (item.isClickable && onItemClickListener != null) { - binding.root.setOnClickListener { onItemClickListener.onClick(item, position, binding) } - } - - if (item.isLongClickable && onItemLongClickListener != null) { - binding.root.setOnLongClickListener { onItemLongClickListener.onLongClick(item, position, binding) } - } - } - - override fun getItemCount(): Int { - return items.size - } - - fun getItem(index: Int): T { - return items[index] - } - - class ViewHolder(val binding: LayoutOnboardingItemBinding) : - RecyclerView.ViewHolder(binding.root) - - fun interface OnItemClickListener { - - fun onClick(item: T, position: Int, binding: LayoutOnboardingItemBinding) - } - - fun interface OnItemLongClickListener { - - fun onLongClick(item: T, position: Int, binding: LayoutOnboardingItemBinding): Boolean - } -} \ No newline at end of file diff --git a/app/src/main/java/com/itsaky/androidide/adapters/viewholders/MultiSelectFileTreeViewHolder.java b/app/src/main/java/com/itsaky/androidide/adapters/viewholders/MultiSelectFileTreeViewHolder.java deleted file mode 100644 index 586a204230..0000000000 --- a/app/src/main/java/com/itsaky/androidide/adapters/viewholders/MultiSelectFileTreeViewHolder.java +++ /dev/null @@ -1,138 +0,0 @@ -package com.itsaky.androidide.adapters.viewholders; - -import android.content.Context; -import android.view.LayoutInflater; -import android.view.View; - -import com.itsaky.androidide.R; -import com.itsaky.androidide.databinding.LayoutFiletreeItemSelectableBinding; -import com.itsaky.androidide.models.FileExtension; -import com.unnamed.b.atv.model.TreeNode; - -import java.io.File; -import java.util.List; -import java.util.Set; - -public class MultiSelectFileTreeViewHolder extends TreeNode.BaseNodeViewHolder { - - private LayoutFiletreeItemSelectableBinding binding; - private Set selectedFiles; - - public MultiSelectFileTreeViewHolder(Context context, Set selectedFiles) { - super(context); - this.selectedFiles = selectedFiles; - } - - @Override - public View createNodeView(TreeNode node, File file) { - // This is where the binding is created, only for visible nodes. - binding = LayoutFiletreeItemSelectableBinding.inflate(LayoutInflater.from(context)); - - final boolean isDir = node.isDirectory(); - - binding.filetreeName.setText(file.getName()); - binding.filetreeIcon.setImageResource(FileExtension.Factory.forFile(file, isDir).getIcon()); - - int padding = (int) (context.getResources().getDisplayMetrics().density * 16 * (node.getLevel() - 1)); - binding.getRoot().setPadding(padding, binding.getRoot().getPaddingTop(), binding.getRoot().getPaddingRight(), binding.getRoot().getPaddingBottom()); - - if (isDir) { - binding.filetreeChevron.setVisibility(View.VISIBLE); - binding.filetreeChevron.setRotation(node.isExpanded() ? 90 : 0); - } else { - binding.filetreeChevron.setVisibility(View.INVISIBLE); - } - - View.OnClickListener toggleListener = v -> { - if (file.isDirectory()) { - getTreeView().toggleNode(node); - } - }; - binding.filetreeName.setOnClickListener(toggleListener); - binding.filetreeIcon.setOnClickListener(toggleListener); - binding.filetreeChevron.setOnClickListener(toggleListener); - - binding.filetreeCheckbox.setOnCheckedChangeListener(null); - updateCheckboxState(node); - binding.filetreeCheckbox.setOnCheckedChangeListener((buttonView, isChecked) -> { - propagateSelectionToChildren(node, isChecked); - updateParentCheckboxStates(node.getParent()); - }); - - return binding.getRoot(); - } - - @Override - public void toggle(boolean active) { - if (binding == null) return; - binding.filetreeChevron.setRotation(active ? 90 : 0); - } - - private void propagateSelectionToChildren(TreeNode node, boolean isSelected) { - File file = (File) node.getValue(); - if (isSelected) { - selectedFiles.add(file); - } else { - selectedFiles.remove(file); - } - updateCheckboxState(node); - - if (node.isDirectory()) { - for (TreeNode child : (List) node.getChildren()) { - propagateSelectionToChildren(child, isSelected); - } - } - } - - private void updateParentCheckboxStates(TreeNode parent) { - if (parent == null || parent.getValue() == null) return; - - MultiSelectFileTreeViewHolder parentViewHolder = (MultiSelectFileTreeViewHolder) parent.getViewHolder(); - if (parentViewHolder != null) { - parentViewHolder.updateCheckboxState(parent); - } - - updateParentCheckboxStates(parent.getParent()); - } - - public void updateCheckboxState(TreeNode node) { - if (binding == null) return; - - File file = node.getValue(); - if (file == null) return; - - binding.filetreeCheckbox.setOnCheckedChangeListener(null); - - if (file.isDirectory()) { - int childCount = node.getChildren().size(); - int selectedCount = 0; - for (TreeNode child : (List) node.getChildren()) { - if (selectedFiles.contains(child.getValue())) { - selectedCount++; - } - } - - if (selectedCount == 0) { - binding.filetreeCheckbox.setButtonDrawable(R.drawable.abc_btn_check_material); - binding.filetreeCheckbox.setChecked(false); - selectedFiles.remove(file); - } else if (selectedCount == childCount) { - binding.filetreeCheckbox.setButtonDrawable(R.drawable.abc_btn_check_material); - binding.filetreeCheckbox.setChecked(true); - selectedFiles.add(file); - } else { - binding.filetreeCheckbox.setButtonDrawable(R.drawable.ic_indeterminate_check_box); - binding.filetreeCheckbox.setChecked(true); - selectedFiles.remove(file); - } - } else { - binding.filetreeCheckbox.setButtonDrawable(R.drawable.abc_btn_check_material); - binding.filetreeCheckbox.setChecked(selectedFiles.contains(file)); - } - - binding.filetreeCheckbox.setOnCheckedChangeListener((buttonView, isChecked) -> { - propagateSelectionToChildren(node, isChecked); - updateParentCheckboxStates(node.getParent()); - }); - } -} \ No newline at end of file diff --git a/app/src/main/java/com/itsaky/androidide/agent/model/ModelLoadResult.kt b/app/src/main/java/com/itsaky/androidide/agent/model/ModelLoadResult.kt deleted file mode 100644 index e68e6f043f..0000000000 --- a/app/src/main/java/com/itsaky/androidide/agent/model/ModelLoadResult.kt +++ /dev/null @@ -1,16 +0,0 @@ -package com.itsaky.androidide.agent.model - -sealed interface ModelLoadResult { - data class Loaded( - val modelName: String - ) : ModelLoadResult - - data class Rejected( - val message: String - ) : ModelLoadResult - - data class Failed( - val message: String, - val cause: Throwable? = null - ) : ModelLoadResult -} diff --git a/app/src/main/java/com/itsaky/androidide/analytics/gradle/BuildMetric.kt b/app/src/main/java/com/itsaky/androidide/analytics/gradle/BuildMetric.kt deleted file mode 100644 index 06a6b43372..0000000000 --- a/app/src/main/java/com/itsaky/androidide/analytics/gradle/BuildMetric.kt +++ /dev/null @@ -1,24 +0,0 @@ -package com.itsaky.androidide.analytics.gradle - -import android.os.Bundle -import com.itsaky.androidide.analytics.Metric -import com.itsaky.androidide.tooling.api.messages.BuildId - -/** - * Metric about a build event. - * - * @author Akash Yadav - */ -abstract class BuildMetric : Metric { - /** - * Unique ID of the build session. - */ - abstract val buildId: BuildId - - override fun asBundle(): Bundle = - Bundle().apply { - putString("build_session_id", buildId.buildSessionId) - putLong("build_id", buildId.buildId) - putString("run_type", buildId.runType.typeName) - } -} diff --git a/app/src/main/java/com/itsaky/androidide/api/IDEApiFacade.kt b/app/src/main/java/com/itsaky/androidide/api/IDEApiFacade.kt deleted file mode 100644 index 9309400b32..0000000000 --- a/app/src/main/java/com/itsaky/androidide/api/IDEApiFacade.kt +++ /dev/null @@ -1,76 +0,0 @@ -package com.itsaky.androidide.api - -import com.itsaky.androidide.actions.ActionData -import com.itsaky.androidide.actions.ActionItem -import com.itsaky.androidide.actions.ActionsRegistry -import com.itsaky.androidide.actions.internal.DefaultActionsRegistry -import com.itsaky.androidide.projects.builder.BuildResult -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.suspendCancellableCoroutine -import kotlinx.coroutines.withContext -import kotlin.coroutines.resume - -/** - * Simple result wrapper for API operations. - */ -data class ApiResult( - val success: Boolean, - val message: String = "", - val data: String = "" -) - -/** - * The single, clean entry point for the AI agent to interact with the IDE. - */ -object IDEApiFacade { - - suspend fun runApp(): ApiResult { - val activity = ActionContextProvider.getActivity() - ?: return ApiResult(false, "No active IDE window to launch the app.") - - val action = ActionsRegistry.getInstance() - .findAction(ActionItem.Location.EDITOR_TOOLBAR, "ide.editor.build.quickRun") - ?: return ApiResult(false, "Launch App action is not available.") - - val actionData = ActionData.create(activity) - - return suspendCancellableCoroutine { continuation -> - val listener = java.util.function.Consumer { result -> - when { - result.isSuccess && result.launchResult != null && result.launchResult.isSuccess -> { - continuation.resume(ApiResult(true, "App built and launched successfully on the device.")) - } - result.isSuccess -> { - val launchError = - result.launchResult?.message ?: "Launch failed for an unknown reason." - continuation.resume(ApiResult(false, "Build was successful, but the app failed to launch: $launchError")) - } - else -> { - continuation.resume(ApiResult(false, "Build failed: ${result.message}")) - } - } - } - - continuation.invokeOnCancellation { activity.removeOneTimeBuildResultListener(listener) } - - val registry = ActionsRegistry.getInstance() as? DefaultActionsRegistry - if (registry == null) { - continuation.resume(ApiResult(false, "Failed to get action registry instance.")) - return@suspendCancellableCoroutine - } - - activity.addOneTimeBuildResultListener(listener) - - try { - registry.executeAction(action, actionData) - } catch (t: Throwable) { - activity.removeOneTimeBuildResultListener(listener) - if (continuation.isActive) { - continuation.resume( - ApiResult(false, "Failed to launch the app: ${t.message}") - ) - } - } - } - } -} diff --git a/app/src/main/java/com/itsaky/androidide/app/EdgeToEdgeIDEActivity.kt b/app/src/main/java/com/itsaky/androidide/app/EdgeToEdgeIDEActivity.kt deleted file mode 100644 index 140f74727a..0000000000 --- a/app/src/main/java/com/itsaky/androidide/app/EdgeToEdgeIDEActivity.kt +++ /dev/null @@ -1,191 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.app - -import android.annotation.SuppressLint -import android.content.Context -import android.content.res.Configuration -import android.graphics.Rect -import android.os.Build -import android.os.Build.VERSION_CODES -import android.os.Bundle -import android.os.PersistableBundle -import android.view.View -import android.view.WindowInsets -import android.view.WindowManager -import android.view.inputmethod.InputMethodManager -import androidx.annotation.CallSuper -import androidx.core.graphics.Insets -import androidx.core.view.OnApplyWindowInsetsListener -import androidx.core.view.ViewCompat -import androidx.core.view.WindowInsetsCompat -import androidx.core.view.doOnAttach -import com.itsaky.androidide.utils.EdgeToEdgeUtils -import com.itsaky.androidide.utils.getSystemBarInsets -import org.slf4j.LoggerFactory - -/** - * Same as IDEActivity but DecorFitsSystemWindows is set to false - * Useful for creating immersive edge-to-edge experiences. - * - * @author Smooth E - * @author Akash Yadav - */ -abstract class EdgeToEdgeIDEActivity : IDEActivity() { - - /** - * Whether edge-to-edge should be applied to the activity. - */ - protected open var edgeToEdgeEnabled = true - - /** - * Whether the decor view padding should be updated to match the system bars in landscape orientation. - */ - protected open var eteUpdateDecorViewPaddingInLandscape = true - - /** - * Style for the status bar. - */ - protected open val statusBarStyle = EdgeToEdgeUtils.DEFAULT_STATUS_BAR_STYLE!! - - /** - * Style for the navigation bar. - */ - protected open val navigationBarStyle = EdgeToEdgeUtils.DEFAULT_NAVIGATION_BAR_STYLE!! - - /** - * Original padding of the window's decor view. - */ - protected open var decorViewPadding: Rect? = null - - /** - * Last window insets. - */ - protected open var systemBarInsets: Insets? = null - - override var enableSystemBarTheming: Boolean - get() = false - set(@Suppress("UNUSED_PARAMETER") value) { - throw UnsupportedOperationException("Use edgeToEdgeEnabled and systemBarStyles instead") - } - - private val log = LoggerFactory.getLogger(EdgeToEdgeIDEActivity::class.java) - - @SuppressLint("WrongConstant") - private val onApplyWindowInsetsListener = OnApplyWindowInsetsListener { view, insets -> - onApplyWindowInsets(insets) - if (!eteUpdateDecorViewPaddingInLandscape || - view.resources.configuration.orientation != Configuration.ORIENTATION_LANDSCAPE - ) { - decorViewPadding?.also { p -> - // when switching from landscape to portrait, restore the original padding - view.setPadding(p.left, p.top, p.right, p.bottom) - } - return@OnApplyWindowInsetsListener insets - } - - if (decorViewPadding == null) { - Rect().apply { - left = view.paddingLeft - top = view.paddingTop - right = view.paddingRight - bottom = view.paddingBottom - }.also { paddings -> - decorViewPadding = paddings - } - } - - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { - val systemBarInsets = insets.getInsets(WindowInsets.Type.systemBars()) - view.setPadding( - systemBarInsets.left, - 0, - systemBarInsets.right, - systemBarInsets.bottom - ) - } else { - @Suppress("DEPRECATION") - view.setPadding( - insets.stableInsetLeft, - 0, - insets.stableInsetRight, - insets.stableInsetBottom - ) - } - - insets - } - - override fun onCreate(savedInstanceState: Bundle?) { - applyEdgeToEdge() - super.onCreate(savedInstanceState) - } - - override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) { - applyEdgeToEdge() - super.onCreate(savedInstanceState, persistentState) - } - - @SuppressLint("RestrictedApi") - private fun applyEdgeToEdge() { - this.window!!.apply { - addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) - @Suppress("DEPRECATION") - clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION) - if (Build.VERSION.SDK_INT >= VERSION_CODES.P) { - attributes = attributes.apply { - layoutInDisplayCutoutMode = - WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES - } - } - } - - EdgeToEdgeUtils.applyEdgeToEdge(this, this.statusBarStyle, this.navigationBarStyle) - - ViewCompat.setOnApplyWindowInsetsListener( - this.window.decorView, - this.onApplyWindowInsetsListener - ) - - this.window.decorView.doOnAttach { onApplySystemBarInsets(getSystemBarInsets(it)) } - } - - /** - * Called when the window insets change. - * - * @param insets The window insets. These insets are not expected to be consumed. - */ - @CallSuper - protected open fun onApplyWindowInsets(insets: WindowInsetsCompat) { - this.systemBarInsets = getSystemBarInsets(insets) - } - - /** - * Called with the system bar insets when the decor view is attached to the window. - */ - protected open fun onApplySystemBarInsets(insets: Insets) {} - - fun closeKeyboard() { - // Get the current focused view; if none, create a new one so that we have a valid window token - val view = currentFocus ?: View(this) - // Retrieve the input method manager service - val inputMethodManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager - // Request to hide the keyboard from the window - inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0) - } -} diff --git a/app/src/main/java/com/itsaky/androidide/app/EditorEvents.kt b/app/src/main/java/com/itsaky/androidide/app/EditorEvents.kt deleted file mode 100644 index 295df1d391..0000000000 --- a/app/src/main/java/com/itsaky/androidide/app/EditorEvents.kt +++ /dev/null @@ -1,75 +0,0 @@ -package com.itsaky.androidide.app - -import android.util.Log -import java.io.File -import java.util.concurrent.CopyOnWriteArrayList - -/** - * Process-wide dispatcher that EditorHandlerActivity uses to broadcast editor lifecycle events - * out to non-activity subscribers (e.g. plugin service providers). Activity-side observers - * already have direct access to the view model; this exists so cross-process modules don't - * need to depend on activity internals. - * - * `lastActiveFile` retains the most recent non-null active file so a plugin asking - * "what is the user editing?" still gets a useful answer even when the foreground tab - * is a plugin tab (which has no file). - */ -object EditorEvents { - - private const val TAG = "EditorEvents" - - @Volatile - var lastActiveFile: File? = null - private set - - private val fileChangeListeners = CopyOnWriteArrayList<(File?) -> Unit>() - - fun addFileChangeListener(listener: (File?) -> Unit) { - fileChangeListeners.addIfAbsent(listener) - } - - fun removeFileChangeListener(listener: (File?) -> Unit) { - fileChangeListeners.remove(listener) - } - - @Volatile - private var lastNotifiedPath: String? = null - - /** - * Called by the editor activity whenever the displayed tab changes. `file` is non-null - * only when the active tab is a real file (not a plugin tab); `lastActiveFile` is only - * updated for non-null files so consumers can still answer "what was the user editing?" - * while a plugin tab is in the foreground. Listeners fire only when the active path - * actually changes — dedup here means a 2Hz-polling plugin doesn't see redundant - * notifications on every UI tick. - */ - fun notifyFileChanged(file: File?) { - if (file != null) { - lastActiveFile = file - } - val path = file?.absolutePath - if (path == lastNotifiedPath) return - lastNotifiedPath = path - Log.d(TAG, "notifyFileChanged -> ${path ?: ""}") - fileChangeListeners.forEach { listener -> - try { - listener(file) - } catch (_: Exception) { - } - } - } - - /** - * Called when an opened file is no longer in the editor (closed). If it matches our - * stashed `lastActiveFile`, clear it so we don't hand plugins a stale path. - */ - fun notifyFileClosed(file: File) { - if (lastActiveFile?.absolutePath == file.absolutePath) { - Log.d(TAG, "notifyFileClosed: clearing lastActiveFile (${file.absolutePath})") - lastActiveFile = null - // Clear dedupe state too, otherwise reopening the same path later could be - // swallowed by notifyFileChanged's "same path" short-circuit. - lastNotifiedPath = null - } - } -} diff --git a/app/src/main/java/com/itsaky/androidide/app/configuration/JdkDistributionProviderImpl.kt b/app/src/main/java/com/itsaky/androidide/app/configuration/JdkDistributionProviderImpl.kt deleted file mode 100644 index f84f7faf27..0000000000 --- a/app/src/main/java/com/itsaky/androidide/app/configuration/JdkDistributionProviderImpl.kt +++ /dev/null @@ -1,73 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.app.configuration - -import com.google.auto.service.AutoService -import com.itsaky.androidide.models.JdkDistribution -import com.itsaky.androidide.preferences.internal.BuildPreferences -import com.itsaky.androidide.utils.Environment -import com.itsaky.androidide.utils.JdkUtils -import org.slf4j.LoggerFactory -import java.io.File - -/** - * @author Akash Yadav - */ -@AutoService(IJdkDistributionProvider::class) -class JdkDistributionProviderImpl : IJdkDistributionProvider { - - companion object { - - private val log = LoggerFactory.getLogger(JdkDistributionProviderImpl::class.java) - } - - private var _installedDistributions: List? = null - - override val installedDistributions: List - get() = _installedDistributions ?: emptyList() - - override fun loadDistributions() { - _installedDistributions = doLoadDistributions() - } - - private fun doLoadDistributions(): List { - return JdkUtils.findJavaInstallations().also { distributions -> - if(distributions.isEmpty()) { - return emptyList() - } - - val selectedJavaHome = findDefaultDistribution(distributions)?.javaHome?.let { File(it) } - ?: distributions.first().javaHome.let { File(it) } - - log.debug("Setting Environment.JAVA_HOME to {}", selectedJavaHome.absolutePath) - Environment.JAVA_HOME = selectedJavaHome - Environment.JAVA = selectedJavaHome.resolve("bin/java") - } - } - - private fun findDefaultDistribution(distributions: List): JdkDistribution? { - return distributions.find { - it.javaVersion.startsWith(IJdkDistributionProvider.DEFAULT_JAVA_VERSION) - } - } - - private fun isValidJavaHome(javaHome: File): Boolean { - val javaExec = javaHome.resolve("bin/java") - return javaHome.exists() && javaExec.exists() && javaExec.isFile && javaExec.canExecute() - } -} \ No newline at end of file diff --git a/app/src/main/java/com/itsaky/androidide/app/strictmode/ViolationHandler.kt b/app/src/main/java/com/itsaky/androidide/app/strictmode/ViolationHandler.kt deleted file mode 100644 index ded11d7808..0000000000 --- a/app/src/main/java/com/itsaky/androidide/app/strictmode/ViolationHandler.kt +++ /dev/null @@ -1,48 +0,0 @@ -package com.itsaky.androidide.app.strictmode - -import com.itsaky.androidide.tasks.runOnUiThread -import org.slf4j.LoggerFactory - -/** - * A violation handler for strict mode. - * - * @author Akash Yadav - */ -object ViolationHandler { - private val logger = LoggerFactory.getLogger(ViolationHandler::class.java) - - private const val ALLOW_VIOLATION_MESSAGE = "StrictMode violation '{}' allowed because: {}" - private const val WARN_VIOLATION_MESSAGE = "StrictMode violation detected" - - /** - * Allow the violation. - * - * @param violation The violation that was detected. - */ - fun allow( - violation: ViolationDispatcher.Violation, - reason: String, - ) { - logger.info(ALLOW_VIOLATION_MESSAGE, violation.violation.javaClass.simpleName, reason) - } - - /** - * Log the violation. - * - * @param violation The violation that was detected. - */ - fun log(violation: ViolationDispatcher.Violation) { - logger.warn(WARN_VIOLATION_MESSAGE, violation.violation) - } - - /** - * Crash the app (throw an exception on the main thread). - * - * @param violation The violation that was detected. - */ - fun crash(violation: ViolationDispatcher.Violation) { - runOnUiThread { - throw RuntimeException(WARN_VIOLATION_MESSAGE, violation.violation) - } - } -} \ No newline at end of file diff --git a/app/src/main/java/com/itsaky/androidide/assets/AssetsInstallExceptions.kt b/app/src/main/java/com/itsaky/androidide/assets/AssetsInstallExceptions.kt deleted file mode 100644 index c3e9e8ff71..0000000000 --- a/app/src/main/java/com/itsaky/androidide/assets/AssetsInstallExceptions.kt +++ /dev/null @@ -1,3 +0,0 @@ -package com.itsaky.androidide.assets - -class MissingAssetsEntryException(cause: Throwable) : Exception(cause) diff --git a/app/src/main/java/com/itsaky/androidide/di/AppModule.kt b/app/src/main/java/com/itsaky/androidide/di/AppModule.kt deleted file mode 100644 index a9c1a7a8fb..0000000000 --- a/app/src/main/java/com/itsaky/androidide/di/AppModule.kt +++ /dev/null @@ -1,67 +0,0 @@ -package com.itsaky.androidide.di - -import com.itsaky.androidide.actions.FileActionManager -import com.itsaky.androidide.analytics.AnalyticsManager -import com.itsaky.androidide.analytics.IAnalyticsManager -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.RecentProjectRepository -import com.itsaky.androidide.repositories.RecentProjectRepositoryImpl -import com.itsaky.androidide.roomData.recentproject.RecentProjectRoomDatabase -import com.itsaky.androidide.viewmodel.CloneRepositoryViewModel -import com.itsaky.androidide.viewmodel.GitBottomSheetViewModel -import com.itsaky.androidide.viewmodel.MainViewModel -import com.itsaky.androidide.viewmodel.OutlineViewModel -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.SupervisorJob -import org.koin.android.ext.koin.androidApplication -import org.koin.android.ext.koin.androidContext -import org.koin.core.module.dsl.viewModel -import org.koin.core.qualifier.named -import org.koin.dsl.module - -/** Qualifier for the process-lifetime [CoroutineScope]; see the binding for why it is named. */ -const val APPLICATION_SCOPE = "applicationScope" - -val coreModule = - module { - single { FileActionManager() } - - // Analytics - single { AnalyticsManager() } - - viewModel { - GitBottomSheetViewModel(get()) - } - viewModel { MainViewModel() } - viewModel { CloneRepositoryViewModel(get(), get()) } - single { TreeSitterOutlineProvider(androidContext()) } - viewModel { OutlineViewModel(get()) } - - // Named, because an unqualified single is claimed by type alone: this one - // instance was serving both the Room database below and EditorHandlerActivity's saveAllAsync, - // and a second unqualified CoroutineScope added anywhere would silently retarget the save with - // no compile error and no failing test. Consumers now ask for it by name. - single(named(APPLICATION_SCOPE)) { - CoroutineScope(SupervisorJob() + Dispatchers.IO) - } - - single { - RecentProjectRoomDatabase.getDatabase(androidApplication(), get(named(APPLICATION_SCOPE))) - } - - single { - get().recentProjectDao() - } - - single { - RecentProjectRepositoryImpl(get()) - } - - single { GitCredentialsManager(get()) } - - single { PendingDeepLinkOpen() } - } diff --git a/app/src/main/java/com/itsaky/androidide/di/PluginModule.kt b/app/src/main/java/com/itsaky/androidide/di/PluginModule.kt deleted file mode 100644 index abc42ee177..0000000000 --- a/app/src/main/java/com/itsaky/androidide/di/PluginModule.kt +++ /dev/null @@ -1,50 +0,0 @@ -package com.itsaky.androidide.di - -import com.itsaky.androidide.app.IDEApplication -import com.itsaky.androidide.repositories.PluginRepository -import com.itsaky.androidide.repositories.PluginRepositoryImpl -import com.itsaky.androidide.repositories.TemplateCollectionRepository -import com.itsaky.androidide.repositories.TemplateCollectionRepositoryImpl -import com.itsaky.androidide.viewmodels.ExternalFileInstallViewModel -import com.itsaky.androidide.viewmodels.PluginManagerViewModel -import org.koin.android.ext.koin.androidContext -import org.koin.androidx.viewmodel.dsl.viewModel -import org.koin.dsl.module -import java.io.File - -/** - * Koin module for plugin-related dependencies - */ -val pluginModule = - module { - - // Repository - single { - PluginRepositoryImpl( - pluginManagerProvider = { IDEApplication.getPluginManager() }, - pluginsDir = File(IDEApplication.cachedFilesDir, "plugins"), - ) - } - - single { - TemplateCollectionRepositoryImpl() - } - - // ViewModel - viewModel { - PluginManagerViewModel( - pluginRepository = get(), - contentResolver = androidContext().contentResolver, - filesDir = IDEApplication.cachedFilesDir, - ) - } - - viewModel { - ExternalFileInstallViewModel( - pluginRepository = get(), - templateCollectionRepository = get(), - contentResolver = androidContext().contentResolver, - filesDir = IDEApplication.cachedFilesDir, - ) - } - } diff --git a/app/src/main/java/com/itsaky/androidide/di/TemplateModule.kt b/app/src/main/java/com/itsaky/androidide/di/TemplateModule.kt deleted file mode 100644 index efddd25b84..0000000000 --- a/app/src/main/java/com/itsaky/androidide/di/TemplateModule.kt +++ /dev/null @@ -1,30 +0,0 @@ -package com.itsaky.androidide.di - -import com.itsaky.androidide.repositories.TemplateRepository -import com.itsaky.androidide.repositories.TemplateRepositoryImpl -import com.itsaky.androidide.utils.Environment -import com.itsaky.androidide.viewmodels.TemplateManagerViewModel -import org.koin.androidx.viewmodel.dsl.viewModel -import org.koin.dsl.module - -/** - * Koin module for template-related dependencies - */ -val templateModule = - module { - - // Repository - single { - TemplateRepositoryImpl( - templatesDir = Environment.TEMPLATES_DIR, - downloadDir = Environment.DOWNLOAD_DIR, - ) - } - - // ViewModel - viewModel { - TemplateManagerViewModel( - templateRepository = get(), - ) - } - } diff --git a/app/src/main/java/com/itsaky/androidide/dnd/DragEventRouter.kt b/app/src/main/java/com/itsaky/androidide/dnd/DragEventRouter.kt deleted file mode 100644 index a991cca0f8..0000000000 --- a/app/src/main/java/com/itsaky/androidide/dnd/DragEventRouter.kt +++ /dev/null @@ -1,53 +0,0 @@ -package com.itsaky.androidide.dnd - -import android.view.DragEvent -import android.view.View - -/** - * A [View.OnDragListener] implementation that delegates the complex Android drag state machine - * into a clean [DropTargetCallback]. - */ -class DragEventRouter( - private val callback: DropTargetCallback -) : View.OnDragListener { - override fun onDrag(view: View, event: DragEvent): Boolean { - val canHandle = callback.canAcceptDrop(event) - - return when (event.action) { - DragEvent.ACTION_DRAG_STARTED -> { - if (canHandle) callback.onDragStarted(view) - canHandle - } - - DragEvent.ACTION_DRAG_ENTERED -> { - if (canHandle) callback.onDragEntered(view) - true - } - - DragEvent.ACTION_DRAG_LOCATION -> { - canHandle - } - - DragEvent.ACTION_DRAG_EXITED -> { - callback.onDragExited(view) - true - } - - DragEvent.ACTION_DROP -> { - callback.onDragExited(view) - if (canHandle) { - callback.onDrop(event) - } else { - false - } - } - - DragEvent.ACTION_DRAG_ENDED -> { - callback.onDragExited(view) - canHandle - } - - else -> false - } - } -} diff --git a/app/src/main/java/com/itsaky/androidide/dnd/DropTargetCallback.kt b/app/src/main/java/com/itsaky/androidide/dnd/DropTargetCallback.kt deleted file mode 100644 index ba39ff0173..0000000000 --- a/app/src/main/java/com/itsaky/androidide/dnd/DropTargetCallback.kt +++ /dev/null @@ -1,35 +0,0 @@ -package com.itsaky.androidide.dnd - -import android.view.DragEvent -import android.view.View - -/** - * Callback interface for handling routed drag-and-drop events on a specific target view. - */ -interface DropTargetCallback { - /** - * Determines whether the current [event] contains data that this target can handle. - */ - fun canAcceptDrop(event: DragEvent): Boolean - - /** - * Called when a drag operation begins. Useful for applying initial visual cues. - */ - fun onDragStarted(view: View) {} - - /** - * Called when a valid dragged item enters the bounds of the target [view]. - */ - fun onDragEntered(view: View) - - /** - * Called when a dragged item exits the target [view], or when the drag operation ends/is canceled. - */ - fun onDragExited(view: View) - - /** - * Called when the user successfully drops a valid item on the target. - * @return True if the drop was successfully consumed and handled. - */ - fun onDrop(event: DragEvent): Boolean -} diff --git a/app/src/main/java/com/itsaky/androidide/dnd/GitUrlDropExtensions.kt b/app/src/main/java/com/itsaky/androidide/dnd/GitUrlDropExtensions.kt deleted file mode 100644 index a6fdb6e018..0000000000 --- a/app/src/main/java/com/itsaky/androidide/dnd/GitUrlDropExtensions.kt +++ /dev/null @@ -1,28 +0,0 @@ -package com.itsaky.androidide.dnd - -import android.view.View -import androidx.fragment.app.Fragment -import androidx.lifecycle.DefaultLifecycleObserver -import androidx.lifecycle.LifecycleOwner - - -fun Fragment.handleGitUrlDrop( - targetView: View = requireView(), - shouldAcceptDrop: () -> Boolean = { isVisible }, - onDropped: (String) -> Unit -) { - val dropTarget = GitUrlDropTarget( - context = requireContext(), - rootView = targetView, - shouldAcceptDrop = shouldAcceptDrop, - onRepositoryDropped = onDropped - ) - - dropTarget.attach() - - viewLifecycleOwner.lifecycle.addObserver(object : DefaultLifecycleObserver { - override fun onDestroy(owner: LifecycleOwner) { - dropTarget.detach() - } - }) -} diff --git a/app/src/main/java/com/itsaky/androidide/dnd/GitUrlDropTarget.kt b/app/src/main/java/com/itsaky/androidide/dnd/GitUrlDropTarget.kt deleted file mode 100644 index bd8b1b1aa9..0000000000 --- a/app/src/main/java/com/itsaky/androidide/dnd/GitUrlDropTarget.kt +++ /dev/null @@ -1,107 +0,0 @@ -package com.itsaky.androidide.dnd - -import android.content.ClipDescription -import android.content.Context -import android.view.DragEvent -import android.view.View -import androidx.core.view.ContentInfoCompat -import androidx.core.view.ViewCompat -import com.itsaky.androidide.git.core.parseGitRepositoryUrl -import com.itsaky.androidide.utils.DropHighlighter - -internal class GitUrlDropTarget( - private val context: Context, - private val rootView: View, - private val shouldAcceptDrop: () -> Boolean = { true }, - private val onRepositoryDropped: (String) -> Unit, -) { - - fun attach() { - ViewCompat.setOnReceiveContentListener( - rootView, - supportedDropMimeTypes, - ) { _, payload -> tryConsumeRepositoryPayload(payload) } - - bindRepositoryDropTarget(rootView) - } - - fun detach() { - ViewCompat.setOnReceiveContentListener(rootView, null, null) - rootView.setOnDragListener(null) - } - - /** - * Attempts to consume a dropped repository URL from the given [payload]. - * Returns `null` on success to indicate consumption, or the original [payload] otherwise. - */ - private fun tryConsumeRepositoryPayload(payload: ContentInfoCompat): ContentInfoCompat? { - if (!shouldAcceptDrop()) { - return payload - } - - val repositoryUrl = extractRepositoryUrl(payload) ?: return payload - - onRepositoryDropped(repositoryUrl) - return null - } - - private fun bindRepositoryDropTarget(view: View) { - val dropCallback = object : DropTargetCallback { - override fun canAcceptDrop(event: DragEvent): Boolean { - return shouldAcceptDrop() && event.clipDescription.isSupportedDropPayload() - } - - override fun onDragStarted(view: View) { - DropHighlighter.highlight(view, context) - } - - override fun onDragEntered(view: View) { - DropHighlighter.highlight(view, context) - } - - override fun onDragExited(view: View) { - DropHighlighter.clear(view) - } - - override fun onDrop(event: DragEvent): Boolean { - val contentInfo = ContentInfoCompat.Builder( - event.clipData, - ContentInfoCompat.SOURCE_DRAG_AND_DROP, - ).build() - - return ViewCompat.performReceiveContent(view, contentInfo) == null - } - } - - view.setOnDragListener(DragEventRouter(dropCallback)) - } - - private fun extractRepositoryUrl(payload: ContentInfoCompat): String? { - val clip = payload.clip - for (index in 0 until clip.itemCount) { - val item = clip.getItemAt(index) - val text = item.uri?.toString() ?: item.coerceToText(context)?.toString() - - if (text.isNullOrBlank()) continue - - parseGitRepositoryUrl(text)?.let { return it } - } - - return null - } - - private fun ClipDescription?.isSupportedDropPayload(): Boolean { - if (this == null) { - return false - } - - return supportedDropMimeTypes.any(::hasMimeType) - } - - private companion object { - val supportedDropMimeTypes = arrayOf( - ClipDescription.MIMETYPE_TEXT_PLAIN, - ClipDescription.MIMETYPE_TEXT_URILIST, - ) - } -} diff --git a/app/src/main/java/com/itsaky/androidide/editor/floating/ChromeControlTooltips.kt b/app/src/main/java/com/itsaky/androidide/editor/floating/ChromeControlTooltips.kt deleted file mode 100644 index 43a32c64c8..0000000000 --- a/app/src/main/java/com/itsaky/androidide/editor/floating/ChromeControlTooltips.kt +++ /dev/null @@ -1,24 +0,0 @@ - -package com.itsaky.androidide.editor.floating - -import android.view.View -import com.itsaky.androidide.floating.model.ChromeControl -import com.itsaky.androidide.idetooltips.TooltipCategory -import com.itsaky.androidide.idetooltips.TooltipManager -import com.itsaky.androidide.idetooltips.TooltipTag - -object ChromeControlTooltips { - val handler: (ChromeControl, View) -> Unit = { control, anchor -> - tagFor(control)?.let { tag -> - TooltipManager.showTooltip(anchor.context, anchor, TooltipCategory.CATEGORY_IDE, tag) - } - } - - private fun tagFor(control: ChromeControl): String? = - when (control) { - ChromeControl.MINIMIZE -> TooltipTag.WINDOW_MINIMIZE - ChromeControl.MAXIMIZE -> TooltipTag.WINDOW_MAXIMIZE - ChromeControl.DOCK -> TooltipTag.WINDOW_DOCK - ChromeControl.CLOSE -> TooltipTag.WINDOW_CLOSE - } -} diff --git a/app/src/main/java/com/itsaky/androidide/events/FileTree.kt b/app/src/main/java/com/itsaky/androidide/events/FileTree.kt deleted file mode 100644 index 3b4a5e9141..0000000000 --- a/app/src/main/java/com/itsaky/androidide/events/FileTree.kt +++ /dev/null @@ -1,30 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.events - -import com.itsaky.androidide.eventbus.events.Event -import com.itsaky.androidide.models.SheetOption -import com.unnamed.b.atv.model.TreeNode - -internal data class FileContextMenuItemClickEvent(val option: SheetOption) : Event() -internal data class FileContextMenuItemLongClickEvent(val option: SheetOption) : Event() - -data class ExpandTreeNodeRequestEvent(val node: TreeNode) : Event() -data class CollapseTreeNodeRequestEvent(val node: TreeNode, val includeSubnodes: Boolean) : Event() - -class ListProjectFilesRequestEvent : Event() diff --git a/app/src/main/java/com/itsaky/androidide/events/PluginLanguagesChangedEvent.kt b/app/src/main/java/com/itsaky/androidide/events/PluginLanguagesChangedEvent.kt deleted file mode 100644 index f6bda67fd9..0000000000 --- a/app/src/main/java/com/itsaky/androidide/events/PluginLanguagesChangedEvent.kt +++ /dev/null @@ -1,5 +0,0 @@ -package com.itsaky.androidide.events - -import com.itsaky.androidide.eventbus.events.Event - -class PluginLanguagesChangedEvent : Event() diff --git a/app/src/main/java/com/itsaky/androidide/fragments/CloneRepositoryFragment.kt b/app/src/main/java/com/itsaky/androidide/fragments/CloneRepositoryFragment.kt deleted file mode 100644 index 1446e3586e..0000000000 --- a/app/src/main/java/com/itsaky/androidide/fragments/CloneRepositoryFragment.kt +++ /dev/null @@ -1,244 +0,0 @@ -package com.itsaky.androidide.fragments - -import android.os.Bundle -import android.view.LayoutInflater -import android.view.View -import android.view.ViewGroup -import android.widget.EditText -import androidx.core.widget.doAfterTextChanged -import org.koin.androidx.viewmodel.ext.android.activityViewModel -import androidx.lifecycle.Lifecycle -import androidx.lifecycle.lifecycleScope -import androidx.lifecycle.repeatOnLifecycle -import com.google.android.material.button.MaterialButton -import com.google.android.material.textfield.TextInputLayout -import com.itsaky.androidide.activities.MainActivity -import com.itsaky.androidide.databinding.FragmentCloneRepositoryBinding -import com.itsaky.androidide.viewmodel.CloneRepositoryViewModel -import com.itsaky.androidide.viewmodel.MainViewModel -import com.itsaky.androidide.git.core.models.CloneRepoUiState -import com.itsaky.androidide.R -import com.itsaky.androidide.dnd.handleGitUrlDrop -import com.itsaky.androidide.idetooltips.TooltipManager -import com.itsaky.androidide.idetooltips.TooltipTag -import com.itsaky.androidide.utils.flashError -import com.itsaky.androidide.utils.flashInfo -import com.itsaky.androidide.utils.forEachViewRecursively -import kotlinx.coroutines.launch -import org.koin.androidx.viewmodel.ext.android.viewModel -import java.io.File - -class CloneRepositoryFragment : BaseFragment() { - - private var binding: FragmentCloneRepositoryBinding? = null - private val viewModel: CloneRepositoryViewModel by viewModel() - private val mainViewModel: MainViewModel by activityViewModel() - private var lastStatusResId: Int? = null - - override fun onCreateView( - inflater: LayoutInflater, - container: ViewGroup?, - savedInstanceState: Bundle? - ): View? { - binding = FragmentCloneRepositoryBinding.inflate(inflater, container, false) - return binding?.root - } - - override fun onViewCreated(view: View, savedInstanceState: Bundle?) { - super.onViewCreated(view, savedInstanceState) - - setupUI() - observePendingCloneUrl() - observeViewModel() - handleGitUrlDrop { url -> - binding?.repoUrl?.setText(url) - viewModel.onInputChanged(url, binding?.localPath?.text?.toString().orEmpty()) - } - } - - private fun setupUI() { - binding?.apply { - - repoUrl.doAfterTextChanged { - viewModel.onInputChanged(it.toString(), localPath.text.toString()) - } - - localPath.apply { - doAfterTextChanged { - viewModel.onInputChanged(repoUrl.text.toString(), it.toString()) - } - } - - localPathLayout.setEndIconOnClickListener { - pickDirectory { file -> - val url = repoUrl.text.toString().trim() - var projectName = url.substringAfterLast("/", "") - if (projectName.endsWith(".git")) { - projectName = projectName.dropLast(4) - } - - val destFile = if (projectName.isNotBlank()) { - File(file, projectName) - } else { - file - } - - localPath.setText(destFile.absolutePath) - } - } - - authCheckbox.setOnCheckedChangeListener { _, isChecked -> - authGroup.visibility = if (isChecked) View.VISIBLE else View.GONE - } - - cloneButton.setOnClickListener { - cloneRepo() - } - - cancelButton.setOnClickListener { - viewModel.cancelClone() - } - - exitButton.setOnClickListener { - mainViewModel.setScreen(MainViewModel.SCREEN_MAIN) - } - - root.forEachViewRecursively { child -> - if (child is EditText || child is TextInputLayout) { - return@forEachViewRecursively - } - child.setOnLongClickListener { v -> - TooltipManager.showIdeCategoryTooltip( - context = requireContext(), - anchorView = v, - tag = TooltipTag.GIT_DOWNLOAD_SCREEN - ) - true - } - } - } - } - - private fun FragmentCloneRepositoryBinding.cloneRepo() { - val url = repoUrl.text.toString() - val path = localPath.text.toString() - val mUsername = if (authCheckbox.isChecked) username.text.toString() else null - val mPassword = if (authCheckbox.isChecked) password.text.toString() else null - - viewModel.cloneRepository(url, path, mUsername, mPassword) - } - - private fun observeViewModel() { - viewLifecycleOwner.lifecycleScope.launch { - viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) { - viewModel.uiState.collect { state -> - binding?.apply { - val isLoading = state is CloneRepoUiState.Cloning - repoUrl.isEnabled = !isLoading - localPath.isEnabled = !isLoading - username.isEnabled = !isLoading - password.isEnabled = !isLoading - - progressBar.apply { - visibility = if (isLoading) View.VISIBLE else View.GONE - if (state is CloneRepoUiState.Cloning) { - progress = state.clonePercentage - } - } - - progressText.apply { - if (state is CloneRepoUiState.Cloning && state.cloneProgress.isNotEmpty()) { - visibility = View.VISIBLE - text = state.cloneProgress - } else { - visibility = View.GONE - } - } - - cancelButton.visibility = - if (state is CloneRepoUiState.Cloning && state.isCancellable) View.VISIBLE else View.GONE - - when (state) { - is CloneRepoUiState.Idle -> { - cloneButton.apply { - isEnabled = state.isCloneButtonEnabled - refreshStatus(isForRetry = false) - } - lastStatusResId = null - } - - is CloneRepoUiState.Cloning -> { - cloneButton.apply { - isEnabled = false - refreshStatus(isForRetry = false) - } - - if (state.statusTextResId != lastStatusResId) { - lastStatusResId = state.statusTextResId - val message = state.statusTextResId?.let { getString(it) } - ?: getString(R.string.cloning_repo) - flashInfo(message) - } - } - - is CloneRepoUiState.Error -> { - cloneButton.apply { - isEnabled = true - refreshStatus(isForRetry = state.canRetry) - } - val statusMessage = - state.errorResId?.let { getString(it) } ?: state.errorMessage - flashError(statusMessage) - } - - is CloneRepoUiState.Success -> { - cloneButton.isEnabled = true - flashInfo(getString(R.string.clone_successful)) - val destDir = File(state.localPath) - if (destDir.exists()) { - mainViewModel.setScreen(MainViewModel.SCREEN_MAIN) - (requireActivity() as? MainActivity)?.openProject(destDir) - - // Reset state after opening project - repoUrl.text?.clear() - localPath.text?.clear() - username.text?.clear() - password.text?.clear() - authCheckbox.isChecked = false - viewModel.resetState() - } - } - } - } - } - } - } - } - - private fun observePendingCloneUrl() { - viewLifecycleOwner.lifecycleScope.launch { - viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) { - mainViewModel.cloneRepositoryEvent.collect { url -> - val trimmedUrl = url.trim() - if (trimmedUrl.isNotBlank()) { - binding?.repoUrl?.setText(trimmedUrl) - viewModel.onInputChanged(trimmedUrl, binding?.localPath?.text?.toString().orEmpty()) - } - } - } - } - } - - private fun MaterialButton.refreshStatus(isForRetry: Boolean) { - setIconResource(if (isForRetry) R.drawable.ic_refresh else 0) - - text = context.getString( - if (isForRetry) R.string.retry else R.string.clone_project - ) - } - - override fun onDestroyView() { - super.onDestroyView() - binding = null - } -} diff --git a/app/src/main/java/com/itsaky/androidide/fragments/CrashReportFragment.kt b/app/src/main/java/com/itsaky/androidide/fragments/CrashReportFragment.kt deleted file mode 100644 index 2799800418..0000000000 --- a/app/src/main/java/com/itsaky/androidide/fragments/CrashReportFragment.kt +++ /dev/null @@ -1,169 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ -package com.itsaky.androidide.fragments - -import android.content.Context -import android.content.Intent -import android.net.Uri -import android.os.Bundle -import android.text.SpannableString -import android.text.Spanned -import android.text.TextPaint -import android.text.method.LinkMovementMethod -import android.text.style.ClickableSpan -import android.view.LayoutInflater -import android.view.View -import android.view.ViewGroup -import android.widget.TextView -import androidx.activity.OnBackPressedCallback -import androidx.core.content.ContextCompat -import androidx.core.net.toUri -import androidx.fragment.app.Fragment -import com.itsaky.androidide.databinding.LayoutCrashReportBinding -import com.itsaky.androidide.resources.R -import com.itsaky.androidide.utils.BasicBuildInfo -import com.itsaky.androidide.utils.resolveAttr - -class CrashReportFragment : Fragment() { - - private var _binding: LayoutCrashReportBinding? = null - private val binding get() = _binding!! - - private var closeAppOnClick = true - - companion object { - const val KEY_CLOSE_APP_ON_CLICK = "close_on_app_click" - - @JvmStatic - fun newInstance(): CrashReportFragment { - return newInstance(true) - } - - @JvmStatic - fun newInstance( - closeAppOnClick: Boolean - ): CrashReportFragment { - val frag = CrashReportFragment() - val args = Bundle().apply { - putBoolean(KEY_CLOSE_APP_ON_CLICK, closeAppOnClick) - } - frag.arguments = args - return frag - } - } - - override fun onCreateView( - inflater: LayoutInflater, - container: ViewGroup?, - savedInstanceState: Bundle? - ): View { - _binding = LayoutCrashReportBinding.inflate(inflater, container, false) - return binding.root - } - - override fun onViewCreated(view: View, savedInstanceState: Bundle?) { - super.onViewCreated(view, savedInstanceState) - val args = requireArguments() - closeAppOnClick = args.getBoolean(KEY_CLOSE_APP_ON_CLICK) - val title = getString(R.string.msg_ide_crashed) - - binding.apply { - crashTitle.text = title - crashSubtitle.apply { - setCrashInfoText() - } - - closeButton.setOnClickListener { - finishActivity() - } - - btnOkay.setOnClickListener { finishActivity() } - - requireActivity().onBackPressedDispatcher.addCallback( - viewLifecycleOwner, - object : OnBackPressedCallback(true) { - override fun handleOnBackPressed() { - finishActivity() - } - } - ) - - } - } - - fun TextView.setCrashInfoText() { - // Get crash message with placeholder - val supportText = context.getString(R.string.contact_support_team) - val fullText = context.getString(R.string.msg_crash_info, supportText) - val linkColor = requireContext().resolveAttr(com.itsaky.androidide.R.attr.colorOnSurface) - val spannable = SpannableString(fullText) - - // Find clickable phrase in text - val start = fullText.indexOf(supportText) - if (start != -1) { - spannable.setSpan( - object : ClickableSpan() { - override fun onClick(widget: View) { - sendEmail(context = context) - - } - - override fun updateDrawState(ds: TextPaint) { - super.updateDrawState(ds) - ds.color = linkColor - ds.isUnderlineText = true - } - }, - start, - start + supportText.length, - Spanned.SPAN_EXCLUSIVE_EXCLUSIVE - ) - } - - text = spannable - movementMethod = LinkMovementMethod.getInstance() - } - - private fun sendEmail(context: Context) { - val email = "feedback@appdevforall.org" - val subject = Uri.encode(context.getString(R.string.crash_email_subject)) - val body = Uri.encode( - context.getString( - R.string.crash_email_body, - BasicBuildInfo.formatVersion() - ) - ) - - val uri = "mailto:$email?subject=$subject&body=$body".toUri() - - val intent = Intent(Intent.ACTION_SENDTO, uri) - context.startActivity(intent) - } - - private fun finishActivity() { - if (closeAppOnClick) { - requireActivity().finishAffinity() - } else { - requireActivity().finish() - } - } - - override fun onDestroyView() { - super.onDestroyView() - _binding = null - } -} \ No newline at end of file diff --git a/app/src/main/java/com/itsaky/androidide/fragments/TemplateListFragment.kt b/app/src/main/java/com/itsaky/androidide/fragments/TemplateListFragment.kt deleted file mode 100644 index d2e3c3b50f..0000000000 --- a/app/src/main/java/com/itsaky/androidide/fragments/TemplateListFragment.kt +++ /dev/null @@ -1,170 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.fragments - -import android.os.Bundle -import android.view.View -import android.content.res.Configuration -import androidx.lifecycle.lifecycleScope -import org.koin.androidx.viewmodel.ext.android.activityViewModel -import androidx.recyclerview.widget.GridLayoutManager -import com.itsaky.androidide.R -import com.itsaky.androidide.adapters.TemplateListAdapter -import com.itsaky.androidide.databinding.FragmentTemplateListBinding -import com.itsaky.androidide.idetooltips.TooltipManager -import com.itsaky.androidide.idetooltips.TooltipTag.EXIT_TO_MAIN -import com.itsaky.androidide.templates.ITemplateProvider -import com.itsaky.androidide.templates.ITemplateWidgetViewProvider -import com.itsaky.androidide.templates.ProjectTemplate -import com.itsaky.androidide.templates.impl.TemplateProviderImpl -import com.itsaky.androidide.utils.flashError -import com.itsaky.androidide.viewmodel.MainViewModel -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.Job -import kotlinx.coroutines.launch -import kotlinx.coroutines.withContext -import org.slf4j.LoggerFactory - -/** - * A fragment to show the list of available templates. - * - * @author Akash Yadav - */ -class TemplateListFragment : - FragmentWithBinding( - R.layout.fragment_template_list, - FragmentTemplateListBinding::bind, - ) { - private var adapter: TemplateListAdapter? = null - private var reloadJob: Job? = null - - private val viewModel by activityViewModel() - - companion object { - private val log = LoggerFactory.getLogger(TemplateListFragment::class.java) - } - - override fun onViewCreated( - view: View, - savedInstanceState: Bundle?, - ) { - super.onViewCreated(view, savedInstanceState) - - val gridLayoutManager = GridLayoutManager(requireContext(), 1) - binding.list.layoutManager = gridLayoutManager - - binding.exitButton.setOnClickListener { - viewModel.setScreen(MainViewModel.SCREEN_MAIN) - } - - binding.exitButton.setOnLongClickListener { - TooltipManager.showIdeCategoryTooltip( - context = requireContext(), - anchorView = binding.root, - tag = EXIT_TO_MAIN, - ) - true - } - - viewModel.currentScreen.observe(viewLifecycleOwner) { current -> - if (current == MainViewModel.SCREEN_TEMPLATE_DETAILS) { - return@observe - } - - reloadTemplates() - } - } - - override fun onConfigurationChanged(newConfig: Configuration) { - super.onConfigurationChanged(newConfig) - - updateSpanCount() - } - - override fun onResume() { - super.onResume() - updateSpanCount() - } - - private fun updateSpanCount() { - val isLandscape = resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE - val maxSpans = if (isLandscape) 6 else 4 - - val itemCount = binding.list.adapter?.itemCount ?: 0 - - val optimalSpans = maxOf(1, minOf(maxSpans, itemCount)) - - val layoutManager = binding.list.layoutManager as? GridLayoutManager - if (layoutManager != null && layoutManager.spanCount != optimalSpans) { - layoutManager.spanCount = optimalSpans - } - } - - override fun onDestroyView() { - super.onDestroyView() - } - - private fun reloadTemplates() { - _binding ?: return - - log.debug("Reloading templates...") - - reloadJob?.cancel() - reloadJob = viewLifecycleOwner.lifecycleScope.launch { - val (templates, warnings) = withContext(Dispatchers.IO) { - val provider = ITemplateProvider.getInstance(reload = true) - // Pre-warm the widget view provider so per-bind getInstance() in - // TemplateWidgetsListAdapter doesn't trigger a disk read on the UI thread. - ITemplateWidgetViewProvider.getInstance() - val templates = provider.getTemplates().filterIsInstance() - val warnings = (provider as? TemplateProviderImpl)?.warnings.orEmpty() - templates to warnings - } - - _binding ?: return@launch - - adapter = - TemplateListAdapter( - templates = templates, - onClick = { template, _ -> - viewModel.template.value = template - viewModel.setScreen(MainViewModel.SCREEN_TEMPLATE_DETAILS) - }, - onLongClick = { template, itemView -> - template.tooltipTag?.let { tag -> - TooltipManager.showIdeCategoryTooltip( - context = requireContext(), - anchorView = itemView, - tag = tag - ) - } - }, - ) - binding.list.adapter = adapter - updateSpanCount() - - if (warnings.isNotEmpty()) { - requireActivity().flashError( - warnings.joinToString(System.lineSeparator()) { w -> - requireContext().getString(w.resId, *w.args.toTypedArray()) - } - ) - } - } - } -} diff --git a/app/src/main/java/com/itsaky/androidide/fragments/debug/DisplayableUtils.kt b/app/src/main/java/com/itsaky/androidide/fragments/debug/DisplayableUtils.kt deleted file mode 100644 index bfb430bc90..0000000000 --- a/app/src/main/java/com/itsaky/androidide/fragments/debug/DisplayableUtils.kt +++ /dev/null @@ -1,8 +0,0 @@ -package com.itsaky.androidide.fragments.debug - -import com.itsaky.androidide.lsp.debug.model.StackFrameDescriptor -import com.itsaky.androidide.lsp.debug.model.ThreadDescriptor - -fun ThreadDescriptor.displayText(): String = toString() - -fun StackFrameDescriptor.displayText(): String = method diff --git a/app/src/main/java/com/itsaky/androidide/fragments/debug/Resolvable.kt b/app/src/main/java/com/itsaky/androidide/fragments/debug/Resolvable.kt deleted file mode 100644 index 46cf9f1972..0000000000 --- a/app/src/main/java/com/itsaky/androidide/fragments/debug/Resolvable.kt +++ /dev/null @@ -1,236 +0,0 @@ -package com.itsaky.androidide.fragments.debug - -import com.itsaky.androidide.lsp.debug.model.StackFrame -import com.itsaky.androidide.lsp.debug.model.StackFrameDescriptor -import com.itsaky.androidide.lsp.debug.model.ThreadDescriptor -import com.itsaky.androidide.lsp.debug.model.ThreadInfo -import com.itsaky.androidide.lsp.debug.model.Value -import com.itsaky.androidide.lsp.debug.model.Variable -import com.itsaky.androidide.lsp.debug.model.VariableDescriptor -import com.itsaky.androidide.lsp.debug.model.VariableKind -import com.itsaky.androidide.lsp.java.utils.completedOrNull -import com.itsaky.androidide.lsp.java.utils.getValue -import kotlinx.coroutines.CompletableDeferred -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Deferred -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.ExperimentalCoroutinesApi -import kotlinx.coroutines.withContext -import org.slf4j.Logger -import org.slf4j.LoggerFactory - -interface Resolvable { - - /** - * Whether the value is resolved. - */ - val isResolved: Boolean - - /** - * Get the resolved value, or throw an exception if the value is not resolved. - */ - val resolved: T - - /** - * Resolve the value. - */ - suspend fun resolve(): T? -} - -abstract class AbstractResolvable : Resolvable { - - private val _deferred = CompletableDeferred() - - val deferred: Deferred - get() = _deferred - - @OptIn(ExperimentalCoroutinesApi::class) - override val isResolved: Boolean - get() = deferred.completedOrNull != null - - companion object { - @JvmStatic - protected val logger: Logger = LoggerFactory.getLogger(AbstractResolvable::class.java) - private val resolutionDispatcher = Dispatchers.IO - } - - @OptIn(ExperimentalCoroutinesApi::class) - final override suspend fun resolve(): T? { - deferred.completedOrNull?.also { completed -> - // already resolved - return completed - } - - val result = withContext(resolutionDispatcher) { - try { - doResolve()?.also(_deferred::complete) - } catch (err: Throwable) { - logger.error("Resolution failure", err) - _deferred.completeExceptionally(err) - null - } - } - - return result - } - - protected suspend fun withContext(action: suspend CoroutineScope.() -> T): T = - withContext(resolutionDispatcher, action) - - protected abstract suspend fun doResolve(): T -} - -/** - * Get the resolved value, or return `null` if the value is not resolved. - */ -val Resolvable.resolvedOrNull: T? - get() = if (isResolved) resolved else null - -/** - * Get the resolved value, or return [default value][default] if the value is not resolved. - * - * @param default The default value to return if the value is not resolved. - */ -fun Resolvable.resolvedOr(default: T): T? = if (isResolved) resolved else default - -/** - * A [variable][Variable] that is eagerly resolved. - * - * @author Akash Yadav - */ -@OptIn(ExperimentalCoroutinesApi::class) -class ResolvableVariable private constructor( - private val delegate: Variable, -) : AbstractResolvable(), Variable by delegate, Resolvable { - - internal val deferredValue = CompletableDeferred() - - /** - * Whether the variable is resolved. - */ - override val isResolved: Boolean - get() = super.isResolved && deferredValue.completedOrNull != null - - override val resolved: VariableDescriptor - get() = checkNotNull(deferred.completedOrNull) { - "Variable is not resolved" - } - - fun resolvedName() = deferred.completedOrNull?.name ?: "" - - fun resolvedTypeName() = deferred.completedOrNull?.typeName ?: "" - - fun resolvedValue() = deferredValue.getValue( - defaultValue = null, - ) - - fun resolvedKind(): VariableKind = deferred.completedOrNull?.kind ?: VariableKind.UNKNOWN - - companion object { - - private val logger = LoggerFactory.getLogger(ResolvableVariable::class.java) - - /** - * Create a new eagerly-resolved variable delegating to [delegate]. - * - * @param delegate The delegate variable. - * @return The new eagerly-resolved variable. - */ - fun create(delegate: Variable): ResolvableVariable { - if (delegate is ResolvableVariable) { - return delegate - } - - return ResolvableVariable(delegate) - } - } - - /** - * Resolve the variable state. - */ - override suspend fun doResolve(): VariableDescriptor { - // NOTE: - // Care must be taken to only resolve values which are absolutely needed - // to render the UI. Resolution of values which are not immediately required must be deferred. - - val descriptor = delegate.descriptor() - val value = delegate.value() - deferredValue.complete(value) - return descriptor - } - - override suspend fun objectMembers(): Set> = withContext { - delegate.objectMembers() - .map { variable -> - // members of an eagerly-resolved variable are also eagerly-resolved - create(variable) - }.toSet() - } -} - -/** - * @author Akash Yadav - */ -@OptIn(ExperimentalCoroutinesApi::class) -class ResolvableStackFrame private constructor( - private val delegate: StackFrame, -) : AbstractResolvable(), StackFrame by delegate, Resolvable { - - override val resolved: StackFrameDescriptor - get() = checkNotNull(deferred.completedOrNull) { - "Stack frame is not resolved" - } - - companion object { - - /** - * Create a new eagerly-resolved stack frame delegating to [delegate]. - */ - fun create(delegate: StackFrame): ResolvableStackFrame { - if (delegate is ResolvableStackFrame) { - return delegate - } - - return ResolvableStackFrame(delegate) - } - } - - override suspend fun doResolve(): StackFrameDescriptor { - return delegate.descriptor() - } - - override suspend fun getVariables(): List> = - delegate.getVariables().map { variable -> ResolvableVariable.create(variable) } -} - -@OptIn(ExperimentalCoroutinesApi::class) -class ResolvableThreadInfo private constructor( - private val delegate: ThreadInfo, -) : AbstractResolvable(), ThreadInfo by delegate, Resolvable { - - override val resolved: ThreadDescriptor - get() = checkNotNull(deferred.completedOrNull) { - "Thread is not resolved" - } - - companion object { - - /** - * Create a new eagerly-resolved thread info delegating to [delegate]. - */ - fun create(delegate: ThreadInfo): ResolvableThreadInfo { - if (delegate is ResolvableThreadInfo) { - return delegate - } - - return ResolvableThreadInfo(delegate) - } - } - - override suspend fun doResolve(): ThreadDescriptor { - return delegate.descriptor() - } - - override suspend fun getFrames(): List = - delegate.getFrames().map { frame -> ResolvableStackFrame.create(frame) } -} diff --git a/app/src/main/java/com/itsaky/androidide/fragments/debug/VariableIcon.kt b/app/src/main/java/com/itsaky/androidide/fragments/debug/VariableIcon.kt deleted file mode 100644 index 57c57b461c..0000000000 --- a/app/src/main/java/com/itsaky/androidide/fragments/debug/VariableIcon.kt +++ /dev/null @@ -1,63 +0,0 @@ -package com.itsaky.androidide.fragments.debug - -import android.content.res.Resources -import android.graphics.Canvas -import android.graphics.Color -import android.graphics.ColorFilter -import android.graphics.Paint -import android.graphics.PixelFormat -import android.graphics.drawable.Drawable -import androidx.core.graphics.withTranslation - -/** - * @author Akash Yadav - */ -class CircleCharDrawable( - private val char: Char, - private val circle: Boolean -) : - Drawable() { - private val mPaint = Paint().apply { - isAntiAlias = true - color = Color.TRANSPARENT - } - - private val mTextPaint = Paint().apply { - color = -0x1 - isAntiAlias = true - textSize = Resources.getSystem() - .displayMetrics.density * 14 - textAlign = Paint.Align.CENTER - } - - override fun draw(canvas: Canvas) { - val width = bounds.right.toFloat() - val height = bounds.bottom.toFloat() - if (circle) { - canvas.drawCircle(width / 2, height / 2, width / 2, mPaint) - } else { - canvas.drawRect(0f, 0f, width, height, mPaint) - } - canvas.withTranslation(width / 2f, height / 2f) { - val textCenter = -(mTextPaint.descent() + mTextPaint.ascent()) / 2f - drawText(char.toString(), 0f, textCenter, mTextPaint) - } - } - - override fun setAlpha(p1: Int) { - mPaint.alpha = p1 - mTextPaint.alpha = p1 - } - - override fun setColorFilter(colorFilter: ColorFilter?) { - mTextPaint.colorFilter = colorFilter - } - - @Deprecated( - "Deprecated in Java", - ReplaceWith("PixelFormat.OPAQUE", "android.graphics.PixelFormat") - ) - override fun getOpacity(): Int { - return PixelFormat.OPAQUE - } -} \ No newline at end of file diff --git a/app/src/main/java/com/itsaky/androidide/fragments/debug/VariableTreeNodeGenerator.kt b/app/src/main/java/com/itsaky/androidide/fragments/debug/VariableTreeNodeGenerator.kt deleted file mode 100644 index 8f1e632cc7..0000000000 --- a/app/src/main/java/com/itsaky/androidide/fragments/debug/VariableTreeNodeGenerator.kt +++ /dev/null @@ -1,50 +0,0 @@ -package com.itsaky.androidide.fragments.debug - -import io.github.dingyi222666.view.treeview.AbstractTree -import io.github.dingyi222666.view.treeview.Tree -import io.github.dingyi222666.view.treeview.TreeNode -import io.github.dingyi222666.view.treeview.TreeNodeGenerator - -class VariableTreeNodeGenerator private constructor( - private val rootNodes: Set> = emptySet() -) : TreeNodeGenerator> { - - companion object { - fun newInstance( - rootNodes: Set> = emptySet() - ): TreeNodeGenerator> = VariableTreeNodeGenerator(rootNodes) - } - - override fun createNode( - parentNode: TreeNode>, - currentData: ResolvableVariable<*>, - tree: AbstractTree> - ): TreeNode> = TreeNode( - id = Tree.generateId(), - data = currentData, - depth = parentNode.depth + 1, - name = currentData.resolvedOrNull?.name ?: "", - isExpanded = false, - isBranch = true, - ) - - override suspend fun fetchChildData(targetNode: TreeNode>): Set> { - if (targetNode.id == Tree.ROOT_NODE_ID) { - return rootNodes - } - - val data = targetNode.data ?: return emptySet() - return data.objectMembers() - } - - override fun createRootNode(): TreeNode> { - return TreeNode( - id = Tree.ROOT_NODE_ID, - data = null, - depth = -1, - name = Tree.ROOT_NODE_ID.toString(), - isExpanded = true, - isBranch = false, - ) - } -} \ No newline at end of file diff --git a/app/src/main/java/com/itsaky/androidide/fragments/git/GitDialogUtils.kt b/app/src/main/java/com/itsaky/androidide/fragments/git/GitDialogUtils.kt deleted file mode 100644 index 990aa38b69..0000000000 --- a/app/src/main/java/com/itsaky/androidide/fragments/git/GitDialogUtils.kt +++ /dev/null @@ -1,53 +0,0 @@ -package com.itsaky.androidide.fragments.git - -import androidx.appcompat.app.AlertDialog -import androidx.core.widget.doAfterTextChanged -import androidx.fragment.app.Fragment -import com.google.android.material.dialog.MaterialAlertDialogBuilder -import com.itsaky.androidide.R -import com.itsaky.androidide.databinding.DialogGitCredentialsBinding -import com.itsaky.androidide.git.core.GitCredentialsManager - -fun Fragment.showGitCredentialsDialog( - credentialsManager: GitCredentialsManager, - positiveButtonTextResId: Int, - onPositiveClick: (username: String, token: String) -> Unit -) { - val dialogBinding = DialogGitCredentialsBinding.inflate(layoutInflater) - - dialogBinding.username.setText(credentialsManager.getUsername()) - dialogBinding.token.setText(credentialsManager.getToken()) - - val dialog = MaterialAlertDialogBuilder(requireContext()) - .setTitle(R.string.git_credentials_title) - .setView(dialogBinding.root) - .setPositiveButton(positiveButtonTextResId) { _, _ -> - val username = dialogBinding.username.text?.toString()?.trim() - val token = dialogBinding.token.text?.toString()?.trim() - if (!username.isNullOrBlank() && !token.isNullOrBlank()) { - onPositiveClick(username, token) - } - } - .setNeutralButton(R.string.git_credentials_clear) { _, _ -> - credentialsManager.clearCredentials() - } - .setNegativeButton(android.R.string.cancel, null) - .create() - - dialog.setOnShowListener { - val positiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE) - - val validate = { - val user = dialogBinding.username.text?.toString()?.trim() - val token = dialogBinding.token.text?.toString()?.trim() - positiveButton.isEnabled = !user.isNullOrBlank() && !token.isNullOrBlank() - } - - dialogBinding.username.doAfterTextChanged { validate() } - dialogBinding.token.doAfterTextChanged { validate() } - - validate() - } - - dialog.show() -} diff --git a/app/src/main/java/com/itsaky/androidide/fragments/git/GitDiffViewerDialog.kt b/app/src/main/java/com/itsaky/androidide/fragments/git/GitDiffViewerDialog.kt deleted file mode 100644 index 48ab7bb8de..0000000000 --- a/app/src/main/java/com/itsaky/androidide/fragments/git/GitDiffViewerDialog.kt +++ /dev/null @@ -1,165 +0,0 @@ -package com.itsaky.androidide.fragments.git - -import android.graphics.Canvas -import android.graphics.Paint -import android.os.Bundle -import android.text.SpannableStringBuilder -import android.text.Spanned.SPAN_EXCLUSIVE_EXCLUSIVE -import android.text.style.ForegroundColorSpan -import android.text.style.LineBackgroundSpan -import android.view.LayoutInflater -import android.view.View -import android.view.ViewGroup -import androidx.core.content.ContextCompat.getColor -import androidx.fragment.app.DialogFragment -import androidx.lifecycle.lifecycleScope -import com.itsaky.androidide.R -import com.itsaky.androidide.databinding.DialogGitDiffBinding -import com.itsaky.androidide.viewmodel.GitBottomSheetViewModel -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.launch -import kotlinx.coroutines.withContext -import org.koin.androidx.viewmodel.ext.android.activityViewModel -import java.io.File - -class GitDiffViewerDialog : DialogFragment() { - - private val viewModel: GitBottomSheetViewModel by activityViewModel() - - private var filePath: String = "" - - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setStyle(STYLE_NORMAL, R.style.Theme_AndroidIDE) - filePath = arguments?.getString(ARG_FILE_PATH) ?: getString(R.string.diff_viewer) - } - - override fun onCreateView( - inflater: LayoutInflater, - container: ViewGroup?, - savedInstanceState: Bundle? - ): View { - return inflater.inflate(R.layout.dialog_git_diff, container, false) - } - - override fun onViewCreated(view: View, savedInstanceState: Bundle?) { - super.onViewCreated(view, savedInstanceState) - - val binding = DialogGitDiffBinding.bind(view) - - binding.diffTitle.text = filePath - binding.diffText.text = getString(R.string.diff_loading) - - viewLifecycleOwner.lifecycleScope.launch(Dispatchers.IO) { - val repo = viewModel.currentRepository - val diff = if (repo != null && repo.rootDir.exists()) { - val file = File(repo.rootDir, filePath) - repo.getDiff(file) - } else { - null - } ?: getString(R.string.unable_to_load_diff) - - withContext(Dispatchers.Main) { - binding.diffText.text = applyDiffFormatting(diff) - } - } - - binding.btnClose.setOnClickListener { - dismiss() - } - } - - private fun applyDiffFormatting(diff: String): SpannableStringBuilder { - val builder = SpannableStringBuilder() - val lines = diff.split("\n") - - // Find the index of the first diff chunk (starts with @@) - val firstChunkIndex = lines.indexOfFirst { it.startsWith("@@") } - val startIndex = if (firstChunkIndex != -1) firstChunkIndex else 0 - - val context = requireContext() - val colorAdd = getColor(context, R.color.git_diff_add_text) - val bgAdd = getColor(context, R.color.git_diff_add_bg) - val colorDel = getColor(context, R.color.git_diff_del_text) - val bgDel = getColor(context, R.color.git_diff_del_bg) - val colorHeader = getColor(context, R.color.git_diff_header_text) - - for (i in startIndex until lines.size) { - val line = lines[i] - val startIdx = builder.length - when { - line.startsWith("+") && !line.startsWith("+++") -> { - val formattedLine = line.replaceFirst("+", "+ ") - builder.append(formattedLine).append("\n") - val endIdx = builder.length - - builder.setSpan(ForegroundColorSpan(colorAdd), startIdx, endIdx, - SPAN_EXCLUSIVE_EXCLUSIVE - ) - builder.setSpan(FullWidthBackgroundColorSpan(bgAdd), startIdx, endIdx, - SPAN_EXCLUSIVE_EXCLUSIVE - ) - } - line.startsWith("-") && !line.startsWith("---") -> { - val formattedLine = line.replaceFirst("-", "- ") - builder.append(formattedLine).append("\n") - val endIdx = builder.length - - builder.setSpan(ForegroundColorSpan(colorDel), startIdx, endIdx, - SPAN_EXCLUSIVE_EXCLUSIVE - ) - builder.setSpan(FullWidthBackgroundColorSpan(bgDel), startIdx, endIdx, - SPAN_EXCLUSIVE_EXCLUSIVE - ) - } - line.startsWith("@@") -> { - builder.append(line).append("\n") - val endIdx = builder.length - - builder.setSpan(ForegroundColorSpan(colorHeader), startIdx, endIdx, - SPAN_EXCLUSIVE_EXCLUSIVE - ) - } - else -> { - val formattedLine = if (line.startsWith(" ")) " $line" else line - builder.append(formattedLine).append("\n") - } - } - } - - return builder - } - - private class FullWidthBackgroundColorSpan(private val color: Int) : LineBackgroundSpan { - override fun drawBackground( - canvas: Canvas, paint: Paint, - left: Int, right: Int, top: Int, baseline: Int, bottom: Int, - text: CharSequence, start: Int, end: Int, lineNumber: Int - ) { - val oldColor = paint.color - paint.color = color - canvas.drawRect(left.toFloat(), top.toFloat(), right.toFloat(), bottom.toFloat(), paint) - paint.color = oldColor - } - } - - override fun onStart() { - super.onStart() - dialog?.window?.setLayout( - ViewGroup.LayoutParams.MATCH_PARENT, - ViewGroup.LayoutParams.MATCH_PARENT - ) - } - - companion object { - private const val ARG_FILE_PATH = "arg_file_path" - - fun newInstance(filePath: String): GitDiffViewerDialog { - return GitDiffViewerDialog().apply { - arguments = Bundle().apply { - putString(ARG_FILE_PATH, filePath) - } - } - } - } -} diff --git a/app/src/main/java/com/itsaky/androidide/fragments/git/adapter/GitCommitHistoryAdapter.kt b/app/src/main/java/com/itsaky/androidide/fragments/git/adapter/GitCommitHistoryAdapter.kt deleted file mode 100644 index 55aeb1108c..0000000000 --- a/app/src/main/java/com/itsaky/androidide/fragments/git/adapter/GitCommitHistoryAdapter.kt +++ /dev/null @@ -1,61 +0,0 @@ -package com.itsaky.androidide.fragments.git.adapter - -import android.view.LayoutInflater -import android.view.View -import android.view.ViewGroup -import androidx.recyclerview.widget.DiffUtil -import androidx.recyclerview.widget.ListAdapter -import androidx.recyclerview.widget.RecyclerView -import com.itsaky.androidide.R -import com.itsaky.androidide.databinding.ItemGitCommitBinding -import com.itsaky.androidide.git.core.models.GitCommit -import java.text.SimpleDateFormat -import java.util.Date -import java.util.Locale - -class GitCommitHistoryAdapter : - ListAdapter(DiffCallback()) { - - override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { - val binding = ItemGitCommitBinding.inflate( - LayoutInflater.from(parent.context), parent, false - ) - return ViewHolder(binding) - } - - override fun onBindViewHolder(holder: ViewHolder, position: Int) { - val commit = getItem(position) - holder.bind(commit) - } - - class ViewHolder(private val binding: ItemGitCommitBinding) : - RecyclerView.ViewHolder(binding.root) { - - private val dateFormat = SimpleDateFormat("dd MMM yyyy, HH:mm", Locale.getDefault()) - - fun bind(commit: GitCommit) { - binding.apply { - tvCommitMessage.text = commit.message - tvCommitAuthor.text = commit.authorName - tvCommitTime.text = dateFormat.format(Date(commit.timestamp)) - imgCommitStatus.setImageResource(if (commit.hasBeenPushed) R.drawable.ic_cloud_done else R.drawable.ic_upload) - imgCommitStatus.contentDescription = if (commit.hasBeenPushed) { - binding.root.context.getString(R.string.commit_pushed) - } else { - binding.root.context.getString(R.string.commit_not_pushed) - } - } - } - } - - class DiffCallback : DiffUtil.ItemCallback() { - override fun areItemsTheSame(oldItem: GitCommit, newItem: GitCommit): Boolean { - return oldItem.hash == newItem.hash - } - - override fun areContentsTheSame(oldItem: GitCommit, newItem: GitCommit): Boolean { - return oldItem == newItem - } - } - -} diff --git a/app/src/main/java/com/itsaky/androidide/fragments/onboarding/IdeSetupConfigurationFragment.kt b/app/src/main/java/com/itsaky/androidide/fragments/onboarding/IdeSetupConfigurationFragment.kt deleted file mode 100644 index 7833257df3..0000000000 --- a/app/src/main/java/com/itsaky/androidide/fragments/onboarding/IdeSetupConfigurationFragment.kt +++ /dev/null @@ -1,303 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.fragments.onboarding - -import android.annotation.SuppressLint -import android.content.BroadcastReceiver -import android.content.Context -import android.content.Intent -import android.content.IntentFilter -import android.net.ConnectivityManager -import android.net.ConnectivityManager.NetworkCallback -import android.net.Network -import android.net.NetworkCapabilities -import android.net.NetworkRequest -import android.os.Build -import android.os.Bundle -import android.provider.Settings -import android.text.Html -import android.text.Spannable -import android.text.SpannableStringBuilder -import android.text.style.URLSpan -import android.view.ViewGroup -import android.widget.ArrayAdapter -import androidx.core.content.getSystemService -import androidx.core.view.isVisible -import org.adfa.constants.ARM_KEY -import org.adfa.constants.V7_KEY -import org.adfa.constants.V8_KEY -import com.github.appintro.SlidePolicy -import com.itsaky.androidide.R -import com.itsaky.androidide.databinding.LayoutOnboardngSetupConfigBinding -import com.itsaky.androidide.models.IdeSetupArgument -import com.itsaky.androidide.resources.R.string -import com.itsaky.androidide.tasks.runOnUiThread -import com.itsaky.androidide.utils.ConnectionInfo -import com.itsaky.androidide.utils.Environment -import com.itsaky.androidide.utils.flashError -import com.itsaky.androidide.utils.getConnectionInfo - -/** - * @author Akash Yadav - */ -class IdeSetupConfigurationFragment : OnboardingFragment(), SlidePolicy { - - private var _content: LayoutOnboardngSetupConfigBinding? = null - private val content: LayoutOnboardngSetupConfigBinding - get() = checkNotNull(_content) { "Fragment has been destroyed" } - - private var backgroundDataRestrictionReceiver: BroadcastReceiver? = null - private var networkStateChangeCallback: NetworkCallback? = null - - companion object { - - @JvmStatic - fun newInstance(context: Context): IdeSetupConfigurationFragment { - return IdeSetupConfigurationFragment().also { - it.arguments = Bundle().apply { - putCharSequence(KEY_ONBOARDING_TITLE, context.getString(R.string.title_install_tools)) - putCharSequence(KEY_ONBOARDING_SUBTITLE, - context.getString(R.string.subtitle_install_tools)) - putCharSequence(KEY_ONBOARDING_EXTRA_INFO, - Html.fromHtml(context.getString(R.string.msg_install_tools), - Html.FROM_HTML_MODE_COMPACT)) - } - } - } - } - - @SuppressLint("PrivateResource") - override fun createContentView(parent: ViewGroup, attachToParent: Boolean) { - _content = LayoutOnboardngSetupConfigBinding.inflate(layoutInflater, parent, attachToParent) - - content.apply { - noConnection.root.setText(R.string.msg_no_internet) - cellularConnection.root.setText(R.string.msg_connected_to_cellular) - meteredConnection.root.setText(R.string.msg_connected_to_metered_connection) - backgroundDataRestricted.root.setText(R.string.msg_disable_background_data_restriction) - - sdkVersionLayout.isEnabled = true - jdkVersionLayout.isEnabled = true - installGit.isEnabled = true - installOpenssh.isEnabled = true - - val sdkVersions = SdkVersion.entries.map { "SDK ${it.version}" }.reversed() - sdkVersion.setText(sdkVersions[0]) - sdkVersion.setAdapter(ArrayAdapter( - requireContext(), - com.google.android.material.R.layout.m3_auto_complete_simple_item, - sdkVersions) - ) - - val jdkVersions = JdkVersion.entries.map { "JDK ${it.version}" } - jdkVersion.setText(jdkVersions[0]) - jdkVersion.setAdapter(ArrayAdapter( - requireContext(), - com.google.android.material.R.layout.m3_auto_complete_simple_item, - jdkVersions) - ) - } - - updateConnectionStatus() - } - - fun buildIdeSetupArguments(): Array { - val args = mutableListOf() - // this is unused due to idesetup.sh changes - // I want to keep this as an example in case we will need termux bash scrip arguments in the future. - - args.setArgument(IdeSetupArgument.INSTALL_DIR, Environment.HOME.absolutePath) - args.setArgument(IdeSetupArgument.SDK_VERSION, - SdkVersion.fromDisplayName(content.sdkVersion.text).version) - args.setArgument(IdeSetupArgument.JDK_VERSION, - JdkVersion.fromDisplayName(content.jdkVersion.text).version) - args.setArgument(IdeSetupArgument.ASSUME_YES) - if (content.installGit.isChecked) { - args.setArgument(IdeSetupArgument.WITH_GIT) - } - if (content.installOpenssh.isChecked) { - args.setArgument(IdeSetupArgument.WITH_OPENSSH) - } - args.setArgument(IdeSetupArgument.OFFLINE_MODE, true) - args.setArgument(IdeSetupArgument.CACHE_DIR, "../../cache/apt/archives") - args.setArgument(IdeSetupArgument.ABI_FOLDER, getAbiFolder(Build.SUPPORTED_ABIS[0])) - return args.toTypedArray() - } - - private fun MutableList.setArgument(argument: IdeSetupArgument, value: Any? = null) { - val strVal = value?.toString() ?: "" - if (argument.requiresValue && strVal.isBlank()) { - throw IllegalArgumentException("${argument.name} requires a value") - } - - add(argument.argumentName) - add(strVal) - } - - private fun getAbiFolder(deviceAbi:String) : String { - val abiList = listOf(V8_KEY, V7_KEY, ARM_KEY) // List of substrings to check for - - val index = abiList.indexOfFirst { deviceAbi.contains(it) } - return abiList[index] - } - - override fun onStart() { - super.onStart() - updateConnectionStatus() - monitorNetworkState() - } - - override fun onStop() { - super.onStop() - removeNetworkMonitors() - } - - private fun updateConnectionStatus(networkCapabilities: NetworkCapabilities? = null) = - updateConnectionStatus(getConnectionInfo(requireContext(), networkCapabilities)) - - private fun updateConnectionStatus(connectionInfo: ConnectionInfo) = runOnUiThread { - content.noConnection.root.isVisible = false - content.cellularConnection.root.isVisible = false - content.meteredConnection.root.isVisible = false - content.backgroundDataRestricted.root.isVisible = false - - if (connectionInfo === ConnectionInfo.UNKNOWN || !connectionInfo.isConnected) { - showNoConnectionWarning() - return@runOnUiThread - } - - if (connectionInfo.isCellularTransport) { - addCellularTransportWarning() - } - - if (connectionInfo.isMeteredConnection && !connectionInfo.isCellularTransport) { - addMeteredConnectionWarning() - } - - if (connectionInfo.isBackgroundDataRestricted) { - addBackgroundDataRestrictedWarning() - } - } - - private fun addBackgroundDataRestrictedWarning() { - content.backgroundDataRestricted.root.apply { - setText(R.string.msg_disable_background_data_restriction) - isVisible = true - } - } - - private fun addMeteredConnectionWarning() { - content.meteredConnection.root.apply { - setText(R.string.msg_connected_to_metered_connection) - isVisible = true - } - } - - private fun addCellularTransportWarning() { - content.cellularConnection.root.apply { - setText(R.string.msg_connected_to_cellular) - isVisible = true - } - } - - private fun showNoConnectionWarning() { - val msg = SpannableStringBuilder(getString(R.string.msg_no_internet)) - msg.append(" ") - msg.append(getString(R.string.action_open_settings), URLSpan(""), - Spannable.SPAN_EXCLUSIVE_EXCLUSIVE - ) - - content.noConnection.root.apply { - isVisible = true - setOnClickListener { - it.context.startActivity(Intent(Settings.ACTION_WIFI_SETTINGS)) - } - } - } - - override fun onDestroyView() { - super.onDestroyView() - backgroundDataRestrictionReceiver = null - networkStateChangeCallback = null - } - - override val isPolicyRespected: Boolean - get() = getConnectionInfo(requireContext()).isConnected - - override fun onUserIllegallyRequestedNextPage() { - flashError(string.msg_no_internet) - } - - private fun monitorNetworkState() { - val connectivityManager = requireContext().getSystemService() ?: return - networkStateChangeCallback?.also { - connectivityManager.registerDefaultNetworkCallback(it) - } - - networkStateChangeCallback = object : NetworkCallback() { - - override fun onCapabilitiesChanged( - network: Network, - networkCapabilities: NetworkCapabilities - ) { - updateConnectionStatus(networkCapabilities) - } - - override fun onLost(network: Network) { - updateConnectionStatus(ConnectionInfo.UNKNOWN) - } - } - - val networkRequest = NetworkRequest.Builder() - .addCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED) - .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR) - .addTransportType(NetworkCapabilities.TRANSPORT_ETHERNET) - .addTransportType(NetworkCapabilities.TRANSPORT_WIFI) - .build() - connectivityManager.registerNetworkCallback(networkRequest, networkStateChangeCallback!!) - - backgroundDataRestrictionReceiver?.also { - try { - requireContext().unregisterReceiver(it) - } catch (err: Throwable) { /*ignored*/ - } - } - - backgroundDataRestrictionReceiver = object : BroadcastReceiver() { - override fun onReceive(context: Context?, intent: Intent?) { - updateConnectionStatus() - } - } - - requireContext().registerReceiver(backgroundDataRestrictionReceiver!!, - IntentFilter(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED)) - } - - private fun removeNetworkMonitors() { - networkStateChangeCallback?.also { - requireContext().getSystemService()?.unregisterNetworkCallback(it) - networkStateChangeCallback = null - } - - backgroundDataRestrictionReceiver?.also { - requireContext().unregisterReceiver(it) - backgroundDataRestrictionReceiver = null - } - } - -} \ No newline at end of file diff --git a/app/src/main/java/com/itsaky/androidide/fragments/onboarding/OnboardingFragment.kt b/app/src/main/java/com/itsaky/androidide/fragments/onboarding/OnboardingFragment.kt deleted file mode 100644 index 20d5f65a10..0000000000 --- a/app/src/main/java/com/itsaky/androidide/fragments/onboarding/OnboardingFragment.kt +++ /dev/null @@ -1,70 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.fragments.onboarding - -import android.os.Bundle -import android.view.View -import android.view.ViewGroup -import androidx.core.text.method.LinkMovementMethodCompat -import androidx.core.view.updateLayoutParams -import com.itsaky.androidide.databinding.FragmentOnboardingBinding -import com.itsaky.androidide.fragments.FragmentWithBinding - -open class OnboardingFragment : - FragmentWithBinding(FragmentOnboardingBinding::inflate) { - - companion object { - - const val KEY_ONBOARDING_TITLE = "ide.onboarding.fragment.title" - const val KEY_ONBOARDING_SUBTITLE = "ide.onboarding.fragment.subtitle" - const val KEY_ONBOARDING_EXTRA_INFO = "ide.onboarding.fragment.extraInfo" - - @JvmStatic - fun newInstance(title: CharSequence, subtitle: CharSequence, - extraInfo: CharSequence = ""): OnboardingFragment { - return OnboardingFragment().apply { - arguments = Bundle().apply { - putCharSequence(KEY_ONBOARDING_TITLE, title) - putCharSequence(KEY_ONBOARDING_SUBTITLE, subtitle) - putCharSequence(KEY_ONBOARDING_EXTRA_INFO, extraInfo) - } - } - } - } - - override fun onViewCreated(view: View, savedInstanceState: Bundle?) { - super.onViewCreated(view, savedInstanceState) - binding.onboardingTitle.text = requireArguments().getCharSequence(KEY_ONBOARDING_TITLE) - binding.onboardingSubtitle.text = requireArguments().getCharSequence(KEY_ONBOARDING_SUBTITLE) - - val extraInfo = requireArguments().getCharSequence(KEY_ONBOARDING_EXTRA_INFO, "") - if (extraInfo.isBlank()) { - binding.onboardingExtraInfo.updateLayoutParams { - height = 0 - } - } else { - binding.onboardingExtraInfo.movementMethod = LinkMovementMethodCompat.getInstance() - binding.onboardingExtraInfo.text = extraInfo - } - - binding.contentContainer.removeAllViews() - createContentView(binding.contentContainer, true) - } - - protected open fun createContentView(parent: ViewGroup, attachToParent: Boolean) {} -} \ No newline at end of file diff --git a/app/src/main/java/com/itsaky/androidide/fragments/onboarding/OnboardingInfoFragment.kt b/app/src/main/java/com/itsaky/androidide/fragments/onboarding/OnboardingInfoFragment.kt deleted file mode 100644 index 42c15baa42..0000000000 --- a/app/src/main/java/com/itsaky/androidide/fragments/onboarding/OnboardingInfoFragment.kt +++ /dev/null @@ -1,71 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.fragments.onboarding - -import android.content.res.ColorStateList -import android.os.Bundle -import android.view.View -import androidx.annotation.ColorInt -import androidx.annotation.DrawableRes -import androidx.core.widget.ImageViewCompat -import com.itsaky.androidide.databinding.FragmentOnboardingInfoBinding -import com.itsaky.androidide.fragments.FragmentWithBinding - -/** - * @author Akash Yadav - */ -class OnboardingInfoFragment : - FragmentWithBinding(FragmentOnboardingInfoBinding::inflate) { - - companion object { - - const val KEY_INFO_TEXT = "ide.onboarding.infoFragment.info" - const val KEY_INFO_ICON = "ide.onboarding.infoFragment.icon" - const val KEY_INFO_ICON_TINT = "ide.onboarding.infoFragment.icon.tint" - - @JvmStatic - fun newInstance( - title: CharSequence, - info: CharSequence, - @DrawableRes icon: Int, - @ColorInt iconTint: Int - ): OnboardingInfoFragment { - return OnboardingInfoFragment().apply { - arguments = Bundle().apply { - putCharSequence(OnboardingFragment.KEY_ONBOARDING_TITLE, title) - putCharSequence(KEY_INFO_TEXT, info) - putInt(KEY_INFO_ICON, icon) - putInt(KEY_INFO_ICON_TINT, iconTint) - } - } - } - } - - override fun onViewCreated(view: View, savedInstanceState: Bundle?) { - super.onViewCreated(view, savedInstanceState) - - binding.infoTitle.text = requireArguments().getCharSequence( - OnboardingFragment.KEY_ONBOARDING_TITLE) - - binding.infoMessage.text = requireArguments().getCharSequence(KEY_INFO_TEXT) - binding.image.setImageResource(requireArguments().getInt(KEY_INFO_ICON)) - ImageViewCompat.setImageTintList(binding.image, - ColorStateList.valueOf(requireArguments().getInt( - KEY_INFO_ICON_TINT))) - } -} \ No newline at end of file diff --git a/app/src/main/java/com/itsaky/androidide/fragments/onboarding/OnboardingMultiActionFragment.kt b/app/src/main/java/com/itsaky/androidide/fragments/onboarding/OnboardingMultiActionFragment.kt deleted file mode 100644 index 465c5196eb..0000000000 --- a/app/src/main/java/com/itsaky/androidide/fragments/onboarding/OnboardingMultiActionFragment.kt +++ /dev/null @@ -1,83 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.fragments.onboarding - -import android.os.Build -import android.os.Bundle -import android.view.ViewGroup -import androidx.recyclerview.widget.RecyclerView -import com.itsaky.androidide.adapters.onboarding.DefaultOnboardingItemAdapter -import com.itsaky.androidide.databinding.LayoutOnboardingMultiactionBinding -import com.itsaky.androidide.models.OnboardingItem -import com.itsaky.androidide.utils.uncheckedCast - -/** - * @author Akash Yadav - */ -open class OnboardingMultiActionFragment : OnboardingFragment() { - - protected var recyclerView: RecyclerView? = null - private set - - companion object { - - const val KEY_ACTION_ITEMS = "ide.onboarding.multiActionFragment.items" - - @JvmStatic - fun newInstance( - title: CharSequence, - subtitle: CharSequence, - items: List - ): OnboardingFragment { - return OnboardingMultiActionFragment().apply { - arguments = Bundle().apply { - putCharSequence(KEY_ONBOARDING_TITLE, title) - putCharSequence(KEY_ONBOARDING_SUBTITLE, subtitle) - - val arr = items.toTypedArray() - putParcelableArray(KEY_ACTION_ITEMS, arr) - } - } - } - } - - override fun createContentView(parent: ViewGroup, attachToParent: Boolean) { - val binding = LayoutOnboardingMultiactionBinding.inflate(layoutInflater, parent, attachToParent) - binding.onboardingItems.adapter = createAdapter() - recyclerView = binding.onboardingItems - } - - protected inline fun getItemsFromArgs(): Array { - return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { - requireArguments().getParcelableArray(KEY_ACTION_ITEMS, T::class.java)!! - } else { - uncheckedCast( - @Suppress("DEPRECATION") requireArguments().getParcelableArray(KEY_ACTION_ITEMS)!!) - } - } - - override fun onDestroyView() { - super.onDestroyView() - recyclerView = null - } - - protected open fun createAdapter(): RecyclerView.Adapter<*> { - val items = getItemsFromArgs() - return DefaultOnboardingItemAdapter(items.toList()) - } -} \ No newline at end of file diff --git a/app/src/main/java/com/itsaky/androidide/fragments/onboarding/ideSetupConfig.kt b/app/src/main/java/com/itsaky/androidide/fragments/onboarding/ideSetupConfig.kt deleted file mode 100644 index 0ff8bb2eaf..0000000000 --- a/app/src/main/java/com/itsaky/androidide/fragments/onboarding/ideSetupConfig.kt +++ /dev/null @@ -1,74 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.fragments.onboarding - -import com.itsaky.androidide.app.configuration.CpuArch - -private val ARM_ONLY = arrayOf(CpuArch.AARCH64, CpuArch.ARM) -private val ALL = arrayOf(CpuArch.AARCH64, CpuArch.ARM, CpuArch.X86_64) - -/** - * Android SDK versions. - * - * @author Akash Yadav - */ -enum class SdkVersion(val version: String, val supportedArchs: Array) { - - SDK_33_0_1("33.0.1", ARM_ONLY), - SDK_34_0_0("34.0.0", ARM_ONLY), - SDK_34_0_1("34.0.1", ARM_ONLY), - SDK_34_0_3("34.0.3", ARM_ONLY), - SDK_34_0_4("34.0.4", ALL), - ; - - val displayName = "SDK $version" - - companion object { - - @JvmStatic - fun fromDisplayName(displayName: CharSequence) = - entries.first { it.displayName.contentEquals(displayName) } - - @JvmStatic - fun fromVersion(version: CharSequence) = entries.first { it.version.contentEquals(version) } - } -} - -/** - * JDK versions. - * - * @author Akash Yadav - */ -enum class JdkVersion(val version: String) { - - JDK_17("17"), - JDK_21("21"), - ; - - val displayName = "JDK $version" - - companion object { - - @JvmStatic - fun fromDisplayName(displayName: CharSequence) = - entries.first { it.displayName.contentEquals(displayName) } - - @JvmStatic - fun fromVersion(version: CharSequence) = entries.first { it.version.contentEquals(version) } - } -} \ No newline at end of file diff --git a/app/src/main/java/com/itsaky/androidide/fragments/sheets/BaseBottomSheetFragment.java b/app/src/main/java/com/itsaky/androidide/fragments/sheets/BaseBottomSheetFragment.java deleted file mode 100755 index 311073b417..0000000000 --- a/app/src/main/java/com/itsaky/androidide/fragments/sheets/BaseBottomSheetFragment.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - * - */ -package com.itsaky.androidide.fragments.sheets; - -import android.app.Dialog; -import android.os.Bundle; -import androidx.annotation.NonNull; -import com.google.android.material.bottomsheet.BottomSheetDialogFragment; - -public abstract class BaseBottomSheetFragment extends BottomSheetDialogFragment { - - protected Dialog mDialog; - - @NonNull - @Override - public Dialog onCreateDialog(Bundle savedInstanceState) { - mDialog = super.onCreateDialog(savedInstanceState); - return mDialog; - } - - public boolean isShowing() { - return mDialog != null && mDialog.isShowing(); - } -} diff --git a/app/src/main/java/com/itsaky/androidide/fragments/sidebar/EditorSidebarFragment.kt b/app/src/main/java/com/itsaky/androidide/fragments/sidebar/EditorSidebarFragment.kt deleted file mode 100644 index 84d61b1764..0000000000 --- a/app/src/main/java/com/itsaky/androidide/fragments/sidebar/EditorSidebarFragment.kt +++ /dev/null @@ -1,65 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.fragments.sidebar - -import android.os.Bundle -import android.view.View -import com.itsaky.androidide.activities.editor.EditorHandlerActivity -import com.itsaky.androidide.databinding.FragmentEditorSidebarBinding -import com.itsaky.androidide.fragments.FragmentWithBinding -import com.itsaky.androidide.idetooltips.TooltipCategory -import com.itsaky.androidide.idetooltips.TooltipManager -import com.itsaky.androidide.utils.EditorSidebarActions - -/** - * Fragment for showing the default items in the editor activity's sidebar. - * - * @author Akash Yadav - */ -class EditorSidebarFragment : FragmentWithBinding( - FragmentEditorSidebarBinding::inflate -) { - - override fun onViewCreated(view: View, savedInstanceState: Bundle?) { - super.onViewCreated(view, savedInstanceState) - EditorSidebarActions.setup(this) - } - - fun setupTooltip( - view: View, - tooltipTag: String, - category: String = TooltipCategory.CATEGORY_IDE, - ) { - (requireActivity() as? EditorHandlerActivity)?.let { activity -> - view.setOnLongClickListener { view -> - TooltipManager.showTooltip( - context = view.context, - anchorView = view, - category = category, - tag = tooltipTag, - ) - true - } - } - } - - /** - * Get the (nullable) binding object for this fragment. - */ - internal fun getBinding() = _binding -} diff --git a/app/src/main/java/com/itsaky/androidide/fragments/sidebar/FileTreeDropController.kt b/app/src/main/java/com/itsaky/androidide/fragments/sidebar/FileTreeDropController.kt deleted file mode 100644 index 43a182626a..0000000000 --- a/app/src/main/java/com/itsaky/androidide/fragments/sidebar/FileTreeDropController.kt +++ /dev/null @@ -1,132 +0,0 @@ -package com.itsaky.androidide.fragments.sidebar - -import android.app.Activity -import android.view.DragEvent -import android.view.View -import androidx.lifecycle.LifecycleOwner -import androidx.lifecycle.lifecycleScope -import com.itsaky.androidide.R -import com.itsaky.androidide.adapters.viewholders.FileTreeViewHolder -import com.itsaky.androidide.dnd.DragEventRouter -import com.itsaky.androidide.dnd.DropTargetCallback -import com.itsaky.androidide.dnd.hasImportableContent -import com.itsaky.androidide.utils.DropHighlighter -import com.itsaky.androidide.utils.FileImporter -import com.unnamed.b.atv.model.TreeNode -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.launch -import kotlinx.coroutines.withContext -import java.io.File - - -internal class FileTreeDropController( - private val activity: Activity, - private val onDropCompleted: (TreeNode?, File, Int) -> Unit, - private val onDropFailed: (String) -> Unit, -) { - - private data class DropTarget(val node: TreeNode?, val file: File) - - val nodeBinder = FileTreeViewHolder.ExternalDropHandler { node, file, view -> - bindDropTarget(view, DropTarget(node, file)) - } - - fun bindRootTarget(containerView: View, projectRootDirectory: File) { - bindDropTarget(containerView, DropTarget(null, projectRootDirectory)) - } - - private fun bindDropTarget(view: View, target: DropTarget) { - val dropCallback = object : DropTargetCallback { - override fun canAcceptDrop(event: DragEvent): Boolean { - return event.hasImportableContent(activity) - } - - override fun onDragEntered(view: View) { - DropHighlighter.highlight(view, activity) - } - - override fun onDragExited(view: View) { - DropHighlighter.clear(view) - } - - override fun onDrop(event: DragEvent): Boolean { - return importDroppedFiles(target, event) - } - } - - view.setOnDragListener(DragEventRouter(dropCallback)) - } - - private fun importDroppedFiles(target: DropTarget, event: DragEvent): Boolean { - val context = activity.applicationContext - val clipData = event.clipData ?: return false - val dragPermissions = activity.requestDragAndDropPermissions(event) - - val lifecycleOwner = activity as? LifecycleOwner - if (lifecycleOwner == null) { - dragPermissions?.release() - return false - } - - lifecycleOwner.lifecycleScope.launch { - val result = runCatching { - withContext(Dispatchers.IO) { - FileImporter(context).copyDroppedFiles(clipData, target.file) - } - } - - dragPermissions?.release() - - handleImportResult( - target = target, - result = result.getOrNull(), - error = result.exceptionOrNull() - ) - } - - return true - } - - private fun handleImportResult( - target: DropTarget, - result: FileImporter.ImportResult?, - error: Throwable? - ) { - if (activity.isFinishing || activity.isDestroyed) return - - if (error != null) { - onDropFailed(error.toReadableMessage()) - return - } - - when (result) { - is FileImporter.ImportResult.Success -> handleSuccess(target, result) - is FileImporter.ImportResult.PartialSuccess -> handlePartialSuccess(target, result) - is FileImporter.ImportResult.Failure -> onDropFailed(result.error.toReadableMessage()) - else -> {} - } - } - - private fun handleSuccess(target: DropTarget, result: FileImporter.ImportResult.Success) { - if (result.count > 0) { - onDropCompleted(target.node, target.file, result.count) - } else { - val noFilesMsg = activity.getString(R.string.msg_file_tree_drop_no_files) - onDropFailed(noFilesMsg) - } - } - - private fun handlePartialSuccess( - target: DropTarget, - result: FileImporter.ImportResult.PartialSuccess - ) { - onDropCompleted(target.node, target.file, result.count) - onDropFailed(result.error.toReadableMessage()) - } - - private fun Throwable.toReadableMessage(): String { - return cause?.message - ?: message - ?: activity.getString(R.string.msg_file_tree_drop_import_failed) - } -} diff --git a/app/src/main/java/com/itsaky/androidide/fragments/sidebar/FileTreeSelectionFragment.kt b/app/src/main/java/com/itsaky/androidide/fragments/sidebar/FileTreeSelectionFragment.kt deleted file mode 100644 index c86a087361..0000000000 --- a/app/src/main/java/com/itsaky/androidide/fragments/sidebar/FileTreeSelectionFragment.kt +++ /dev/null @@ -1,120 +0,0 @@ -package com.itsaky.androidide.fragments.sidebar - -import android.content.Context -import android.os.Bundle -import android.view.View -import androidx.core.view.isVisible -import androidx.fragment.app.Fragment -import androidx.fragment.app.setFragmentResult -import androidx.lifecycle.lifecycleScope -import androidx.navigation.fragment.findNavController -import com.itsaky.androidide.R -import com.itsaky.androidide.adapters.viewholders.MultiSelectFileTreeViewHolder -import com.itsaky.androidide.databinding.FragmentFileTreeSelectionBinding -import com.itsaky.androidide.projects.IProjectManager -import com.unnamed.b.atv.model.TreeNode -import com.unnamed.b.atv.view.AndroidTreeView -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.currentCoroutineContext -import kotlinx.coroutines.ensureActive -import kotlinx.coroutines.launch -import kotlinx.coroutines.withContext -import java.io.File - -class FileTreeSelectionFragment : Fragment(R.layout.fragment_file_tree_selection) { - - private var _binding: FragmentFileTreeSelectionBinding? = null - private val binding get() = _binding!! - - private val selectedFiles = mutableSetOf() - private var treeView: AndroidTreeView? = null - - override fun onViewCreated(view: View, savedInstanceState: Bundle?) { - super.onViewCreated(view, savedInstanceState) - _binding = FragmentFileTreeSelectionBinding.bind(view) - loadTreeData() - setupListeners() - } - - private fun loadTreeData() { - binding.loadingIndicator.isVisible = true - val safeContext = requireContext() - viewLifecycleOwner.lifecycleScope.launch { - val projectRootFile = IProjectManager.getInstance().projectDir - if (!projectRootFile.exists()) { - binding.loadingIndicator.isVisible = false - return@launch - } - - val rootNode = withContext(Dispatchers.IO) { - val node = TreeNode.root() - buildTreeNodes(node, projectRootFile, safeContext) - node - } - if (isAdded) { - setupTreeView(rootNode) - } - } - } - - private fun setupTreeView(rootNode: TreeNode) { - binding.loadingIndicator.isVisible = false - treeView = AndroidTreeView(requireContext(), rootNode, R.drawable.bg_ripple) - binding.fileTreeContainer.addView(treeView!!.view) - rootNode.children?.forEach { treeView?.expandNode(it) } - } - - private suspend fun buildTreeNodes(parentNode: TreeNode, dir: File, context: Context) { - dir.listFiles() - ?.sortedWith(compareBy({ !it.isDirectory }, { it.name })) - ?.forEach { file -> - currentCoroutineContext().ensureActive() - val node = TreeNode(file).apply { - viewHolder = MultiSelectFileTreeViewHolder(context, selectedFiles) - } - parentNode.addChild(node) - if (file.isDirectory) { - buildTreeNodes(node, file, context) - } - } - } - - private fun setupListeners() { - binding.fileTreeToolbar.setNavigationOnClickListener { findNavController().popBackStack() } - binding.btnCancelSelection.setOnClickListener { findNavController().popBackStack() } - binding.btnConfirmSelection.setOnClickListener { - - val finalContextList = mutableListOf() - - val baseDir = IProjectManager.getInstance().projectDir - - selectedFiles.forEach { selectedPath -> - val relativePath = selectedPath.relativeTo(baseDir).path - // Create a File object by joining the project root with the relative path - val target = File(baseDir, relativePath) - - if (target.exists() && target.isDirectory) { - // It's a valid directory, so walk through it and add all readable files - target.walkTopDown() - .filter { walkedFile -> walkedFile.isFile && walkedFile.canRead() } - .forEach { walkedFile -> - finalContextList.add(walkedFile.relativeTo(baseDir).path) - } - } else if (target.exists() && target.isFile && target.canRead()) { - // It's a single, readable file - finalContextList.add(relativePath) - } - } - - setFragmentResult("file_selection_request", Bundle().apply { - putStringArrayList("selected_paths", ArrayList(finalContextList.distinct())) - }) - findNavController().popBackStack() - } - } - - override fun onDestroyView() { - super.onDestroyView() - _binding = null - } -} \ No newline at end of file diff --git a/app/src/main/java/com/itsaky/androidide/handlers/BaseEventHandler.kt b/app/src/main/java/com/itsaky/androidide/handlers/BaseEventHandler.kt deleted file mode 100644 index 6686719bbb..0000000000 --- a/app/src/main/java/com/itsaky/androidide/handlers/BaseEventHandler.kt +++ /dev/null @@ -1,47 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.handlers - -import android.content.Context -import com.itsaky.androidide.activities.editor.EditorHandlerActivity -import com.itsaky.androidide.eventbus.events.Event -import com.itsaky.androidide.eventbus.events.EventReceiver -import org.slf4j.Logger -import org.slf4j.LoggerFactory - -/** - * Base class for event handlers. - * - * @author Akash Yadav - */ -abstract class BaseEventHandler : EventReceiver { - - companion object { - - @JvmStatic - protected val log: Logger = LoggerFactory.getLogger(BaseEventHandler::class.java) - } - - protected open fun checkIsEditorActivity(event: Event): Boolean { - return event.get(Context::class.java) is EditorHandlerActivity - } - - protected open fun logCannotHandle(event: Event) { - log.warn("Context is not EditorActivity. Cannot handle {} event.", event.javaClass.simpleName) - } -} diff --git a/app/src/main/java/com/itsaky/androidide/handlers/EditorActivityLifecyclerObserver.kt b/app/src/main/java/com/itsaky/androidide/handlers/EditorActivityLifecyclerObserver.kt deleted file mode 100644 index a3cdef7088..0000000000 --- a/app/src/main/java/com/itsaky/androidide/handlers/EditorActivityLifecyclerObserver.kt +++ /dev/null @@ -1,94 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.handlers - -import android.content.Context -import androidx.lifecycle.DefaultLifecycleObserver -import androidx.lifecycle.LifecycleOwner -import com.itsaky.androidide.eventbus.events.Event -import com.itsaky.androidide.eventbus.events.EventReceiver -import com.itsaky.androidide.eventbus.events.editor.OnCreateEvent -import com.itsaky.androidide.eventbus.events.editor.OnDestroyEvent -import com.itsaky.androidide.eventbus.events.editor.OnPauseEvent -import com.itsaky.androidide.eventbus.events.editor.OnResumeEvent -import com.itsaky.androidide.eventbus.events.editor.OnStartEvent -import com.itsaky.androidide.eventbus.events.editor.OnStopEvent -import com.itsaky.androidide.projects.ProjectManagerImpl -import com.itsaky.androidide.projects.util.BootClasspathProvider -import com.itsaky.androidide.utils.EditorActivityActions -import com.itsaky.androidide.utils.EditorSidebarActions -import com.itsaky.androidide.utils.Environment -import org.greenrobot.eventbus.EventBus -import java.util.concurrent.CompletableFuture - -/** - * Observes lifecycle events if [com.itsaky.androidide.EditorActivityKt]. - * - * @author Akash Yadav - */ -class EditorActivityLifecyclerObserver : DefaultLifecycleObserver { - private val fileActionsHandler = FileTreeActionHandler() - - override fun onCreate(owner: LifecycleOwner) { - EditorActivityActions.register(owner as Context) - EditorSidebarActions.registerActions(owner as Context) - dispatchEvent(OnCreateEvent()) - } - - override fun onStart(owner: LifecycleOwner) { - CompletableFuture.runAsync(this::initBootclasspathProvider) - register(fileActionsHandler, ProjectManagerImpl.getInstance()) - - dispatchEvent(OnStartEvent()) - } - - override fun onResume(owner: LifecycleOwner) { - EditorActivityActions.register(owner as Context) - dispatchEvent(OnResumeEvent()) - } - - override fun onPause(owner: LifecycleOwner) { - EditorActivityActions.clearActions() - dispatchEvent(OnPauseEvent()) - } - - override fun onStop(owner: LifecycleOwner) { - unregister(fileActionsHandler, ProjectManagerImpl.getInstance()) - dispatchEvent(OnStopEvent()) - } - - override fun onDestroy(owner: LifecycleOwner) { - dispatchEvent(OnDestroyEvent()) - } - - private fun register(vararg receivers: EventReceiver) { - receivers.forEach { it.register() } - } - - private fun unregister(vararg receivers: EventReceiver) { - receivers.forEach { it.unregister() } - } - - private fun dispatchEvent(event: Event) { - EventBus.getDefault().post(event) - } - - private fun initBootclasspathProvider() { - BootClasspathProvider.update(listOf(Environment.ANDROID_JAR.absolutePath)) - } -} diff --git a/app/src/main/java/com/itsaky/androidide/handlers/LspHandler.kt b/app/src/main/java/com/itsaky/androidide/handlers/LspHandler.kt deleted file mode 100644 index 79f3428544..0000000000 --- a/app/src/main/java/com/itsaky/androidide/handlers/LspHandler.kt +++ /dev/null @@ -1,56 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.handlers - -import com.itsaky.androidide.lsp.PluginLanguageSupport -import com.itsaky.androidide.lsp.api.ILanguageClient -import com.itsaky.androidide.lsp.api.ILanguageServerRegistry -import com.itsaky.androidide.lsp.debug.IDebugClient -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.utils.FeatureFlags - -/** - * - * @author Akash Yadav - */ -object LspHandler { - fun registerLanguageServers() { - ILanguageServerRegistry.default.apply { - getServer(JavaLanguageServer.SERVER_ID) ?: register(JavaLanguageServer()) - getServer(KotlinLanguageServer.SERVER_ID) ?: register(KotlinLanguageServer()) - getServer(XMLLanguageServer.SERVER_ID) ?: register(XMLLanguageServer()) - } - PluginLanguageSupport.registerServers() - } - - fun connectClient(client: ILanguageClient) { - ILanguageServerRegistry.default.connectClient(client) - } - - @Throws(Throwable::class) - suspend fun connectDebugClient(client: IDebugClient) = ILanguageServerRegistry.default.connectDebugClient(client) - - fun destroyLanguageServers(isConfigurationChange: Boolean) { - if (isConfigurationChange) { - return - } - ILanguageServerRegistry.default.destroy() - } -} diff --git a/app/src/main/java/com/itsaky/androidide/handlers/SnippetHandler.kt b/app/src/main/java/com/itsaky/androidide/handlers/SnippetHandler.kt deleted file mode 100644 index ca1f789d53..0000000000 --- a/app/src/main/java/com/itsaky/androidide/handlers/SnippetHandler.kt +++ /dev/null @@ -1,73 +0,0 @@ -package com.itsaky.androidide.handlers - -import com.itsaky.androidide.lsp.java.providers.snippet.JavaSnippetScope -import com.itsaky.androidide.lsp.kotlin.completion.KotlinSnippetScope -import com.itsaky.androidide.lsp.snippets.DefaultSnippet -import com.itsaky.androidide.lsp.snippets.ISnippetScope -import com.itsaky.androidide.lsp.snippets.SnippetLanguage -import com.itsaky.androidide.lsp.snippets.SnippetRegistry -import com.itsaky.androidide.lsp.snippets.UserSnippetLoader -import com.itsaky.androidide.lsp.xml.providers.snippet.XML_SNIPPET_SCOPES -import com.itsaky.androidide.plugins.extensions.SnippetContribution -import com.itsaky.androidide.plugins.manager.snippets.PluginSnippetManager -import org.slf4j.LoggerFactory - -object SnippetHandler { - private val log = LoggerFactory.getLogger(SnippetHandler::class.java) - - fun loadUserSnippets() { - loadUserSnippetsForLanguage(SnippetLanguage.JAVA.id, JavaSnippetScope.entries) - loadUserSnippetsForLanguage(SnippetLanguage.KOTLIN.id, KotlinSnippetScope.entries) - loadUserSnippetsForLanguage(SnippetLanguage.XML.id, XML_SNIPPET_SCOPES) - } - - fun loadPluginSnippets() { - val allSnippets = PluginSnippetManager.getInstance().getAllSnippets() - allSnippets.forEach { (pluginId, contributions) -> - registerContributions(pluginId, contributions) - } - if (allSnippets.isNotEmpty()) { - log.info("Loaded plugin snippets from {} plugins", allSnippets.size) - } - } - - fun refreshPluginSnippets(pluginId: String) { - SnippetRegistry.unregisterPluginSnippets(pluginId) - val contributions = PluginSnippetManager.getInstance().refreshPlugin(pluginId) - registerContributions(pluginId, contributions) - } - - private fun registerContributions( - pluginId: String, - contributions: List, - ) { - contributions.groupBy { normalizeLanguage(it.language) to it.scope }.forEach { (key, group) -> - val (language, scope) = key - val snippets = group.map { DefaultSnippet(it.prefix, it.description, it.body.toTypedArray()) } - SnippetRegistry.registerPluginSnippets(pluginId, language, scope, snippets) - } - } - - private fun normalizeLanguage(language: String): String = SnippetLanguage.fromId(language)?.id ?: language.lowercase() - - fun removePluginSnippets(pluginId: String) { - SnippetRegistry.unregisterPluginSnippets(pluginId) - } - - private fun loadUserSnippetsForLanguage( - language: String, - scopes: Iterable, - ) { - SnippetRegistry.clearUserSnippets(language) - val userSnippets = UserSnippetLoader.loadUserSnippets(language, scopes) - userSnippets.forEach { (scope, snippets) -> - if (snippets.isNotEmpty()) { - SnippetRegistry.registerUserSnippets(language, scope, snippets) - } - } - val total = userSnippets.values.sumOf { it.size } - if (total > 0) { - log.info("Loaded {} user snippets for {}", total, language) - } - } -} diff --git a/app/src/main/java/com/itsaky/androidide/lsp/BreakpointHandler.kt b/app/src/main/java/com/itsaky/androidide/lsp/BreakpointHandler.kt deleted file mode 100644 index a82ec8b618..0000000000 --- a/app/src/main/java/com/itsaky/androidide/lsp/BreakpointHandler.kt +++ /dev/null @@ -1,420 +0,0 @@ -package com.itsaky.androidide.lsp - -import androidx.annotation.VisibleForTesting -import com.google.common.collect.HashBasedTable -import com.google.common.collect.ImmutableTable -import com.google.common.collect.Table -import com.google.common.collect.TreeBasedTable -import com.itsaky.androidide.eventbus.events.editor.ChangeType -import com.itsaky.androidide.eventbus.events.editor.DocumentChangeEvent -import com.itsaky.androidide.lsp.debug.model.BreakpointDefinition -import com.itsaky.androidide.lsp.debug.model.MethodBreakpoint -import com.itsaky.androidide.lsp.debug.model.PositionalBreakpoint -import com.itsaky.androidide.lsp.debug.model.Source -import com.itsaky.androidide.models.Position -import com.itsaky.androidide.projects.IProjectManager -import com.itsaky.androidide.repositories.BreakpointRepository -import com.itsaky.androidide.repositories.StoredBreakpointsType -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.DelicateCoroutinesApi -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.ExperimentalCoroutinesApi -import kotlinx.coroutines.Job -import kotlinx.coroutines.channels.Channel -import kotlinx.coroutines.delay -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.flow.asStateFlow -import kotlinx.coroutines.flow.update -import kotlinx.coroutines.launch -import kotlinx.coroutines.newSingleThreadContext -import org.slf4j.LoggerFactory -import java.io.File -import java.util.TreeMap -import java.util.concurrent.CopyOnWriteArrayList -import java.util.concurrent.atomic.AtomicReference - -private interface BreakpointEvent { - data class DocChange( - val event: DocumentChangeEvent - ) : BreakpointEvent - - data class Toggle( - val file: File, - val line: Int - ) : BreakpointEvent - - object Save : BreakpointEvent -} - -private data class BpState( - val positional: Table, - val method: Table -) { - companion object { - val EMPTY = BpState(ImmutableTable.of(), ImmutableTable.of()) - } -} - -class BreakpointHandler { - - @OptIn(ExperimentalCoroutinesApi::class, DelicateCoroutinesApi::class) - private val scope = CoroutineScope(newSingleThreadContext("BreakpointHandler")) - private val events = Channel(capacity = Channel.UNLIMITED) - private val _highlightedLocation = MutableStateFlow?>(null) - private var onSetBreakpoints: ((List) -> Unit)? = null - private val listeners = CopyOnWriteArrayList() - - private val stateRef = AtomicReference(BpState.EMPTY) - private var saveJob: Job? = null - - val highlightedLocationState: StateFlow?> - get() = _highlightedLocation.asStateFlow() - - val highlightedLocation: Pair? - get() = highlightedLocationState.value - - val allBreakpoints: List - get() = stateRef.get().let { s -> - buildList { - addAll(s.positional.values()) - addAll(s.method.values()) - } - } - - companion object { - private val logger = LoggerFactory.getLogger(BreakpointHandler::class.java) - - @VisibleForTesting - internal fun computeNewBreakpointPosition( - line: Int, - column: Int, - start: Position, - end: Position, - changeType: ChangeType, - ): Pair { - var newLine = line - var newColumn = column - - if (changeType == ChangeType.INSERT) { - - // insertion before breakpoint line - if (line > start.line) { - // shift down - newLine += end.line - start.line - } - - // insertion on breakpoint line, after start column - else if (line == start.line && column > start.column) { - if (start.line == end.line) { - // same line insertion, shift column right - newColumn += end.column - start.column - } else { - // multi-line insertion - // adjust line and column - newLine += end.line - start.line - newColumn = column - start.column + end.column - } - } - } else if (changeType == ChangeType.DELETE) { - // breakpoint after deletion range - if (line > end.line) { - // shift up - newLine -= end.line - start.line - } - - // breakpoint after last line of deletion, after end column - else if (line == end.line && column > end.column) { - if (start.line == end.line) { - // Single-line deletion - newColumn -= (end.column - start.column); - } else { - // Multi-line deletion - newLine = start.line - newColumn = start.column + (column - end.column); - } - } - - // breakpoint within deleted range - else if ((line > start.line || (line == start.line && column >= start.column)) - && (line < end.line || (line == end.line && column <= end.column)) - ) { - // mark for deletion - newLine = -1 - newColumn = -1 - } - } - - return Pair(newLine, newColumn) - } - } - - fun highlightLocation(file: String, line: Int) { - this._highlightedLocation.update { file to line } - notifyHighlighted(file, line) - } - - fun unhighlightHighlightedLocation() { - this._highlightedLocation.update { null } - notifyUnhighlight() - } - - fun begin(consumer: (List) -> Unit) { - onSetBreakpoints = consumer - - scope.launch { - val projectDir = IProjectManager.getInstance().projectDir - val loadedBreakpoints = BreakpointRepository.getStoredBreakpoints(projectDir) - - refreshBreakpoints(loadedBreakpoints) - notifyBreakpointsUpdated(loadedBreakpoints) - - for (event in events) { - process(event) - } - } - } - - fun addListener(listener: EventListener) { - if (listeners.contains(listener)) { - logger.warn("listener {} is already added", listener) - return - } - - listeners.add(listener) - } - - fun removeListener(listener: EventListener) { - listeners.remove(listener) - } - - suspend fun positionalBreakpointsInFile(file: File): List = - BreakpointRepository.getStoredBreakpoints(IProjectManager.getInstance().projectDir) - .mapNotNull { breakpoint -> - if (breakpoint.source.path != file.absolutePath || breakpoint !is PositionalBreakpoint) { - return@mapNotNull null - } - - breakpoint - } - - suspend fun change(event: DocumentChangeEvent) { - events.send(BreakpointEvent.DocChange(event)) - } - - suspend fun toggle(file: File, line: Int) { - events.send(BreakpointEvent.Toggle(file, line)) - } - - private fun refreshBreakpoints(loadedBreakpoints: StoredBreakpointsType) { - val newPos = HashBasedTable.create() - val newMethod = HashBasedTable.create() - - for (bp in loadedBreakpoints) { - val path = bp.source.path - when (bp) { - is PositionalBreakpoint -> newPos.put(path, bp.line, bp) - is MethodBreakpoint -> newMethod.put(path, bp.methodId, bp) - } - } - - val snap = BpState( - positional = ImmutableTable.copyOf(newPos), - method = ImmutableTable.copyOf(newMethod) - ) - - stateRef.set(snap) - } - - private fun process(event: BreakpointEvent) = runCatching { - when (event) { - is BreakpointEvent.DocChange -> onChange(event) - is BreakpointEvent.Toggle -> onToggle(event) - is BreakpointEvent.Save -> onSave() - } - }.onFailure { err -> - logger.error("Failed to handle event {}", event.javaClass.simpleName, err) - } - - private fun onChange(event: BreakpointEvent.DocChange) { - val ev = event.event - val range = ev.changeRange - val (start, end) = range - - val path = ev.file.toRealPath().toString() - logger.debug( - "change({}): range={},{}-{},{}", when (ev.changeType) { - ChangeType.NEW_TEXT -> "new text" - ChangeType.DELETE -> "delete" - ChangeType.INSERT -> "insert" - }, start.line, start.column, end.line, end.column - ) - - if (end.line - start.line == 0) { - // single line edits don't alter line numbers - // hence we don't need to update the breakpoints - logger.debug("no lines changed") - return - } - - val current = stateRef.get() - - val newPos = HashBasedTable.create(current.positional) - val breakpoints = newPos.row(path) - - if (ev.changeType == ChangeType.NEW_TEXT) { - logger.debug("new content set to file {}. removing all breakpoints", path) - - // All of the editor's text was invalidated - // remove all breakpoints in this file - val localBreakpoints = ArrayList(breakpoints.values) - localBreakpoints.forEach { notifyRemoved(path, it.line) } - - notifyBreakpointsUpdated(localBreakpoints) - breakpoints.clear() - - stateRef.set(current.copy(positional = ImmutableTable.copyOf(newPos))) - events.trySend(BreakpointEvent.Save) - return - } - - val fileBreakpoints = TreeMap(breakpoints) - val updated = mutableMapOf() - - for ((_, bp) in fileBreakpoints) { - val line = bp.line - val column = bp.column - val (newLine, newColumn) = computeNewBreakpointPosition( - line, - column, - start, - end, - ev.changeType - ) - - if (newLine == line && newColumn == column) { - logger.debug("keep breakpoint at line {} in file {}", line, path) - updated[line] = bp - continue - } - - if (newLine == -1 && newColumn == -1) { - logger.debug("remove breakpoint at {},{} in file {}", line, column, path) - notifyRemoved(path, line) - continue - } - - logger.debug("move breakpoint at line {} to line {} in file {}", line, newLine, path) - updated[newLine] = bp.copy(line = newLine) - notifyMoved(path, line, newLine) - } - - breakpoints.apply { - clear() - putAll(updated) - } - - stateRef.set(current.copy(positional = ImmutableTable.copyOf(newPos))) - events.trySend(BreakpointEvent.Save) - - notifyBreakpointsUpdated(newBreakpoints = updated.values.toList()) - } - - private fun onToggle(event: BreakpointEvent.Toggle) { - val (file, line) = event - val path = file.canonicalPath - - val breakpoint = PositionalBreakpoint( - source = Source(path = file.absolutePath, name = file.name), - line = line - ) - - val current = stateRef.get() - val newPos = HashBasedTable.create(current.positional) - - val remove = newPos.contains(path, line) - logger.debug("{} breakpoint at line {} in {}", if (remove) "remove" else "add", line, path) - - if (remove) { - newPos.remove(path, line) - notifyRemoved(path, line) - } else { - newPos.put(path, line, breakpoint) - notifyAdded(path, line) - } - - notifyToggled(path, line) - - val fileBreakpoints = newPos.row(path).values - notifyBreakpointsUpdated(ArrayList(fileBreakpoints)) - - stateRef.set(current.copy(positional = ImmutableTable.copyOf(newPos))) - events.trySend(BreakpointEvent.Save) - } - - private fun onSave() { - saveJob?.cancel() - saveJob = scope.launch(Dispatchers.IO) { - delay(1000) - val snap = stateRef.get() - val breakpointsToSave = buildList { - addAll(snap.positional.values()) - addAll(snap.method.values()) - } - BreakpointRepository.saveBreakpoints( - projectDir = IProjectManager.getInstance().projectDir, - breakpoints = breakpointsToSave - ) - logger.debug("Breakpoints saved to disk.") - } - } - - private fun notifyBreakpointsUpdated(newBreakpoints: List) { - onSetBreakpoints?.invoke(newBreakpoints) - } - - private fun notifyAdded(file: String, line: Int) { - for (listener in listeners) { - listener.onAddBreakpoint(file, line) - } - } - - private fun notifyRemoved(file: String, line: Int) { - for (listener in listeners) { - listener.onRemoveBreakpoint(file, line) - } - } - - private fun notifyToggled(file: String, line: Int) { - for (listener in listeners) { - listener.onToggle(file, line) - } - } - - private fun notifyMoved(file: String, oldLine: Int, newLine: Int) { - for (listener in listeners) { - listener.onMoveBreakpoint(file, oldLine, newLine) - } - } - - private fun notifyHighlighted(file: String, line: Int) { - for (listener in listeners) { - listener.onHighlightLine(file, line) - } - } - - private fun notifyUnhighlight() { - for (listener in listeners) { - listener.onUnhighlight() - } - } - - interface EventListener { - fun onAddBreakpoint(file: String, line: Int) {} - fun onRemoveBreakpoint(file: String, line: Int) {} - fun onToggle(file: String, line: Int) {} - fun onMoveBreakpoint(file: String, oldLine: Int, newLine: Int) {} - fun onHighlightLine(file: String, line: Int) {} - fun onUnhighlight() - } -} \ No newline at end of file diff --git a/app/src/main/java/com/itsaky/androidide/lsp/IDEDebugClientImpl.kt b/app/src/main/java/com/itsaky/androidide/lsp/IDEDebugClientImpl.kt deleted file mode 100644 index 83f35c74a0..0000000000 --- a/app/src/main/java/com/itsaky/androidide/lsp/IDEDebugClientImpl.kt +++ /dev/null @@ -1,341 +0,0 @@ -package com.itsaky.androidide.lsp - -import android.annotation.SuppressLint -import android.widget.RemoteViews.RemoteView -import com.itsaky.androidide.eventbus.events.EventReceiver -import com.itsaky.androidide.eventbus.events.editor.DocumentChangeEvent -import com.itsaky.androidide.lookup.Lookup -import com.itsaky.androidide.lsp.debug.IDebugClient -import com.itsaky.androidide.lsp.debug.IDebugEventHandler -import com.itsaky.androidide.lsp.debug.RemoteClient -import com.itsaky.androidide.lsp.debug.events.BreakpointHitEvent -import com.itsaky.androidide.lsp.debug.events.StepEvent -import com.itsaky.androidide.lsp.debug.model.BreakpointRequest -import com.itsaky.androidide.lsp.debug.model.LocatableEvent -import com.itsaky.androidide.lsp.debug.model.Location -import com.itsaky.androidide.lsp.debug.model.StepRequestParams -import com.itsaky.androidide.lsp.debug.model.StepResult -import com.itsaky.androidide.lsp.debug.model.StepType -import com.itsaky.androidide.lsp.debug.model.ThreadListRequestParams -import com.itsaky.androidide.models.Position -import com.itsaky.androidide.models.Range -import com.itsaky.androidide.viewmodel.DebuggerConnectionState -import com.itsaky.androidide.viewmodel.DebuggerViewModel -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.DelicateCoroutinesApi -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.SupervisorJob -import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.launch -import kotlinx.coroutines.newFixedThreadPoolContext -import kotlinx.coroutines.withContext -import org.greenrobot.eventbus.Subscribe -import org.greenrobot.eventbus.ThreadMode -import org.slf4j.LoggerFactory -import java.io.File -import java.util.concurrent.CopyOnWriteArraySet - -/** - * @author Akash Yadav - */ -class IDEDebugClientImpl( - private val viewModel: DebuggerViewModel, -) : IDebugClient, IDebugEventHandler, EventReceiver { - - private val logger = LoggerFactory.getLogger(IDEDebugClientImpl::class.java) - - @OptIn(DelicateCoroutinesApi::class) - private val clientContext = newFixedThreadPoolContext(4, "IDEDebugClient") - private val clientScope = CoroutineScope(clientContext + SupervisorJob()) - private val clients = CopyOnWriteArraySet() - val breakpoints = BreakpointHandler() - - companion object { - @JvmStatic - fun getInstance() = Lookup.getDefault().lookup(IDEDebugClientImpl::class.java) - - @JvmStatic - fun requireInstance() = checkNotNull(getInstance()) { - "Cannot lookup IDEDebugClientImpl" - } - } - - val connectionStateFlow: StateFlow - get() = viewModel.connectionState - - var connectionState: DebuggerConnectionState - get() = viewModel.connectionState.value - private set(value) { - logger.debug("move to connection state: {}", value) - viewModel.setConnectionState(value) - } - - val debugeePackage: String - get() = viewModel.debugeePackage - - internal val requireClient: RemoteClient - get() = checkNotNull(clientOrNull) - - internal val clientOrNull: RemoteClient? - get() = clients.firstOrNull() - - /** - * Returns true if the client is connected. - * - * @return `true` if the client is connected, `false` otherwise. - */ - fun isVmConnected() = connectionState >= DebuggerConnectionState.ATTACHED - - /** - * Returns true if the client is connected and suspended. - * - * The VM may or may not be able to view/alter its state. Check [connectionState] - * to get the actual state. - * - * @return `true` if the client is connected and suspended, `false` otherwise. - */ - fun isVmSuspended() = connectionState >= DebuggerConnectionState.SUSPENDED - - fun suspendVm() = withClient("suspend vm") { client -> - if (!client.capabilities.suspensionSupport) { - logger.error("Remote client does not support suspending") - return@withClient - } - - if (isVmSuspended()) { - logger.warn("Ignoring attempt to suspend VM when it is already suspended") - return@withClient - } - - logger.debug("suspending client: {}", client.name) - clientScope.launch { - if (client.adapter.suspendClient(client)) { - connectionState = DebuggerConnectionState.SUSPENDED - updateThreadInfo(client) - } - } - } - - fun resumeVm() = withClient("resume vm") { client -> - if (!client.capabilities.suspensionSupport) { - logger.error("Remote client does not support resuming") - return@withClient - } - - if (!isVmSuspended()) { - logger.warn("Ignoring attempt to resume VM when it is not suspended") - return@withClient - } - - logger.debug("resuming client: {}", client.name) - clientScope.launch { - if (client.adapter.resumeClient(client)) { - connectionState = DebuggerConnectionState.ATTACHED - updateThreadInfo(client) - } - } - } - - fun killVm() = withClient("kill vm") { client -> - if (!client.capabilities.killSupport) { - logger.error("Remote client does not support killing debug application") - return@withClient - } - - logger.debug("killing client: {}", client.name) - clientScope.launch { client.adapter.killClient(client) } - } - - fun stepOver() = doStep(type = StepType.Over) - fun stepInto() = doStep(type = StepType.Into) - fun stepOut() = doStep(type = StepType.Out) - - private inline fun withClient(action: String, block: (RemoteClient) -> Unit) { - clientOrNull?.also(block) - ?: logger.error("Cannot perform $action action. Not connected to a remote client.") - } - - private fun doStep( - type: StepType, - countFilter: Int = 1 - ) = withClient("step $type") { client -> - if (!client.capabilities.stepSupport) { - logger.error("Remote client does not support stepping") - return@withClient - } - - clientScope.launch { - val params = StepRequestParams( - remoteClient = client, - type = type, - countFilter = countFilter - ) - - val response = client.adapter.step(params) - if (response.result != StepResult.Success) { - logger.error("Failed to perform step action, result={}", response.result) - } - } - } - - init { - register() - breakpoints.begin { breakpoints -> - - // if we're already connected to a client, update the client as well - clientOrNull?.also { client -> - if (!client.capabilities.breakpointSupport) { - logger.error("Remote client does not support breakpoints") - return@also - } - - clientScope.launch { - clientOrNull?.also { client -> - val response = client.adapter.setBreakpoints( - BreakpointRequest( - remoteClient = client, - breakpoints = breakpoints - ) - ) - - logger.debug("breakpoint result: {}", response.results) - } ?: logger.info("client ${client.name} disconnected while updating breakpoints") - } - } ?: logger.info("deferring breakpoint update, no clients connected") - } - } - - @SuppressLint("ImplicitSamInstance") - @Suppress("UNUSED") - @Subscribe(threadMode = ThreadMode.ASYNC) - fun onContentChange(event: DocumentChangeEvent) { - clientScope.launch { breakpoints.change(event) } - } - - fun toggleBreakpoint(file: File, line: Int) { - clientScope.launch { breakpoints.toggle(file, line) } - } - - override fun onBreakpointHit(event: BreakpointHitEvent) { - logger.debug("onBreakpointHit: {}", event) - - clientScope.launch { - connectionState = DebuggerConnectionState.AWAITING_BREAKPOINT - updateThreadInfo(event.remoteClient, event.threadId) - - openLocation(event) - } - } - - override fun onStep(event: StepEvent) { - logger.debug("onStep: {}", event) - - clientScope.launch { - updateThreadInfo(event.remoteClient, event.threadId) - connectionState = DebuggerConnectionState.AWAITING_BREAKPOINT - - openLocation(event) - } - } - - override fun onAttach(client: RemoteClient) { - logger.debug("onAttach: client={}", client) - - check(client !in clients) { - "Already attached to client" - } - - clients += client - connectionState = DebuggerConnectionState.ATTACHED - breakpoints.unhighlightHighlightedLocation() - - clientScope.launch { - updateThreadInfo(client) - - val breakpoints = breakpoints.allBreakpoints - client.adapter.setBreakpoints( - BreakpointRequest( - remoteClient = client, - breakpoints = breakpoints - ) - ) - } - } - - override fun onDisconnect(client: RemoteClient) { - logger.debug("onDisconnect: client={}", client) - breakpoints.unhighlightHighlightedLocation() - clients -= client - connectionState = DebuggerConnectionState.DETACHED - clientScope.launch { updateThreadInfo(client) } - } - - suspend fun updateThreadInfo( - client: RemoteClient, - selectedThreadId: String? = null, - ) { - val adapter = client.adapter - var selectedThreadIndex = -1 - val threads = when (connectionState) { - DebuggerConnectionState.DETACHED, - DebuggerConnectionState.ATTACHED -> emptyList() - - DebuggerConnectionState.SUSPENDED, - DebuggerConnectionState.AWAITING_BREAKPOINT -> { - val threadResponse = adapter.allThreads( - ThreadListRequestParams( - remoteClient = client - ) - ) - - val threads = threadResponse.threads - if (threads.isEmpty()) { - logger.error("Failed to get info about active threads in VM: {}", client.name) - } else if (selectedThreadId != null) { - selectedThreadIndex = threads.indexOfFirst { - it.descriptor().id == selectedThreadId - } - } - - threads - } - } - - if (threads.isNotEmpty() && selectedThreadIndex < 0) { - selectedThreadIndex = 0 - } - - viewModel.setThreads(threads, selectedThreadIndex) - } - - private suspend fun openLocation(event: LocatableEvent) = openLocation(event.location) - - private suspend fun openLocation(location: Location) { - val file = location.source.path - val position = Position(location.line, 0) - - if (!IDELanguageClientImpl.isInitialized()) { - logger.error("Cannot open {}:{} because language client is not initialized", file, position.line) - return - } - - val activity = IDELanguageClientImpl.getInstance().activity - - if (activity == null) { - logger.error("Cannot open {}:{} because activity is null", file, position.line) - return - } - - breakpoints.highlightLocation(file, position.line) - - withContext(Dispatchers.Main.immediate) { - activity.openFileAndSelect( - file = File(file), - selection = Range( - start = position, - end = position - ) - ) - } - } -} \ No newline at end of file diff --git a/app/src/main/java/com/itsaky/androidide/models/ArtifactType.kt b/app/src/main/java/com/itsaky/androidide/models/ArtifactType.kt deleted file mode 100644 index ee843f4b77..0000000000 --- a/app/src/main/java/com/itsaky/androidide/models/ArtifactType.kt +++ /dev/null @@ -1,49 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.models - -import com.google.gson.annotations.SerializedName - -class ArtifactType { - @SerializedName("type") var type: String? = null - @SerializedName("kind") var kind: String? = null - - companion object { - var TYPE_APK = "APK" - } - - override fun toString(): String { - return "ArtifactType(type=$type, kind=$kind)" - } - - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (other !is ArtifactType) return false - - if (type != other.type) return false - if (kind != other.kind) return false - - return true - } - - override fun hashCode(): Int { - var result = type?.hashCode() ?: 0 - result = 31 * result + (kind?.hashCode() ?: 0) - return result - } -} \ No newline at end of file diff --git a/app/src/main/java/com/itsaky/androidide/models/ContextListItem.kt b/app/src/main/java/com/itsaky/androidide/models/ContextListItem.kt deleted file mode 100644 index b6267809a8..0000000000 --- a/app/src/main/java/com/itsaky/androidide/models/ContextListItem.kt +++ /dev/null @@ -1,17 +0,0 @@ -package com.itsaky.androidide.models - -import androidx.annotation.DrawableRes - -// A sealed interface to represent any item in our list -sealed interface ContextListItem - -// A data class for section titles like "FILES AND FOLDERS" -data class HeaderItem(val title: String) : ContextListItem - -// A data class for a single selectable option -data class SelectableItem( - val id: String, // A unique ID for the item - val text: String, - @DrawableRes val icon: Int, - var isSelected: Boolean = false -) : ContextListItem \ No newline at end of file diff --git a/app/src/main/java/com/itsaky/androidide/models/DefaultOnboardingItem.kt b/app/src/main/java/com/itsaky/androidide/models/DefaultOnboardingItem.kt deleted file mode 100644 index 02c886f4fa..0000000000 --- a/app/src/main/java/com/itsaky/androidide/models/DefaultOnboardingItem.kt +++ /dev/null @@ -1,36 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.models - -import kotlinx.parcelize.Parcelize - -/** - * Default implementation of [OnboardingItem]. - * - * @author Akash Yadav - */ -@Parcelize -data class DefaultOnboardingItem( - override val key: String, - override val title: CharSequence, - override val description: CharSequence = "", - override val icon: Int = 0, - override val iconTint: Int = 0, - override val isClickable: Boolean = false, - override val isLongClickable: Boolean = false -) : OnboardingItem diff --git a/app/src/main/java/com/itsaky/androidide/models/DiagnosticGroup.java b/app/src/main/java/com/itsaky/androidide/models/DiagnosticGroup.java deleted file mode 100755 index 963ac0cb77..0000000000 --- a/app/src/main/java/com/itsaky/androidide/models/DiagnosticGroup.java +++ /dev/null @@ -1,36 +0,0 @@ -/************************************************************************************ - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - * - **************************************************************************************/ -package com.itsaky.androidide.models; - -import com.itsaky.androidide.lsp.models.DiagnosticItem; -import java.io.File; -import java.util.List; - -public class DiagnosticGroup { - public int icon; - public String text; - public File file; - public List diagnostics; - - public DiagnosticGroup(int icon, File file, List diagnostics) { - this.icon = icon; - this.file = file; - this.text = file.getName(); - this.diagnostics = diagnostics; - } -} diff --git a/app/src/main/java/com/itsaky/androidide/models/FileExtension.kt b/app/src/main/java/com/itsaky/androidide/models/FileExtension.kt deleted file mode 100644 index 000ea7681a..0000000000 --- a/app/src/main/java/com/itsaky/androidide/models/FileExtension.kt +++ /dev/null @@ -1,97 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.models - -import androidx.annotation.DrawableRes -import com.itsaky.androidide.resources.R -import java.io.File - -/** - * Info about file extensions in the file tree view. - * - * @author Akash Yadav - */ -enum class FileExtension(val extension: String, @DrawableRes val icon: Int) { - JAVA("java", R.drawable.ic_language_java), - JAR("jar", R.drawable.ic_language_java), - KT("kt", R.drawable.ic_language_kotlin), - KTS("kts", R.drawable.ic_language_kts), - XML("xml", R.drawable.ic_language_xml), - GRADLE("gradle", R.drawable.ic_gradle), - JSON("json", R.drawable.ic_language_json), - PROPERTIES("properties", R.drawable.ic_language_properties), - APK("apk", R.drawable.ic_file_apk), - TXT("txt", R.drawable.ic_file_txt), - LOG("log", R.drawable.ic_file_txt), - CPP("cpp", R.drawable.ic_language_cpp), - H("h", R.drawable.ic_language_cpp), - BAT("bat", R.drawable.ic_terminal), - DIRECTORY("", R.drawable.ic_folder), - IMAGE("", R.drawable.ic_file_image), - GRADLEW("", R.drawable.ic_terminal), - UNKNOWN("", R.drawable.ic_file_unknown); - - /** Factory class for getting [FileExtension] instances. */ - class Factory { - companion object { - - /** Get [FileExtension] for the given file. */ - @JvmStatic - fun forFile(file: File?, isDirectory: Boolean? = null): FileExtension { - return when { - file == null -> UNKNOWN - isDirectory == true -> DIRECTORY - else -> { - val name = file.name - val ext = file.extension.lowercase() - when { - isImageExtension(ext) -> IMAGE - name == "gradlew" -> GRADLEW - else -> forExtension(ext) - } - } - } - } - - private fun isImageExtension(extension: String?): Boolean { - return when (extension?.lowercase()) { - "jpg", "jpeg", "png", "gif", "webp", "bmp", "ico" -> true - else -> false - } - } - - /** Get [FileExtension] for the given extension. */ - @JvmStatic - fun forExtension(extension: String?): FileExtension { - // To not assign IMAGE, GRADLEW and DIRECTORY in case of an empty extension, - // we check if an extension is empty here - if (extension.isNullOrEmpty()) { - return UNKNOWN - } - - for (value in entries) { - if (value.extension == extension) { - return value - } - } - - return UNKNOWN - } - } - } -} diff --git a/app/src/main/java/com/itsaky/androidide/models/HyperlinkedOnboardingItem.kt b/app/src/main/java/com/itsaky/androidide/models/HyperlinkedOnboardingItem.kt deleted file mode 100644 index 3137ca4b7b..0000000000 --- a/app/src/main/java/com/itsaky/androidide/models/HyperlinkedOnboardingItem.kt +++ /dev/null @@ -1,38 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.models - -import kotlinx.parcelize.Parcelize - -/** - * Implementation of [OnboardingItem] which also contains a link to be opened on click. - * - * @property hyperlink The hyperlink. - * @author Akash Yadav - */ -@Parcelize -data class HyperlinkedOnboardingItem( - override val key: String, - override val title: CharSequence, - val hyperlink: String, - override val description: CharSequence = "", - override val icon: Int = 0, - override val iconTint: Int = 0, - override val isClickable: Boolean = false, - override val isLongClickable: Boolean = false -) : OnboardingItem \ No newline at end of file diff --git a/app/src/main/java/com/itsaky/androidide/models/MetadataElement.kt b/app/src/main/java/com/itsaky/androidide/models/MetadataElement.kt deleted file mode 100644 index 3b2ff125c3..0000000000 --- a/app/src/main/java/com/itsaky/androidide/models/MetadataElement.kt +++ /dev/null @@ -1,57 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.models - -import com.google.gson.annotations.SerializedName - -class MetadataElement { - @SerializedName("type") var type: String? = null - @SerializedName("filters") var filters: List? = null - @SerializedName("attributes") var attributes: List? = null - @SerializedName("versionCode") var versionCode = 0 - @SerializedName("versionName") var versionName: String? = null - @SerializedName("outputFile") var outputFile: String? = null - - override fun toString(): String { - return "Element(type=$type, filters=$filters, attributes=$attributes, versionCode=$versionCode, versionName=$versionName, outputFile=$outputFile)" - } - - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (other !is MetadataElement) return false - - if (type != other.type) return false - if (filters != other.filters) return false - if (attributes != other.attributes) return false - if (versionCode != other.versionCode) return false - if (versionName != other.versionName) return false - if (outputFile != other.outputFile) return false - - return true - } - - override fun hashCode(): Int { - var result = type?.hashCode() ?: 0 - result = 31 * result + (filters?.hashCode() ?: 0) - result = 31 * result + (attributes?.hashCode() ?: 0) - result = 31 * result + versionCode - result = 31 * result + (versionName?.hashCode() ?: 0) - result = 31 * result + (outputFile?.hashCode() ?: 0) - return result - } -} \ No newline at end of file diff --git a/app/src/main/java/com/itsaky/androidide/models/NewProjectDetails.java b/app/src/main/java/com/itsaky/androidide/models/NewProjectDetails.java deleted file mode 100755 index 5f747284cf..0000000000 --- a/app/src/main/java/com/itsaky/androidide/models/NewProjectDetails.java +++ /dev/null @@ -1,93 +0,0 @@ -/************************************************************************************ - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - * - **************************************************************************************/ -package com.itsaky.androidide.models; - -public class NewProjectDetails { - - public String name; - public String packageName; - public int minSdk; - public int targetSdk; - public String language; - public String savePath; - public String cppFlags; - - public NewProjectDetails() {} - - public NewProjectDetails( - String name, - String packageName, - int minSdk, - int targetSdk, - String language, - String cppFlags, - String savePath) { - this.name = name; - this.packageName = packageName; - this.minSdk = minSdk; - this.targetSdk = targetSdk; - this.language = language; - this.cppFlags = cppFlags; - this.savePath = savePath; - } - - public String getName() { - return name; - } - - public NewProjectDetails setName(String name) { - this.name = name; - return this; - } - - public String getPackageName() { - return packageName; - } - - public NewProjectDetails setPackageName(String packageName) { - this.packageName = packageName; - return this; - } - - public int getMinSdk() { - return minSdk; - } - - public NewProjectDetails setMinSdk(int minSdk) { - this.minSdk = minSdk; - return this; - } - - public int getTargetSdk() { - return targetSdk; - } - - public NewProjectDetails setTargetSdk(int targetSdk) { - this.targetSdk = targetSdk; - return this; - } - - public String getCppFlags() { - return cppFlags; - } - - public NewProjectDetails setCppFlags(String cppFlags) { - this.cppFlags = cppFlags; - return this; - } -} diff --git a/app/src/main/java/com/itsaky/androidide/models/OnboardingItem.kt b/app/src/main/java/com/itsaky/androidide/models/OnboardingItem.kt deleted file mode 100644 index 49cdd665f7..0000000000 --- a/app/src/main/java/com/itsaky/androidide/models/OnboardingItem.kt +++ /dev/null @@ -1,67 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.models - -import android.os.Parcelable -import androidx.annotation.ColorInt -import androidx.annotation.DrawableRes - -/** - * Item that is shown on the onboarding fragment. - * - * @author Akash Yadav - */ -interface OnboardingItem : Parcelable { - - /** - * The key for the item. - */ - val key: String - - /** - * Title for the item. - */ - val title: CharSequence - - /** - * Short description (or subtitle) for the item. - */ - val description: CharSequence - - /** - * Icon for the item. - */ - @get:DrawableRes - val icon: Int - - /** - * Icon tint for the item. - */ - @get:ColorInt - val iconTint: Int - - /** - * Whether is item is clickable. - */ - val isClickable: Boolean - - /** - * Whether the item is long clickable. - */ - val isLongClickable: Boolean -} \ No newline at end of file diff --git a/app/src/main/java/com/itsaky/androidide/models/OpenedFile.kt b/app/src/main/java/com/itsaky/androidide/models/OpenedFile.kt deleted file mode 100644 index 51ef805219..0000000000 --- a/app/src/main/java/com/itsaky/androidide/models/OpenedFile.kt +++ /dev/null @@ -1,64 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.models - -import com.google.gson.Gson -import com.google.gson.annotations.SerializedName -import com.google.gson.stream.JsonReader -import org.slf4j.LoggerFactory - -/** - * A file that is opened in editor. - * - * @author Akash Yadav - */ -data class OpenedFile( - @SerializedName(KEY_FILE) val filePath: String, - @SerializedName(KEY_SELECTION) var selection: Range -) { - - companion object { - - private const val KEY_FILE = "file" - private const val KEY_SELECTION = "selection" - private val log = LoggerFactory.getLogger(OpenedFile::class.java) - - fun readFrom(reader: JsonReader): OpenedFile? { - return try { -// reader.beginObject() -// var path = "" -// var selection = Range.NONE -// while(reader.hasNext()) { -// val name = reader.nextName() -// if (name == KEY_FILE) { -// path = reader.nextString() -// } else if (name == KEY_SELECTION) { -// selection = Gson().fromJson(reader, Range::class.java) -// } -// } -// reader.endObject() -// -// OpenedFile(path, selection) - Gson().fromJson(reader, OpenedFile::class.java) - } catch (err: Exception) { - log.error("Failed to read opened file", err) - null - } - } - } -} diff --git a/app/src/main/java/com/itsaky/androidide/models/OpenedFilesCache.kt b/app/src/main/java/com/itsaky/androidide/models/OpenedFilesCache.kt deleted file mode 100644 index 859db88a1b..0000000000 --- a/app/src/main/java/com/itsaky/androidide/models/OpenedFilesCache.kt +++ /dev/null @@ -1,73 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.models - -import com.google.gson.Gson -import com.google.gson.annotations.SerializedName -import com.google.gson.reflect.TypeToken -import com.google.gson.stream.JsonReader -import org.slf4j.LoggerFactory -import java.io.Reader - -/** - * @author Akash Yadav - */ -data class OpenedFilesCache( - @SerializedName(KEY_PROJECT_PATH) val projectPath: String = "", - @SerializedName(KEY_SELECTED_FILE) val selectedFile: String, - @SerializedName(KEY_ALL_FILES) val allFiles: List, -) { - - companion object { - - private const val KEY_PROJECT_PATH = "projectPath" - private const val KEY_SELECTED_FILE = "selectedFile" - private const val KEY_ALL_FILES = "allFiles" - private val log = LoggerFactory.getLogger(OpenedFilesCache::class.java) - - @JvmStatic - fun parse(contentReader: Reader): OpenedFilesCache? { - return try { - JsonReader(contentReader).use { reader -> - if (!reader.hasNext()) { - return@use null - } - - reader.beginObject() - var projectPath = "" - var selectedFile = "" - var allFiles = emptyList() - while (reader.hasNext()) { - when (reader.nextName()) { - KEY_PROJECT_PATH -> projectPath = reader.nextString() - KEY_SELECTED_FILE -> selectedFile = reader.nextString() - KEY_ALL_FILES -> allFiles = Gson().fromJson(reader, object : TypeToken>() {}) - else -> reader.skipValue() - } - } - reader.endObject() - - return@use OpenedFilesCache(projectPath, selectedFile, allFiles) - } - } catch (err: Exception) { - log.error("Failed to parse opened files cache", err) - null - } - } - } -} \ No newline at end of file diff --git a/app/src/main/java/com/itsaky/androidide/models/ProjectTemplate.java b/app/src/main/java/com/itsaky/androidide/models/ProjectTemplate.java deleted file mode 100755 index 053b957feb..0000000000 --- a/app/src/main/java/com/itsaky/androidide/models/ProjectTemplate.java +++ /dev/null @@ -1,114 +0,0 @@ -/************************************************************************************ - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - * - **************************************************************************************/ -package com.itsaky.androidide.models; - -import android.content.Context; -import androidx.annotation.DrawableRes; -import androidx.annotation.StringRes; - -public class ProjectTemplate { - - private int id; - private String name; - private String description; - private boolean isSupportJava; - private boolean isSupportKotlin; - private boolean isCpp; - - @DrawableRes private int imageId; - - public ProjectTemplate() {} - - public ProjectTemplate(int id, String name, String description, int imageId) { - this.id = id; - this.name = name; - this.description = description; - this.imageId = imageId; - } - - public int getId() { - return id; - } - - public ProjectTemplate setId(int id) { - this.id = id; - return this; - } - - public ProjectTemplate setName(Context ctx, @StringRes int name) { - return setName(ctx.getString(name)); - } - - public String getName() { - return name; - } - - public ProjectTemplate setName(String name) { - this.name = name; - return this; - } - - public ProjectTemplate setDescription(Context ctx, @StringRes int desc) { - return setDescription(ctx.getString(desc)); - } - - public String getDescription() { - return description; - } - - public ProjectTemplate setDescription(String description) { - this.description = description; - return this; - } - - public int getImageId() { - return imageId; - } - - public ProjectTemplate setImageId(@DrawableRes int imageId) { - this.imageId = imageId; - return this; - } - - public boolean isSupportJava() { - return this.isSupportJava; - } - - public ProjectTemplate setSupportJava(boolean isSupportJava) { - this.isSupportJava = isSupportJava; - return this; - } - - public boolean isSupportKotlin() { - return this.isSupportKotlin; - } - - public ProjectTemplate setSupportKotlin(boolean isSupportKotlin) { - this.isSupportKotlin = isSupportKotlin; - return this; - } - - public boolean isCpp() { - return this.isCpp; - } - - public ProjectTemplate setIsCpp(boolean isCpp) { - this.isCpp = isCpp; - return this; - } -} diff --git a/app/src/main/java/com/itsaky/androidide/models/StepResult.kt b/app/src/main/java/com/itsaky/androidide/models/StepResult.kt deleted file mode 100644 index 8f9d165454..0000000000 --- a/app/src/main/java/com/itsaky/androidide/models/StepResult.kt +++ /dev/null @@ -1,8 +0,0 @@ -package com.itsaky.androidide.models - -data class StepResult( - val stepId: Int, - val wasSuccessful: Boolean, - val output: String, - val error: String? = null -) \ No newline at end of file diff --git a/app/src/main/java/com/itsaky/androidide/models/StorageInfo.kt b/app/src/main/java/com/itsaky/androidide/models/StorageInfo.kt deleted file mode 100644 index d721704ce4..0000000000 --- a/app/src/main/java/com/itsaky/androidide/models/StorageInfo.kt +++ /dev/null @@ -1,7 +0,0 @@ -package com.itsaky.androidide.models - -data class StorageInfo( - val isLowStorage: Boolean, - val availableBytes: Long, - val additionalBytesNeeded: Long -) diff --git a/app/src/main/java/com/itsaky/androidide/models/Symbol.kt b/app/src/main/java/com/itsaky/androidide/models/Symbol.kt deleted file mode 100644 index 663cd27b7d..0000000000 --- a/app/src/main/java/com/itsaky/androidide/models/Symbol.kt +++ /dev/null @@ -1,56 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ -package com.itsaky.androidide.models - -/** - * A symbol that is shown in the [SymbolInputView][com.itsaky.androidide.ui.SymbolInputView]. - * - * @author Akash Yadav - */ -open class Symbol @JvmOverloads constructor( - open val label: String, - open val commit: String, - open val offset: Int = 1, - open val description: String = label -) { - @JvmOverloads - constructor(both: String, offset: Int = 1) : this(both, both, offset) - - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (other !is Symbol) return false - - if (label != other.label) return false - if (commit != other.commit) return false - if (offset != other.offset) return false - if (description != other.description) return false - - return true - } - - override fun hashCode(): Int { - var result = label.hashCode() - result = 31 * result + commit.hashCode() - result = 31 * result + offset - result = 31 * result + description.hashCode() - return result - } - - override fun toString(): String { - return "Symbol(label='$label', commit='$commit', offset=$offset, description='$description')" - } -} \ No newline at end of file diff --git a/app/src/main/java/com/itsaky/androidide/preferences/buildAndRunPrefExts.kt b/app/src/main/java/com/itsaky/androidide/preferences/buildAndRunPrefExts.kt deleted file mode 100644 index 47c7614ee1..0000000000 --- a/app/src/main/java/com/itsaky/androidide/preferences/buildAndRunPrefExts.kt +++ /dev/null @@ -1,115 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.preferences - -import com.itsaky.androidide.R -import com.itsaky.androidide.idetooltips.TooltipTag.PREFS_BUILDRUN_AUTOLAUNCH -import com.itsaky.androidide.idetooltips.TooltipTag.PREFS_BUILDRUN_FLAGS -import com.itsaky.androidide.idetooltips.TooltipTag.PREFS_BUILDRUN_FLAGS_BUILDCACHE -import com.itsaky.androidide.idetooltips.TooltipTag.PREFS_BUILDRUN_FLAGS_DEBUG -import com.itsaky.androidide.idetooltips.TooltipTag.PREFS_BUILDRUN_FLAGS_INFO -import com.itsaky.androidide.idetooltips.TooltipTag.PREFS_BUILDRUN_FLAGS_OFFLINE -import com.itsaky.androidide.idetooltips.TooltipTag.PREFS_BUILDRUN_FLAGS_SCAN -import com.itsaky.androidide.idetooltips.TooltipTag.PREFS_BUILDRUN_FLAGS_STACKTRACE -import com.itsaky.androidide.idetooltips.TooltipTag.PREFS_BUILDRUN_FLAGS_WARNINGMODEALL -import com.itsaky.androidide.idetooltips.TooltipTag.PREFS_BUILD_RUN -import com.itsaky.androidide.preferences.internal.BuildPreferences.GRADLE_COMMANDS -import com.itsaky.androidide.preferences.internal.BuildPreferences.LAUNCH_APP_AFTER_INSTALL -import com.itsaky.androidide.preferences.internal.BuildPreferences.isBuildCacheEnabled -import com.itsaky.androidide.preferences.internal.BuildPreferences.isDebugEnabled -import com.itsaky.androidide.preferences.internal.BuildPreferences.isInfoEnabled -import com.itsaky.androidide.preferences.internal.BuildPreferences.isOfflineEnabled -import com.itsaky.androidide.preferences.internal.BuildPreferences.isScanEnabled -import com.itsaky.androidide.preferences.internal.BuildPreferences.isStacktraceEnabled -import com.itsaky.androidide.preferences.internal.BuildPreferences.isWarningModeAllEnabled -import com.itsaky.androidide.preferences.internal.BuildPreferences.launchAppAfterInstall -import com.itsaky.androidide.resources.R.drawable -import com.itsaky.androidide.resources.R.string -import kotlinx.parcelize.Parcelize - -@Parcelize -class BuildAndRunPreferences( - override val key: String = "idepref_build_n_run", - override val title: Int = string.idepref_build_title, - override val summary: Int? = string.idepref_buildnrun_summary, - override val children: List = mutableListOf(), - override val tooltipTag: String = PREFS_BUILD_RUN, -) : IPreferenceScreen() { - - init { - addPreference(GradleOptions()) - addPreference(RunOptions()) - } -} - -@Parcelize -private class GradleOptions( - override val key: String = "idepref_build_gradle", - override val title: Int = string.gradle, - override val children: List = mutableListOf(), -) : IPreferenceGroup() { - - init { - addPreference(GradleCommands()) - } -} - -@Parcelize -private class GradleCommands( - override val key: String = GRADLE_COMMANDS, - override val title: Int = string.idepref_build_customgradlecommands_title, - override val summary: Int? = string.idepref_build_customgradlecommands_summary, - override val icon: Int? = drawable.ic_bash_commands, - override val tooltipTag: String = PREFS_BUILDRUN_FLAGS, -) : PropertyBasedMultiChoicePreference() { - - override fun getProperties(): List { - return listOf( - propertyEntry("--stacktrace", ::isStacktraceEnabled, PREFS_BUILDRUN_FLAGS_STACKTRACE), - propertyEntry("--info", ::isInfoEnabled, PREFS_BUILDRUN_FLAGS_INFO), - propertyEntry("--debug", ::isDebugEnabled, PREFS_BUILDRUN_FLAGS_DEBUG), - propertyEntry("--scan", ::isScanEnabled, PREFS_BUILDRUN_FLAGS_SCAN), - propertyEntry("--warning-mode all", ::isWarningModeAllEnabled, PREFS_BUILDRUN_FLAGS_WARNINGMODEALL), - propertyEntry("--build-cache", ::isBuildCacheEnabled, PREFS_BUILDRUN_FLAGS_BUILDCACHE), - propertyEntry("--offline", ::isOfflineEnabled, PREFS_BUILDRUN_FLAGS_OFFLINE), - ) - } -} - - -@Parcelize -private class RunOptions( - override val key: String = "ide.build.runOptions", - override val title: Int = R.string.title_run_options, - override val children: List = mutableListOf(), -) : IPreferenceGroup() { - - init { - addPreference(LaunchAppAfterInstall()) - } -} - -@Parcelize -private class LaunchAppAfterInstall( - override val key: String = LAUNCH_APP_AFTER_INSTALL, - override val title: Int = R.string.idepref_launchAppAfterInstall_title, - override val summary: Int? = R.string.idepref_launchAppAfterInstall_summary, - override val icon: Int? = drawable.ic_open_external, - override val tooltipTag: String = PREFS_BUILDRUN_AUTOLAUNCH, -) : - SwitchPreference(setValue = ::launchAppAfterInstall::set, getValue = ::launchAppAfterInstall::get) diff --git a/app/src/main/java/com/itsaky/androidide/projects/builder/BuildResult.kt b/app/src/main/java/com/itsaky/androidide/projects/builder/BuildResult.kt deleted file mode 100644 index 9bda02982c..0000000000 --- a/app/src/main/java/com/itsaky/androidide/projects/builder/BuildResult.kt +++ /dev/null @@ -1,7 +0,0 @@ -package com.itsaky.androidide.projects.builder - -data class BuildResult( - val isSuccess: Boolean, - val message: String, - val launchResult: LaunchResult? = null -) \ No newline at end of file diff --git a/app/src/main/java/com/itsaky/androidide/projects/builder/LaunchResult.kt b/app/src/main/java/com/itsaky/androidide/projects/builder/LaunchResult.kt deleted file mode 100644 index 929908cc66..0000000000 --- a/app/src/main/java/com/itsaky/androidide/projects/builder/LaunchResult.kt +++ /dev/null @@ -1,3 +0,0 @@ -package com.itsaky.androidide.projects.builder - -data class LaunchResult(val isSuccess: Boolean, val message: String) \ No newline at end of file diff --git a/app/src/main/java/com/itsaky/androidide/provider/IDEDocumentsProvider.java b/app/src/main/java/com/itsaky/androidide/provider/IDEDocumentsProvider.java deleted file mode 100644 index ac368a1f4d..0000000000 --- a/app/src/main/java/com/itsaky/androidide/provider/IDEDocumentsProvider.java +++ /dev/null @@ -1,330 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.provider; - -import android.content.res.AssetFileDescriptor; -import android.database.Cursor; -import android.database.MatrixCursor; -import android.graphics.Point; -import android.os.CancellationSignal; -import android.os.ParcelFileDescriptor; -import android.provider.DocumentsContract.Document; -import android.provider.DocumentsContract.Root; -import android.provider.DocumentsProvider; -import android.webkit.MimeTypeMap; -import androidx.annotation.NonNull; -import com.itsaky.androidide.resources.R; -import com.itsaky.androidide.utils.Environment; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.Collections; -import java.util.LinkedList; -import java.util.Locale; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * A document provider for the Storage Access Framework which exposes the files in the $HOME/ - * directory to other apps. - * - *

Note that this replaces providing an activity matching the ACTION_GET_CONTENT intent: - * - *

"A document provider and ACTION_GET_CONTENT should be considered mutually exclusive. If you - * support both of them simultaneously, your app will appear twice in the system picker UI, offering - * two different ways of accessing your stored data. This would be confusing for users." - - * http://developer.android.com/guide/topics/providers/document-provider.html#43 - * - * @see TermuxDocumentsProvider - */ -public class IDEDocumentsProvider extends DocumentsProvider { - - private static final String ALL_MIME_TYPES = "*/*"; - private static final Logger LOG = LoggerFactory.getLogger(IDEDocumentsProvider.class); - private static final File BASE_DIR = getBaseDir(); - // The default columns to return information about a root if no specific - // columns are requested in a query. - private static final String[] DEFAULT_ROOT_PROJECTION = - new String[]{ - Root.COLUMN_ROOT_ID, - Root.COLUMN_MIME_TYPES, - Root.COLUMN_FLAGS, - Root.COLUMN_ICON, - Root.COLUMN_TITLE, - Root.COLUMN_SUMMARY, - Root.COLUMN_DOCUMENT_ID, - Root.COLUMN_AVAILABLE_BYTES - }; - // The default columns to return information about a document if no specific - // columns are requested in a query. - private static final String[] DEFAULT_DOCUMENT_PROJECTION = - new String[]{ - Document.COLUMN_DOCUMENT_ID, - Document.COLUMN_MIME_TYPE, - Document.COLUMN_DISPLAY_NAME, - Document.COLUMN_LAST_MODIFIED, - Document.COLUMN_FLAGS, - Document.COLUMN_SIZE - }; - - @NonNull - private static File getBaseDir() { - if (Environment.HOME != null) { - return Environment.HOME; - } - - return new File(Environment.DEFAULT_HOME); - } - - @Override - public boolean onCreate() { - return true; - } - - @Override - public boolean isChildDocument(String parentDocumentId, String documentId) { - return documentId.startsWith(parentDocumentId); - } - - @Override - public String createDocument(String parentDocumentId, String mimeType, String displayName) - throws FileNotFoundException { - File newFile = new File(parentDocumentId, displayName); - int noConflictId = 2; - while (newFile.exists()) { - newFile = new File(parentDocumentId, displayName + " (" + noConflictId++ + ")"); - } - try { - boolean succeeded; - if (Document.MIME_TYPE_DIR.equals(mimeType)) { - succeeded = newFile.mkdir(); - } else { - succeeded = newFile.createNewFile(); - } - if (!succeeded) { - throw new FileNotFoundException("Failed to create document with id " + newFile.getPath()); - } - } catch (IOException e) { - throw new FileNotFoundException("Failed to create document with id " + newFile.getPath()); - } - return newFile.getPath(); - } - - @Override - public void deleteDocument(String documentId) throws FileNotFoundException { - File file = getFileForDocId(documentId); - if (!file.delete()) { - throw new FileNotFoundException("Failed to delete document with id " + documentId); - } - } - - @Override - public Cursor queryRoots(String[] projection) { - final MatrixCursor result = - new MatrixCursor(projection != null ? projection : DEFAULT_ROOT_PROJECTION); - final String applicationName = getContext().getString(R.string.app_name); - - final MatrixCursor.RowBuilder row = result.newRow(); - LOG.debug("queryRoots() before all add"); - row.add(Root.COLUMN_ROOT_ID, getDocIdForFile(BASE_DIR)); - LOG.debug("queryRoots() before all add, 1"); - row.add(Root.COLUMN_DOCUMENT_ID, getDocIdForFile(BASE_DIR)); - LOG.debug("queryRoots() before all add, 2"); - row.add(Root.COLUMN_SUMMARY, null); - LOG.debug("queryRoots() before all add, 3"); - row.add( - Root.COLUMN_FLAGS, - Root.FLAG_SUPPORTS_CREATE | Root.FLAG_SUPPORTS_SEARCH | Root.FLAG_SUPPORTS_IS_CHILD); - LOG.debug("queryRoots() before all add, 4"); - row.add(Root.COLUMN_TITLE, applicationName); - LOG.debug("queryRoots() before all add, 5"); - row.add(Root.COLUMN_MIME_TYPES, ALL_MIME_TYPES); - LOG.debug("queryRoots() before all add, 6"); - row.add(Root.COLUMN_AVAILABLE_BYTES, BASE_DIR.getFreeSpace()); - LOG.debug("queryRoots() before all add, 7"); - row.add(Root.COLUMN_ICON, R.drawable.ic_launcher_foreground); - LOG.debug("queryRoots() before all add"); - return result; - } - - /** - * Get the document id given a file. This document id must be consistent across time as other - * applications may save the ID and use it to reference documents later. - * - *

The reverse of @{link #getFileForDocId}. - */ - private static String getDocIdForFile(File file) { - return file.getAbsolutePath(); - } - - @Override - public Cursor queryDocument(String documentId, String[] projection) throws FileNotFoundException { - final MatrixCursor result = - new MatrixCursor(projection != null ? projection : DEFAULT_DOCUMENT_PROJECTION); - includeFile(result, documentId, null); - return result; - } - - @Override - public Cursor queryChildDocuments(String parentDocumentId, String[] projection, String sortOrder) - throws FileNotFoundException { - final MatrixCursor result = - new MatrixCursor(projection != null ? projection : DEFAULT_DOCUMENT_PROJECTION); - final File parent = getFileForDocId(parentDocumentId); - for (File file : parent.listFiles()) { - includeFile(result, null, file); - } - return result; - } - - @Override - public Cursor querySearchDocuments(String rootId, String query, String[] projection) - throws FileNotFoundException { - final MatrixCursor result = - new MatrixCursor(projection != null ? projection : DEFAULT_DOCUMENT_PROJECTION); - final File parent = getFileForDocId(rootId); - - // This example implementation searches file names for the query and doesn't rank search - // results, so we can stop as soon as we find a sufficient number of matches. Other - // implementations might rank results and use other data about files, rather than the file - // name, to produce a match. - final LinkedList pending = new LinkedList<>(); - pending.add(parent); - - final int MAX_SEARCH_RESULTS = 50; - while (!pending.isEmpty() && result.getCount() < MAX_SEARCH_RESULTS) { - final File file = pending.removeFirst(); - // Avoid directories outside the $HOME directory linked with symlinks (to avoid e.g. - // search - // through the whole SD card). - boolean isInsideHome; - try { - isInsideHome = file.getCanonicalPath().startsWith(Environment.HOME.getAbsolutePath()); - } catch (IOException e) { - isInsideHome = true; - } - if (isInsideHome) { - if (file.isDirectory()) { - Collections.addAll(pending, file.listFiles()); - } else { - if (file.getName().toLowerCase(Locale.ROOT).contains(query)) { - includeFile(result, null, file); - } - } - } - } - - return result; - } - - @Override - public String getDocumentType(String documentId) throws FileNotFoundException { - File file = getFileForDocId(documentId); - return getMimeType(file); - } - - @Override - public ParcelFileDescriptor openDocument( - final String documentId, String mode, CancellationSignal signal) - throws FileNotFoundException { - final File file = getFileForDocId(documentId); - final int accessMode = ParcelFileDescriptor.parseMode(mode); - return ParcelFileDescriptor.open(file, accessMode); - } - - @Override - public AssetFileDescriptor openDocumentThumbnail( - String documentId, Point sizeHint, CancellationSignal signal) throws FileNotFoundException { - final File file = getFileForDocId(documentId); - final ParcelFileDescriptor pfd = - ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY); - return new AssetFileDescriptor(pfd, 0, file.length()); - } - - /** - * Add a representation of a file to a cursor. - * - * @param result the cursor to modify - * @param docId the document ID representing the desired file (may be null if given file) - * @param file the File object representing the desired file (may be null if given docID) - */ - private void includeFile(MatrixCursor result, String docId, File file) - throws FileNotFoundException { - if (docId == null) { - docId = getDocIdForFile(file); - } else { - file = getFileForDocId(docId); - } - - int flags = 0; - if (file.isDirectory()) { - if (file.canWrite()) { - flags |= Document.FLAG_DIR_SUPPORTS_CREATE; - } - } else if (file.canWrite()) { - flags |= Document.FLAG_SUPPORTS_WRITE; - } - if (file.getParentFile().canWrite()) { - flags |= Document.FLAG_SUPPORTS_DELETE; - } - - final String displayName = file.getName(); - final String mimeType = getMimeType(file); - if (mimeType.startsWith("image/")) { - flags |= Document.FLAG_SUPPORTS_THUMBNAIL; - } - - final MatrixCursor.RowBuilder row = result.newRow(); - row.add(Document.COLUMN_DOCUMENT_ID, docId); - row.add(Document.COLUMN_DISPLAY_NAME, displayName); - row.add(Document.COLUMN_SIZE, file.length()); - row.add(Document.COLUMN_MIME_TYPE, mimeType); - row.add(Document.COLUMN_LAST_MODIFIED, file.lastModified()); - row.add(Document.COLUMN_FLAGS, flags); - row.add(Document.COLUMN_ICON, R.mipmap.ic_launcher); - } - - /** - * Get the file given a document id (the reverse of {@link #getDocIdForFile(File)}). - */ - private static File getFileForDocId(String docId) throws FileNotFoundException { - final File f = new File(docId); - if (!f.exists()) { - throw new FileNotFoundException(f.getAbsolutePath() + " not found"); - } - return f; - } - - private static String getMimeType(File file) { - if (file.isDirectory()) { - return Document.MIME_TYPE_DIR; - } else { - final String name = file.getName(); - final int lastDot = name.lastIndexOf('.'); - if (lastDot >= 0) { - final String extension = name.substring(lastDot + 1).toLowerCase(Locale.ROOT); - final String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); - if (mime != null) { - return mime; - } - } - return "application/octet-stream"; - } - } -} diff --git a/app/src/main/java/com/itsaky/androidide/repositories/BreakpointRepository.kt b/app/src/main/java/com/itsaky/androidide/repositories/BreakpointRepository.kt deleted file mode 100644 index e361d9f799..0000000000 --- a/app/src/main/java/com/itsaky/androidide/repositories/BreakpointRepository.kt +++ /dev/null @@ -1,112 +0,0 @@ -package com.itsaky.androidide.repositories - -import android.util.Log -import com.google.gson.Gson -import com.google.gson.GsonBuilder -import com.google.gson.reflect.TypeToken -import com.itsaky.androidide.lsp.debug.model.BreakpointDefinition -import com.itsaky.androidide.lsp.debug.model.PositionalBreakpoint -import com.itsaky.androidide.lsp.debug.model.MethodBreakpoint -import com.itsaky.androidide.tooling.api.util.RuntimeTypeAdapterFactory -import com.itsaky.androidide.utils.Environment -import io.sentry.Sentry -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.withContext -import java.io.File - - -typealias StoredBreakpointsType = List - -private val StoredBreakpointsTypeToken = object : TypeToken() {} - -/** - * Repository responsible for persisting and retrieving breakpoints - * for a given project. Breakpoints are serialized/deserialized - * using Gson and stored in the project editor cache directory. - */ -object BreakpointRepository { - private const val BREAKPOINT_FILE_NAME = "breakpoints.json" - - private val bpAdapter = - RuntimeTypeAdapterFactory.of(BreakpointDefinition::class.java, "kind") - .registerSubtype(PositionalBreakpoint::class.java, "positional") - .registerSubtype(MethodBreakpoint::class.java, "method") - - private val gson: Gson = GsonBuilder() - .registerTypeAdapterFactory(bpAdapter) - .create() - - /** - * Returns the file where breakpoints are stored for the given project. - * - * @param projectDir The project directory. - * @return [File] representing the JSON file containing stored breakpoints. - */ - fun getBreakpointsStorageFile(projectDir: File): File { - return Environment.getProjectCacheDir(projectDir).resolve("editor/$BREAKPOINT_FILE_NAME") - } - - /** - * Reads and deserializes the list of breakpoints from disk. - */ - suspend fun getStoredBreakpoints(projectDir: File): StoredBreakpointsType { - val breakpointFile = getBreakpointsStorageFile(projectDir) - - return withContext(Dispatchers.IO) { - if (!breakpointFile.exists()) { - return@withContext emptyList() - } - - try { - val jsonString = breakpointFile.readText() - if (jsonString.isBlank()) { - return@withContext emptyList() - } - - gson.fromJson( - jsonString, - StoredBreakpointsTypeToken.type - ) ?: emptyList() - } catch (e: Exception) { - e.printStackTrace() - emptyList() - } - } - } - - /** - * Serializes and saves the given list of breakpoints to disk. - * - * Serialization is done on [Dispatchers.Default] (CPU-bound), - * and writing is performed on [Dispatchers.IO] (I/O-bound). - * - * @param projectDir The project directory. - * @param breakpoints List of [BreakpointDefinition] to save. - */ - suspend fun saveBreakpoints( - projectDir: File, - breakpoints: StoredBreakpointsType - ) { - val file = getBreakpointsStorageFile(projectDir) - - val jsonOut = withContext(Dispatchers.Default) { - gson.toJson(breakpoints, StoredBreakpointsTypeToken.type) - } - - withContext(Dispatchers.IO) { - try { - file.parentFile?.mkdirs() - if (!file.exists()) file.createNewFile() - - file.writeText(jsonOut) - } catch (e: Exception) { - Log.e( - "BreakpointManager", - "Failed to save breakpoints to file: ${file.absolutePath}", - e - ) - Sentry.captureException(e) - } - } - } -} \ No newline at end of file diff --git a/app/src/main/java/com/itsaky/androidide/repositories/PluginRepository.kt b/app/src/main/java/com/itsaky/androidide/repositories/PluginRepository.kt deleted file mode 100644 index 88a32ca7e1..0000000000 --- a/app/src/main/java/com/itsaky/androidide/repositories/PluginRepository.kt +++ /dev/null @@ -1,58 +0,0 @@ -package com.itsaky.androidide.repositories - -import android.net.Uri -import com.itsaky.androidide.plugins.PluginInfo -import com.itsaky.androidide.plugins.PluginMetadata -import java.io.File - -/** - * Repository interface for plugin operations - * Defines the contract for plugin data operations - */ -interface PluginRepository { - - /** - * Get all available plugins - */ - suspend fun getAllPlugins(): Result> - - /** - * Enable a plugin by ID - */ - suspend fun enablePlugin(pluginId: String): Result - - /** - * Disable a plugin by ID - */ - suspend fun disablePlugin(pluginId: String): Result - - /** - * Uninstall a plugin by ID - */ - suspend fun uninstallPlugin(pluginId: String): Result - - /** - * Read plugin metadata from a file without installing it - */ - suspend fun getPluginMetadataFromFile(pluginFile: File): Result - - /** - * Returns true if the incoming file's signing certificate matches the installed plugin's certificate - */ - suspend fun haveMatchingSignatures(incomingFile: File, existingPluginId: String): Result - - /** - * Install a plugin from file - */ - suspend fun installPluginFromFile(pluginFile: File): Result - - /** - * Reload all plugins - */ - suspend fun reloadPlugins(): Result - - /** - * Check if plugin manager is available - */ - fun isPluginManagerAvailable(): Boolean -} \ No newline at end of file diff --git a/app/src/main/java/com/itsaky/androidide/roomData/recentproject/RecentProject.kt b/app/src/main/java/com/itsaky/androidide/roomData/recentproject/RecentProject.kt deleted file mode 100644 index bed87d9068..0000000000 --- a/app/src/main/java/com/itsaky/androidide/roomData/recentproject/RecentProject.kt +++ /dev/null @@ -1,22 +0,0 @@ -package com.itsaky.androidide.roomData.recentproject - -import androidx.room.ColumnInfo -import androidx.room.Entity -import androidx.room.Index -import androidx.room.PrimaryKey - -@Entity( - tableName = "recent_project_table", - indices = [Index(value = ["location"], unique = true)] -) -data class RecentProject( - @PrimaryKey(autoGenerate = true) - @ColumnInfo(name = "id") val id: Int = 0, - @ColumnInfo(name = "name") val name: String, - @ColumnInfo(name = "create_at") val createdAt: String, - @ColumnInfo(name = "location") val location: String, - @ColumnInfo(name = "last_modified") val lastModified: String = "0", - @ColumnInfo(name = "template_name") val templateName: String = "unknown", - @ColumnInfo(name = "language") val language: String = "unknown" -) - diff --git a/app/src/main/java/com/itsaky/androidide/services/builder/BuildProfile.kt b/app/src/main/java/com/itsaky/androidide/services/builder/BuildProfile.kt deleted file mode 100644 index 0e3789b01d..0000000000 --- a/app/src/main/java/com/itsaky/androidide/services/builder/BuildProfile.kt +++ /dev/null @@ -1,10 +0,0 @@ -package com.itsaky.androidide.services.builder - -/** - * A build profile for tuning Gradle builds. - * - * @author Akash Yadav - */ -data class BuildProfile( - val isDebugBuild: Boolean, -) diff --git a/app/src/main/java/com/itsaky/androidide/services/builder/GradleBuildServiceConnnection.kt b/app/src/main/java/com/itsaky/androidide/services/builder/GradleBuildServiceConnnection.kt deleted file mode 100644 index eb813b4f5d..0000000000 --- a/app/src/main/java/com/itsaky/androidide/services/builder/GradleBuildServiceConnnection.kt +++ /dev/null @@ -1,48 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.services.builder - -import android.content.ComponentName -import android.content.ServiceConnection -import android.os.IBinder -import org.slf4j.LoggerFactory - -/** - * [ServiceConnection] for [GradleBuildService]. - * - * @author Akash Yadav - */ -class GradleBuildServiceConnnection : ServiceConnection { - - internal var onConnected: ((GradleBuildService) -> Unit)? = null - - companion object { - - private val log = LoggerFactory.getLogger(GradleBuildServiceConnnection::class.java) - } - - override fun onServiceConnected(name: ComponentName?, service: IBinder?) { - val serviceBinder = service as GradleServiceBinder - onConnected?.invoke(serviceBinder.service!!) - } - - override fun onServiceDisconnected(name: ComponentName?) { - onConnected = null - log.info("Disconnected from Gradle build service") - } -} \ No newline at end of file diff --git a/app/src/main/java/com/itsaky/androidide/services/builder/util.kt b/app/src/main/java/com/itsaky/androidide/services/builder/util.kt deleted file mode 100644 index 1c012c90cf..0000000000 --- a/app/src/main/java/com/itsaky/androidide/services/builder/util.kt +++ /dev/null @@ -1,33 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.services.builder - -import com.itsaky.androidide.preferences.internal.BuildPreferences -import com.itsaky.androidide.tooling.api.messages.GradleDistributionParams - -/** - * The distribution params. This considers [gradleInstallationDir] preference as well. - */ -val gradleDistributionParams: GradleDistributionParams - get() { - if (BuildPreferences.gradleInstallationDir.isBlank()) { - return GradleDistributionParams.WRAPPER - } - - return GradleDistributionParams.forInstallationDir(BuildPreferences.gradleInstallationDir) - } \ No newline at end of file diff --git a/app/src/main/java/com/itsaky/androidide/services/debug/DebugOverlayManager.kt b/app/src/main/java/com/itsaky/androidide/services/debug/DebugOverlayManager.kt deleted file mode 100644 index 42652f598a..0000000000 --- a/app/src/main/java/com/itsaky/androidide/services/debug/DebugOverlayManager.kt +++ /dev/null @@ -1,215 +0,0 @@ -package com.itsaky.androidide.services.debug - -import android.content.Context -import android.graphics.PixelFormat -import android.hardware.display.DisplayManager -import android.view.ContextThemeWrapper -import android.view.Gravity -import android.view.LayoutInflater -import android.view.MotionEvent -import android.view.ViewConfiguration -import android.view.WindowManager -import android.widget.Toast -import android.provider.Settings -import androidx.core.content.ContextCompat -import androidx.core.hardware.display.DisplayManagerCompat -import com.itsaky.androidide.R -import com.itsaky.androidide.actions.ActionItem -import com.itsaky.androidide.actions.ActionsRegistry -import com.itsaky.androidide.databinding.DebuggerActionsWindowBinding -import com.itsaky.androidide.idetooltips.TooltipManager -import com.itsaky.androidide.idetooltips.TooltipTag -import com.itsaky.androidide.utils.PermissionsHelper -import com.itsaky.androidide.utils.isAtLeastR -import org.slf4j.LoggerFactory -import kotlin.math.abs - -/** - * Manages interaction with the actions shown in the debugger overlay window. - * - * @author Akash Yadav - */ -class DebugOverlayManager private constructor( - private val windowManager: WindowManager, - private val binding: DebuggerActionsWindowBinding, - val attachedDisplayId: Int, - private val touchSlop: Int = ViewConfiguration.get(binding.root.context).scaledTouchSlop, -) { - private var initialWindowX = 0 - private var initialWindowY = 0 - private var initialTouchX = 0f - private var initialTouchY = 0f - private var isDragging = false - - init { - binding.dragHandle.root.isLongClickable = true - binding.dragHandle.root.icon = - ContextCompat.getDrawable(binding.root.context, R.drawable.ic_drag_handle) - - binding.dragHandle.root.setOnTouchListener { v, event -> - when (event.action) { - MotionEvent.ACTION_DOWN -> { - initialWindowX = overlayLayoutParams.x - initialWindowY = overlayLayoutParams.y - initialTouchX = event.rawX - initialTouchY = event.rawY - isDragging = false - false - } - - MotionEvent.ACTION_MOVE -> { - val deltaX = (event.rawX - initialTouchX).toInt() - val deltaY = (event.rawY - initialTouchY).toInt() - if (isDragging || abs(deltaX) > touchSlop || abs(deltaY) > touchSlop) { - isDragging = true - v.isPressed = false - v.parent.requestDisallowInterceptTouchEvent(true) - overlayLayoutParams.x = initialWindowX + deltaX - overlayLayoutParams.y = initialWindowY + deltaY - windowManager.updateViewLayout(binding.root, overlayLayoutParams) - true - } else false - } - - MotionEvent.ACTION_UP -> { - if (isDragging) { - isDragging = false - true - } else { - v.performClick() - false - } - } - - MotionEvent.ACTION_CANCEL -> { - isDragging = false - false - } - - else -> false - } - } - - binding.dragHandle.root.setOnLongClickListener { view -> - TooltipManager.showIdeCategoryTooltip( - context = view.context, - anchorView = view.rootView, - tag = TooltipTag.DEBUGGER_ACTION_MOVE - ) - true - } - } - - private var isShown = false - private val overlayLayoutParams by lazy { - WindowManager.LayoutParams( - /* w = */ WindowManager.LayoutParams.WRAP_CONTENT, - /* h = */ WindowManager.LayoutParams.WRAP_CONTENT, - /* _type = */ WM_OVERLAY_TYPE, - /* _flags = */ WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, - /* _format = */ PixelFormat.TRANSLUCENT - ).apply { - gravity = Gravity.TOP or Gravity.CENTER_HORIZONTAL - } - } - - fun show() { - if (isShown) { - return - } - - val ctx = binding.root.context - - if (!Settings.canDrawOverlays(ctx)) { - logger.warn("Overlay permission denied. Skipping debugger overlay window.") - - val state = PermissionsHelper.getOverlayPermissionState(ctx) - val message = if (state == PermissionsHelper.OverlayPermissionState.UNSUPPORTED) { - ctx.getString(R.string.permission_overlay_unsupported_hint) - } else { - ctx.getString(R.string.permission_overlay_restricted_settings_hint) - } - Toast.makeText(ctx, message, Toast.LENGTH_LONG).show() - return - } - - try { - windowManager.addView(binding.root, overlayLayoutParams) - isShown = true - } catch (err: Throwable) { - logger.error("Failed to show debugger overlay window", err) - } - } - - fun hide() { - if (!isShown) { - return - } - - try { - windowManager.removeView(binding.root) - } catch (err: Throwable) { - logger.error("Failed to hide debugger overlay window", err) - } finally { - isShown = false - } - } - - fun refreshActions() { - // noinspection NotifyDataSetChanged - binding.actions.adapter?.notifyDataSetChanged() - } - - companion object { - - private val logger = LoggerFactory.getLogger(DebugOverlayManager::class.java) - private const val WM_OVERLAY_TYPE = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY - - /** * Create a new [DebugOverlayManager] from the given [Context]. - * - * @param ctx The [Context] to use for creating the [DebugOverlayManager]. - * @return A new [DebugOverlayManager]. - */ - fun create(ctx: Context, displayId: Int = -1): DebugOverlayManager { - val windowContext = run { - if (displayId == -1) { - logger.debug("no display id provided. overlay will be shown on default display") - return@run ctx - } - - logger.debug("trying to get window context for displayId={}", displayId) - val displayManager = DisplayManagerCompat.getInstance(ctx) - val targetDisplay = displayManager.getDisplay(displayId) - val displayContext = - if (targetDisplay != null) ctx.createDisplayContext(targetDisplay) else ctx - - if (isAtLeastR()) { - displayContext.createWindowContext(WM_OVERLAY_TYPE, null) - } else displayContext - } - - // IMPORTANT! - // Wrap the context with a theme, so we could use MaterialButtons! - val context = ContextThemeWrapper(windowContext, R.style.Theme_AndroidIDE) - val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager - val inflater = LayoutInflater.from(context) - - // noinspection InflateParams - val layout = DebuggerActionsWindowBinding.inflate(inflater) - - val actionsRegistry = ActionsRegistry.getInstance() - val debuggerActions = actionsRegistry.getActions(ActionItem.Location.DEBUGGER_ACTIONS) - - val actions = debuggerActions.values.toList() - val adapter = DebuggerActionsOverlayAdapter(actions) - layout.actions.adapter = adapter - - logger.debug("overlay manager created for display {}", displayId) - return DebugOverlayManager( - windowManager = windowManager, - binding = layout, - attachedDisplayId = displayId, - ) - } - } -} \ No newline at end of file diff --git a/app/src/main/java/com/itsaky/androidide/services/debug/DebuggerActionsOverlayAdapter.kt b/app/src/main/java/com/itsaky/androidide/services/debug/DebuggerActionsOverlayAdapter.kt deleted file mode 100644 index 399e9f6035..0000000000 --- a/app/src/main/java/com/itsaky/androidide/services/debug/DebuggerActionsOverlayAdapter.kt +++ /dev/null @@ -1,63 +0,0 @@ -package com.itsaky.androidide.services.debug - -import android.view.LayoutInflater -import android.view.ViewGroup -import androidx.appcompat.widget.TooltipCompat -import androidx.recyclerview.widget.RecyclerView -import com.itsaky.androidide.actions.ActionData -import com.itsaky.androidide.actions.ActionItem -import com.itsaky.androidide.actions.ActionsRegistry -import com.itsaky.androidide.actions.internal.DefaultActionsRegistry -import com.itsaky.androidide.editor.databinding.LayoutPopupMenuItemBinding -import com.itsaky.androidide.idetooltips.TooltipManager - -/** - * @author Akash Yadav - */ -class DebuggerActionsOverlayAdapter( - actions: List, -): RecyclerView.Adapter() { - - private val actions = actions.sortedBy { action -> action.order } - private val actionsRegister = ActionsRegistry.getInstance() as DefaultActionsRegistry - - class VH( - val binding: LayoutPopupMenuItemBinding - ): RecyclerView.ViewHolder(binding.root) - - override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH { - val inflater = LayoutInflater.from(parent.context) - val binding = LayoutPopupMenuItemBinding.inflate(inflater, parent, false) - return VH(binding) - } - - override fun getItemCount() = actions.size - - override fun onBindViewHolder(holder: VH, position: Int) { - val binding = holder.binding - val action = actions[position] - val data = ActionData.create(binding.root.context) - - action.prepare(data) - - binding.root.icon = action.icon - binding.root.alpha = if (action.enabled) 1f else 0.5f - TooltipCompat.setTooltipText(binding.root, action.label) - - binding.root.apply { - setOnClickListener { - if (action.enabled) { - actionsRegister.executeAction(action, data) - } - } - setOnLongClickListener { - TooltipManager.showIdeCategoryTooltip( - context = this.context, - anchorView = this.rootView, - tag = action.tooltipTag - ) - true - } - } - } -} \ No newline at end of file diff --git a/app/src/main/java/com/itsaky/androidide/services/log/CachingLogSender.kt b/app/src/main/java/com/itsaky/androidide/services/log/CachingLogSender.kt deleted file mode 100644 index 5f72c1ecce..0000000000 --- a/app/src/main/java/com/itsaky/androidide/services/log/CachingLogSender.kt +++ /dev/null @@ -1,51 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.services.log - -import com.itsaky.androidide.logsender.ILogSender - -/** - * An implementation of [ILogSender] which caches the ID, PID and package name from the provided sender. - * - * @author Akash Yadav - */ -class CachingLogSender( - private val sender: ILogSender, - internal val port: Int, - internal var isStarted: Boolean -) : ILogSender by sender { - - private var cachedPid: Int = -1 - private var cachedId: String? = null - private var cachedPckName: String? = null - - override fun getPid(): Int { - if (this.cachedPid != -1) { - return this.cachedPid - } - return sender.pid.also { this.cachedPid = it } - } - - override fun getPackageName(): String { - return this.cachedPckName ?: sender.packageName.also { this.cachedPckName = it } - } - - override fun getId(): String { - return this.cachedId ?: sender.id.also { this.cachedId = it } - } -} \ No newline at end of file diff --git a/app/src/main/java/com/itsaky/androidide/services/log/ConnectionObserverParams.kt b/app/src/main/java/com/itsaky/androidide/services/log/ConnectionObserverParams.kt deleted file mode 100644 index 49495f2af8..0000000000 --- a/app/src/main/java/com/itsaky/androidide/services/log/ConnectionObserverParams.kt +++ /dev/null @@ -1,55 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.services.log - -import android.content.Intent -import android.os.Bundle - -/** - * Arguments passed to a connection observer from [LogReceiverImpl]. - * - * @property clientId The unique identifier for the client that was connected or disconnected. - * @property totalConnections The total number of connections after this client was connected/disconnected. - * @author Akash Yadav - */ -data class ConnectionObserverParams(val clientId: String, val totalConnections: Int) { - - companion object { - - const val KEY_CLIENT_ID = "com.itsaky.androidide.logreceiver.connectedClientId" - const val KEY_CONNECTION_COUNT = "com.itsaky.androidide.logreceiver.connectionCount" - - @JvmStatic - internal fun from(intent: Intent?): ConnectionObserverParams? { - val clientId = intent?.getStringExtra(KEY_CLIENT_ID) ?: return null - val connectionCount = intent.getIntExtra(KEY_CONNECTION_COUNT, -1) - if (connectionCount == -1) { - return null - } - - return ConnectionObserverParams(clientId, connectionCount) - } - } - - internal fun bundle(): Bundle { - return Bundle().apply { - putString(KEY_CLIENT_ID, clientId) - putInt(KEY_CONNECTION_COUNT, totalConnections) - } - } -} diff --git a/app/src/main/java/com/itsaky/androidide/services/log/LogReceiverService.kt b/app/src/main/java/com/itsaky/androidide/services/log/LogReceiverService.kt deleted file mode 100644 index 623cdf7ec3..0000000000 --- a/app/src/main/java/com/itsaky/androidide/services/log/LogReceiverService.kt +++ /dev/null @@ -1,166 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.services.log - -import android.app.Service -import android.content.Intent -import android.os.IBinder -import androidx.localbroadcastmanager.content.LocalBroadcastManager -import com.itsaky.androidide.logsender.LogSender -import com.itsaky.androidide.lookup.Lookup -import com.itsaky.androidide.models.LogLine -import com.itsaky.androidide.preferences.internal.DevOpsPreferences -import org.slf4j.LoggerFactory -import java.util.concurrent.Executors -import java.util.concurrent.TimeUnit -import java.util.concurrent.atomic.AtomicBoolean - -/** - * Service for handling log lines that are sent by the client applications. - * - * @author Akash Yadav - */ -class LogReceiverService : Service() { - - private val binder = LogReceiverImpl() - private val started = AtomicBoolean(false) - private val isBoundToConsumer = AtomicBoolean(false) - - private val scheduledExecutor = Executors.newSingleThreadScheduledExecutor() - - companion object { - - private val log = LoggerFactory.getLogger(LogReceiverService::class.java) - - internal const val ACTION_CONNECT_LOG_CONSUMER = "com.itsaky.androidide.logrecevier.CONNECT_LOG_CONSUMER" - internal const val ACTION_CONNECTION_UPDATE = "com.itsaky.androidide.logreceiver.CONNECTION_UPDATE" - - private const val LOG_CONSUMER_WAIT_DURATION = 10 // seconds - - @JvmStatic - internal val LOOKUP_KEY = Lookup.Key() - } - - override fun onCreate() { - super.onCreate() - Lookup.getDefault().update(LOOKUP_KEY, this) - log.info("LogReceiverService has been created") - } - - override fun onBind(intent: Intent?): IBinder? { - log.debug("Received bind request: {}", intent) - - if (!DevOpsPreferences.logsenderEnabled) { - log.debug("Rejecting bind request. LogReceiver is disabled.") - return null - } - - if (intent?.action == ACTION_CONNECT_LOG_CONSUMER) { - if (isBoundToConsumer.get()) { - log.warn("LogReceiverService is limited to one consumer only.") - return null - } - - log.info("Log consumer has been bound") - return startBinderAndGet().also { binder -> - binder.startReaders() - isBoundToConsumer.set(true) - } - } - - if (intent?.action != LogSender.SERVICE_ACTION) { - log.debug("Rejecting bind request: action={}", intent?.action) - return null - } - - log.debug("Accepting bind request...") - return startBinderAndGet().also { - if (!isBoundToConsumer.get()) { - // listen for consumers to bind to the service for next LOG_CONSUMER_WAIT_DURATION - // if the consumer still does not connect, disconnect from all senders and stop the service - listenForConsumer() - } - } - } - - override fun onUnbind(intent: Intent?): Boolean { - return super.onUnbind(intent) - } - - private fun startBinderAndGet(): LogReceiverImpl { - return binder.also { - if (!started.getAndSet(true)) { - binder.acceptSenders() - binder.connectionObserver = this::onConnectionUpdated - } - } - } - - override fun onDestroy() { - super.onDestroy() - log.debug("LogReceiverService is being destroyed...") - binder.close() - started.set(false) - try { - scheduledExecutor.shutdownNow() - } catch (e: Exception) { - // ignored - } - Lookup.getDefault().unregister(LOOKUP_KEY) - } - - fun setConsumer(consumer: ((LogLine) -> Unit)?) { - binder.consumer = consumer - } - - private fun onConnectionUpdated(params: ConnectionObserverParams) { - val intent = Intent(ACTION_CONNECTION_UPDATE) - intent.putExtras(params.bundle()) - LocalBroadcastManager.getInstance(this).sendBroadcastSync(intent) - } - - private fun listenForConsumer() { - log.debug("Waiting for log consumer...") - scheduledExecutor.schedule({ - if (!isBoundToConsumer.get()) { - // ask senders to disconnect - log.debug("No log consumer has been bound to the log receiver service") - binder.disconnectAll() - } - }, LOG_CONSUMER_WAIT_DURATION.toLong(), TimeUnit.SECONDS) - } - - /** - * Disconnects all connected log senders. Disconnecting all senders will eventually lead - * to this service being destroyed. - */ - internal fun disconnectAll() { - if (started.get()) { - binder.disconnectAll() - } - } -} - -/** - * Lookup the instance of [LogReceiverService] in the [Lookup] registry. - * - * @return The [LogReceiverService] instance or `null` it the service is not registered. - */ -fun lookupLogService(): LogReceiverService? { - return Lookup.getDefault().lookup(LogReceiverService.LOOKUP_KEY) -} diff --git a/app/src/main/java/com/itsaky/androidide/services/log/LogSenderHandler.kt b/app/src/main/java/com/itsaky/androidide/services/log/LogSenderHandler.kt deleted file mode 100644 index f28cd1a410..0000000000 --- a/app/src/main/java/com/itsaky/androidide/services/log/LogSenderHandler.kt +++ /dev/null @@ -1,81 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.services.log - -import com.itsaky.androidide.logsender.socket.SenderInfoCommand -import com.itsaky.androidide.models.LogLine -import kotlinx.coroutines.CancellationException -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.withContext -import org.slf4j.LoggerFactory -import java.net.Socket -import java.net.SocketException - -/** - * Handles a single log sender. - * - * @author Akash Yadav - */ -class LogSenderHandler(private val sender: SenderInfoCommand, private val socket: Socket, - internal var consumer: ((LogLine) -> Unit)? = null, - private var onClose: ((String) -> Unit)? = null) : AutoCloseable { - - private var manuallyClosed = false - - companion object { - - private val log = LoggerFactory.getLogger(LogSenderHandler::class.java) - } - - suspend fun startAsync() = withContext(Dispatchers.IO) { - try { - socket.getInputStream().bufferedReader().use { reader -> - while (!socket.isClosed) { - try { - LogLine.forLogString(reader.readLine())?.let { line -> consumer?.invoke(line) } - } catch (cancellation: CancellationException) { - break - } - } - } - } catch (err: SocketException) { - if (!manuallyClosed) { - log.error("An error occurred while reading from socket", err) - } - } finally { - close() - } - } - - override fun close() { - try { - manuallyClosed = true - - if (!socket.isClosed) { - log.debug("Closing log sender handler...") - socket.close() - } - } catch (err: Throwable) { - log.error("Failed to close socket", err) - } finally { - onClose?.invoke(this.sender.senderId) - this.consumer = null - this.onClose = null - } - } -} diff --git a/app/src/main/java/com/itsaky/androidide/services/log/MultiLogSenderHandler.kt b/app/src/main/java/com/itsaky/androidide/services/log/MultiLogSenderHandler.kt deleted file mode 100644 index a4523f8e89..0000000000 --- a/app/src/main/java/com/itsaky/androidide/services/log/MultiLogSenderHandler.kt +++ /dev/null @@ -1,144 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.services.log - -import com.itsaky.androidide.logsender.socket.SenderInfoCommand -import com.itsaky.androidide.logsender.socket.SocketCommandParser -import com.itsaky.androidide.models.LogLine -import com.itsaky.androidide.tasks.cancelIfActive -import kotlinx.coroutines.CoroutineName -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.Job -import kotlinx.coroutines.launch -import kotlinx.coroutines.withContext -import org.slf4j.LoggerFactory -import java.lang.Thread.currentThread -import java.net.ServerSocket -import java.util.concurrent.ConcurrentHashMap -import java.util.concurrent.atomic.AtomicBoolean -import java.util.concurrent.atomic.AtomicInteger - -/** - * Handles clients that connect to the log receiver. - * - * @author Akash Yadav - */ -class MultiLogSenderHandler(consumer: ((LogLine) -> Unit)? = null) : AutoCloseable { - - private val clients = ConcurrentHashMap() - private val port = AtomicInteger(-1) - private var isAlive = AtomicBoolean(false) - - private var logHandlerScope = CoroutineScope( - Dispatchers.IO + CoroutineName("MultiLogSenderHandler")) - - internal var consumer: ((LogLine) -> Unit)? = consumer - set(value) { - field = value - clients.forEach { (_, client) -> client.consumer = value } - } - - companion object { - private val log = LoggerFactory.getLogger(MultiLogSenderHandler::class.java) - } - - fun getPort(): Int { - return port.get() - } - - private suspend fun startAsync() = withContext(Dispatchers.IO) { - val job = coroutineContext[Job] - val server = try { - ServerSocket(0) - } catch (err: Exception) { - log.error("Failed to start log receiver socket", err) - return@withContext - } - - try { - port.set(server.localPort) - log.info("Starting log receiver server socket at port {}", getPort()) - - while (job?.isCancelled != true && isAlive.get()) { - val clientSocket = server.accept() - - val senderInfoLine = clientSocket.getInputStream().bufferedReader().readLine() - val command = SocketCommandParser.parse(senderInfoLine) - if (command == null || command !is SenderInfoCommand) { - log.error( - "Cannot accept log sender client. A sender must send the /sender command first.") - clientSocket.use {} - continue - } - - val handler = LogSenderHandler(command, clientSocket, consumer, ::removeClient) - - log.info("A log sender has been connected") - - clients[command.senderId] = handler - - handler.startAsync() - } - } catch (interrupt: InterruptedException) { - log.warn("MultiLogSenderHandler thread has been interrupted") - currentThread().interrupt() - } catch (err: Throwable) { - log.error("An error occurred while accept log client connections", err) - } finally { - this@MultiLogSenderHandler.close() - server.close() - } - } - - internal fun removeClient(senderId: String) { - clients.remove(senderId)?.closeAndLogError() - } - - private fun removeAllClients() { - this.clients.forEach { (_, handler) -> - handler.closeAndLogError() - } - - this.clients.clear() - } - - fun start() { - isAlive.set(true) - logHandlerScope.launch { - startAsync() - } - } - - fun isAlive() = isAlive.get() - - override fun close() { - this.isAlive.set(false) - this.removeAllClients() - this.consumer = null - this.logHandlerScope.cancelIfActive() - } - - private fun LogSenderHandler.closeAndLogError() { - try { - close() - } catch (e: Exception) { - log.warn("Failed to close", e) - } - } -} diff --git a/app/src/main/java/com/itsaky/androidide/services/log/utils.kt b/app/src/main/java/com/itsaky/androidide/services/log/utils.kt deleted file mode 100644 index 29f67aba18..0000000000 --- a/app/src/main/java/com/itsaky/androidide/services/log/utils.kt +++ /dev/null @@ -1,30 +0,0 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.services.log - -import android.os.RemoteException -import com.itsaky.androidide.logsender.ILogSender - -fun ILogSender.isAlive() : Boolean { - return try { - ping() - true - } catch (err: RemoteException) { - false - } -} \ No newline at end of file diff --git a/app/src/main/java/com/itsaky/androidide/shortcuts/ShortcutCategory.kt b/app/src/main/java/com/itsaky/androidide/shortcuts/ShortcutCategory.kt deleted file mode 100644 index 6a22bad2f7..0000000000 --- a/app/src/main/java/com/itsaky/androidide/shortcuts/ShortcutCategory.kt +++ /dev/null @@ -1,8 +0,0 @@ -package com.itsaky.androidide.shortcuts - -enum class ShortcutCategory { - FILE_MANAGEMENT, - SEARCH_AND_REPLACE, - PROJECTS_AND_SOLUTIONS, - WINDOWS_AND_DISPLAY, -} diff --git a/app/src/main/java/com/itsaky/androidide/shortcuts/ShortcutContext.kt b/app/src/main/java/com/itsaky/androidide/shortcuts/ShortcutContext.kt deleted file mode 100644 index d0df89914c..0000000000 --- a/app/src/main/java/com/itsaky/androidide/shortcuts/ShortcutContext.kt +++ /dev/null @@ -1,8 +0,0 @@ -package com.itsaky.androidide.shortcuts - -enum class ShortcutContext { - APP_GLOBAL, - MAIN, - EDITOR, - MODAL, -} diff --git a/app/src/main/java/com/itsaky/androidide/shortcuts/ShortcutGroupProvider.kt b/app/src/main/java/com/itsaky/androidide/shortcuts/ShortcutGroupProvider.kt deleted file mode 100644 index c66cdc5af1..0000000000 --- a/app/src/main/java/com/itsaky/androidide/shortcuts/ShortcutGroupProvider.kt +++ /dev/null @@ -1,19 +0,0 @@ -package com.itsaky.androidide.shortcuts - -import com.itsaky.androidide.shortcuts.groups.FileManagementGroup -import com.itsaky.androidide.shortcuts.groups.ProjectsAndSolutionsGroup -import com.itsaky.androidide.shortcuts.groups.SearchAndReplaceGroup -import com.itsaky.androidide.shortcuts.groups.ShortcutGroup -import com.itsaky.androidide.shortcuts.groups.WindowsAndDisplayGroup - -/** - * Provides the set of available shortcut groups for the IDE. - */ -class ShortcutGroupProvider { - fun all(): List = listOf( - ProjectsAndSolutionsGroup(), - WindowsAndDisplayGroup(), - FileManagementGroup(), - SearchAndReplaceGroup(), - ) -} diff --git a/app/src/main/java/com/itsaky/androidide/shortcuts/ShortcutManager.kt b/app/src/main/java/com/itsaky/androidide/shortcuts/ShortcutManager.kt deleted file mode 100644 index 7bef063b81..0000000000 --- a/app/src/main/java/com/itsaky/androidide/shortcuts/ShortcutManager.kt +++ /dev/null @@ -1,69 +0,0 @@ -package com.itsaky.androidide.shortcuts - -import android.content.Context -import android.view.KeyEvent -import android.view.View -import android.widget.EditText - -class ShortcutManager( - context: Context, -) { - - private val catalog: List = ShortcutCatalog().all(context) - - private val contextPriority = listOf( - ShortcutContext.MODAL, - ShortcutContext.EDITOR, - ShortcutContext.MAIN, - ShortcutContext.APP_GLOBAL, - ) - - fun dispatch( - event: KeyEvent, - context: ShortcutContext, - focusView: View?, - executionContext: ShortcutExecutionContext, - hasModal: Boolean = false, - ): Boolean { - if (!shouldHandleShortcuts(event, focusView)) return false - - val activeContexts = if (hasModal) { - setOf(ShortcutContext.APP_GLOBAL, ShortcutContext.MODAL) - } else { - setOf(ShortcutContext.APP_GLOBAL, context) - } - - val definition = findMatchingShortcut(event, activeContexts) ?: return false - return executionContext.ideShortcutActions.execute(definition.actionId) - } - - private fun shouldHandleShortcuts( - event: KeyEvent, - focusView: View?, - ): Boolean { - if (event.keyCode == KeyEvent.KEYCODE_ESCAPE) return true - return focusView !is EditText - } - - private fun findMatchingShortcut( - event: KeyEvent, - activeContexts: Set, - ): ShortcutDefinition? { - val matchingDefinitions = catalog.filter { definition -> - definition.contexts.any(activeContexts::contains) && - definition.bindings.any { it.matches(event) } - } - - return matchingDefinitions.maxByOrNull { definition -> - definition.contexts - .filter { it in activeContexts } - .maxOfOrNull(::priorityScore) - ?: Int.MIN_VALUE - } - } - - private fun priorityScore(context: ShortcutContext): Int { - val index = contextPriority.indexOf(context) - return if (index == -1) Int.MIN_VALUE else contextPriority.size - index - } -} diff --git a/app/src/main/java/com/itsaky/androidide/shortcuts/groups/FileManagementGroup.kt b/app/src/main/java/com/itsaky/androidide/shortcuts/groups/FileManagementGroup.kt deleted file mode 100644 index c88ef80c1d..0000000000 --- a/app/src/main/java/com/itsaky/androidide/shortcuts/groups/FileManagementGroup.kt +++ /dev/null @@ -1,43 +0,0 @@ -package com.itsaky.androidide.shortcuts.groups - -import android.content.Context -import android.view.KeyEvent -import com.itsaky.androidide.actions.file.CloseFileAction -import com.itsaky.androidide.actions.file.SaveFileAction -import com.itsaky.androidide.resources.R -import com.itsaky.androidide.shortcuts.KeyShortcut -import com.itsaky.androidide.shortcuts.ShortcutCategory -import com.itsaky.androidide.shortcuts.ShortcutContext -import com.itsaky.androidide.shortcuts.ShortcutDefinition - -internal class FileManagementGroup : ShortcutGroup { - override fun shortcuts(context: Context): List { - return listOf( - ShortcutDefinition( - id = ShortcutDefinitionIds.SAVE_ALL_FILES, - title = context.getString(R.string.save), - bindings = listOf( - KeyShortcut.ctrl(KeyEvent.KEYCODE_S), - ), - category = ShortcutCategory.FILE_MANAGEMENT, - contexts = setOf( - ShortcutContext.EDITOR, - ), - actionId = SaveFileAction.ID, - ), - ShortcutDefinition( - id = ShortcutDefinitionIds.CLOSE_CURRENT_FILE, - title = context.getString(R.string.shortcut_close_current_file), - bindings = listOf( - KeyShortcut.ctrl(KeyEvent.KEYCODE_W), - KeyShortcut.ctrl(KeyEvent.KEYCODE_F4), - ), - category = ShortcutCategory.FILE_MANAGEMENT, - contexts = setOf( - ShortcutContext.EDITOR, - ), - actionId = CloseFileAction.ID, - ), - ) - } -} diff --git a/app/src/main/java/com/itsaky/androidide/shortcuts/groups/ProjectsAndSolutionsGroup.kt b/app/src/main/java/com/itsaky/androidide/shortcuts/groups/ProjectsAndSolutionsGroup.kt deleted file mode 100644 index 7ab45d11e0..0000000000 --- a/app/src/main/java/com/itsaky/androidide/shortcuts/groups/ProjectsAndSolutionsGroup.kt +++ /dev/null @@ -1,55 +0,0 @@ -package com.itsaky.androidide.shortcuts.groups - -import android.content.Context -import android.view.KeyEvent -import com.itsaky.androidide.actions.main.CloneRepositoryAction -import com.itsaky.androidide.actions.main.CreateProjectAction -import com.itsaky.androidide.actions.main.OpenProjectAction -import com.itsaky.androidide.resources.R -import com.itsaky.androidide.shortcuts.KeyShortcut -import com.itsaky.androidide.shortcuts.ShortcutCategory -import com.itsaky.androidide.shortcuts.ShortcutContext -import com.itsaky.androidide.shortcuts.ShortcutDefinition - -internal class ProjectsAndSolutionsGroup : ShortcutGroup { - override fun shortcuts(context: Context): List { - return listOf( - ShortcutDefinition( - id = ShortcutDefinitionIds.CREATE_PROJECT, - title = context.getString(R.string.shortcut_create_project), - bindings = listOf( - KeyShortcut.ctrl(KeyEvent.KEYCODE_N), - ), - category = ShortcutCategory.PROJECTS_AND_SOLUTIONS, - contexts = setOf( - ShortcutContext.MAIN, - ), - actionId = CreateProjectAction.ID, - ), - ShortcutDefinition( - id = ShortcutDefinitionIds.OPEN_PROJECT, - title = context.getString(R.string.shortcut_open_project), - bindings = listOf( - KeyShortcut.ctrl(KeyEvent.KEYCODE_O), - ), - category = ShortcutCategory.PROJECTS_AND_SOLUTIONS, - contexts = setOf( - ShortcutContext.MAIN, - ), - actionId = OpenProjectAction.ID, - ), - ShortcutDefinition( - id = ShortcutDefinitionIds.CLONE_REPOSITORY, - title = context.getString(R.string.shortcut_clone_repository), - bindings = listOf( - KeyShortcut.ctrlShift(KeyEvent.KEYCODE_O), - ), - category = ShortcutCategory.PROJECTS_AND_SOLUTIONS, - contexts = setOf( - ShortcutContext.MAIN, - ), - actionId = CloneRepositoryAction.ID, - ), - ) - } -} diff --git a/app/src/main/java/com/itsaky/androidide/shortcuts/groups/SearchAndReplaceGroup.kt b/app/src/main/java/com/itsaky/androidide/shortcuts/groups/SearchAndReplaceGroup.kt deleted file mode 100644 index bd533c9ea6..0000000000 --- a/app/src/main/java/com/itsaky/androidide/shortcuts/groups/SearchAndReplaceGroup.kt +++ /dev/null @@ -1,60 +0,0 @@ -package com.itsaky.androidide.shortcuts.groups - -import android.content.Context -import android.view.KeyEvent -import com.itsaky.androidide.actions.etc.FindInFileAction -import com.itsaky.androidide.actions.etc.FindInProjectAction -import com.itsaky.androidide.actions.etc.ReplaceInProjectAction -import com.itsaky.androidide.resources.R -import com.itsaky.androidide.shortcuts.KeyShortcut -import com.itsaky.androidide.shortcuts.ShortcutCategory -import com.itsaky.androidide.shortcuts.ShortcutContext -import com.itsaky.androidide.shortcuts.ShortcutDefinition - -internal class SearchAndReplaceGroup : ShortcutGroup { - override fun shortcuts(context: Context): List = - listOf( - ShortcutDefinition( - id = ShortcutDefinitionIds.FIND_IN_PROJECT, - title = context.getString(R.string.menu_find_project), - bindings = - listOf( - KeyShortcut.ctrlShift(KeyEvent.KEYCODE_F), - ), - category = ShortcutCategory.SEARCH_AND_REPLACE, - contexts = - setOf( - ShortcutContext.EDITOR, - ), - actionId = FindInProjectAction.ID, - ), - ShortcutDefinition( - id = ShortcutDefinitionIds.FIND_IN_FILE, - title = context.getString(R.string.menu_find_file), - bindings = - listOf( - KeyShortcut.ctrl(KeyEvent.KEYCODE_F), - ), - category = ShortcutCategory.SEARCH_AND_REPLACE, - contexts = - setOf( - ShortcutContext.EDITOR, - ), - actionId = FindInFileAction.ID, - ), - ShortcutDefinition( - id = ShortcutDefinitionIds.REPLACE_IN_PROJECT, - title = context.getString(R.string.menu_replace_project), - bindings = - listOf( - KeyShortcut.ctrlShift(KeyEvent.KEYCODE_R), - ), - category = ShortcutCategory.SEARCH_AND_REPLACE, - contexts = - setOf( - ShortcutContext.EDITOR, - ), - actionId = ReplaceInProjectAction.ID, - ), - ) -} diff --git a/app/src/main/java/com/itsaky/androidide/shortcuts/groups/ShortcutGroup.kt b/app/src/main/java/com/itsaky/androidide/shortcuts/groups/ShortcutGroup.kt deleted file mode 100644 index f3b2800e3b..0000000000 --- a/app/src/main/java/com/itsaky/androidide/shortcuts/groups/ShortcutGroup.kt +++ /dev/null @@ -1,8 +0,0 @@ -package com.itsaky.androidide.shortcuts.groups - -import android.content.Context -import com.itsaky.androidide.shortcuts.ShortcutDefinition - -interface ShortcutGroup { - fun shortcuts(context: Context): List -} diff --git a/app/src/main/java/com/itsaky/androidide/shortcuts/groups/WindowsAndDisplayGroup.kt b/app/src/main/java/com/itsaky/androidide/shortcuts/groups/WindowsAndDisplayGroup.kt deleted file mode 100644 index 496d48eb32..0000000000 --- a/app/src/main/java/com/itsaky/androidide/shortcuts/groups/WindowsAndDisplayGroup.kt +++ /dev/null @@ -1,68 +0,0 @@ -package com.itsaky.androidide.shortcuts.groups - -import android.content.Context -import android.view.KeyEvent -import com.itsaky.androidide.actions.main.OpenTerminalAction -import com.itsaky.androidide.actions.main.PreferencesAction -import com.itsaky.androidide.actions.sidebar.PreferencesSidebarAction -import com.itsaky.androidide.actions.sidebar.TerminalSidebarAction -import com.itsaky.androidide.resources.R -import com.itsaky.androidide.shortcuts.KeyShortcut -import com.itsaky.androidide.shortcuts.ShortcutCategory -import com.itsaky.androidide.shortcuts.ShortcutContext -import com.itsaky.androidide.shortcuts.ShortcutDefinition - -internal class WindowsAndDisplayGroup : ShortcutGroup { - override fun shortcuts(context: Context): List { - return listOf( - ShortcutDefinition( - id = ShortcutDefinitionIds.OPEN_TERMINAL, - title = context.getString(R.string.shortcut_open_terminal), - bindings = listOf( - KeyShortcut.ctrlAlt(KeyEvent.KEYCODE_T), - ), - category = ShortcutCategory.WINDOWS_AND_DISPLAY, - contexts = setOf( - ShortcutContext.EDITOR, - ), - actionId = TerminalSidebarAction.ID, - ), - ShortcutDefinition( - id = ShortcutDefinitionIds.OPEN_TERMINAL_MAIN, - title = context.getString(R.string.shortcut_open_terminal), - bindings = listOf( - KeyShortcut.ctrlAlt(KeyEvent.KEYCODE_T), - ), - category = ShortcutCategory.WINDOWS_AND_DISPLAY, - contexts = setOf( - ShortcutContext.MAIN, - ), - actionId = OpenTerminalAction.ID, - ), - ShortcutDefinition( - id = ShortcutDefinitionIds.OPEN_PREFERENCES, - title = context.getString(R.string.shortcut_open_preferences), - bindings = listOf( - KeyShortcut.ctrl(KeyEvent.KEYCODE_COMMA), - ), - category = ShortcutCategory.WINDOWS_AND_DISPLAY, - contexts = setOf( - ShortcutContext.EDITOR, - ), - actionId = PreferencesSidebarAction.ID, - ), - ShortcutDefinition( - id = ShortcutDefinitionIds.OPEN_PREFERENCES_MAIN, - title = context.getString(R.string.shortcut_open_preferences), - bindings = listOf( - KeyShortcut.ctrl(KeyEvent.KEYCODE_COMMA), - ), - category = ShortcutCategory.WINDOWS_AND_DISPLAY, - contexts = setOf( - ShortcutContext.MAIN, - ), - actionId = PreferencesAction.ID, - ), - ) - } -} diff --git a/app/src/main/java/com/itsaky/androidide/tasks/callables/FileTreeCallable.java b/app/src/main/java/com/itsaky/androidide/tasks/callables/FileTreeCallable.java deleted file mode 100755 index afe8454fd9..0000000000 --- a/app/src/main/java/com/itsaky/androidide/tasks/callables/FileTreeCallable.java +++ /dev/null @@ -1,97 +0,0 @@ -/************************************************************************************ - * This file is part of AndroidIDE. - * - * - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - * - **************************************************************************************/ - -package com.itsaky.androidide.tasks.callables; - -import android.content.Context; - -import com.itsaky.androidide.adapters.viewholders.FileTreeViewHolder; -import com.unnamed.b.atv.model.TreeNode; - -import java.io.File; -import java.io.FileFilter; -import java.util.Arrays; -import java.util.Comparator; -import java.util.concurrent.Callable; - -public class FileTreeCallable implements Callable { - private final Context ctx; - private final TreeNode parent; - private final File file; - private final FileTreeViewHolder.ExternalDropHandler externalDropHandler; - - public FileTreeCallable(Context ctx, TreeNode parent, File file) { - this(ctx, parent, file, null); - } - - public FileTreeCallable( - Context ctx, TreeNode parent, File file, FileTreeViewHolder.ExternalDropHandler externalDropHandler) { - this.ctx = ctx; - this.parent = parent; - this.file = file; - this.externalDropHandler = externalDropHandler; - } - - @Override - public Boolean call() throws Exception { - populateChildren(file.listFiles(/*new HiddenFilesFilter()*/), parent); - return true; - } - - private void populateChildren(File[] files, TreeNode parent) { - if (files == null) return; - - Arrays.sort(files, new SortFileName()); - Arrays.sort(files, new SortFolder()); - for (File file : files) { - parent.addChild(createNode(file), false); - } - } - - private TreeNode createNode(File file) { - TreeNode node = new TreeNode(file); - node.setViewHolder(new FileTreeViewHolder(ctx, externalDropHandler)); - return node; - } - - public static class HiddenFilesFilter implements FileFilter { - - @Override - public boolean accept(File p1) { - return !p1.getName().startsWith("."); - } - } - - public static class SortFileName implements Comparator { - @Override - public int compare(File f1, File f2) { - return f1.getName().compareTo(f2.getName()); - } - } - - public static class SortFolder implements Comparator { - @Override - public int compare(File f1, File f2) { - if (f1.isDirectory() == f2.isDirectory()) return 0; - else if (f1.isDirectory() && !f2.isDirectory()) return -1; - else return 1; - } - } -} diff --git a/app/src/main/java/com/itsaky/androidide/ui/CustomDividerItemDecoration.kt b/app/src/main/java/com/itsaky/androidide/ui/CustomDividerItemDecoration.kt deleted file mode 100644 index e8a08420f0..0000000000 --- a/app/src/main/java/com/itsaky/androidide/ui/CustomDividerItemDecoration.kt +++ /dev/null @@ -1,45 +0,0 @@ -package com.itsaky.androidide.ui - -import android.content.Context -import android.graphics.Canvas -import android.graphics.Rect -import android.graphics.drawable.Drawable -import android.view.View -import androidx.core.content.ContextCompat -import androidx.recyclerview.widget.RecyclerView - -class CustomDividerItemDecoration(context: Context, private val drawableResId: Int) : - RecyclerView.ItemDecoration() { - private val divider: Drawable? = ContextCompat.getDrawable(context, drawableResId) - - override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) { - divider ?: return - - val left = parent.paddingLeft - val right = parent.width - parent.paddingRight - - // Loop until the second to last child - val childCount = parent.childCount - for (i in 0 until childCount - 1) { - val child = parent.getChildAt(i) - val params = child.layoutParams as RecyclerView.LayoutParams - val top = child.bottom + params.bottomMargin - val bottom = top + divider.intrinsicHeight - divider.setBounds(left, top, right, bottom) - divider.draw(c) - } - } - - override fun getItemOffsets( - outRect: Rect, view: View, - parent: RecyclerView, state: RecyclerView.State - ) { - val position = parent.getChildAdapterPosition(view) - // Only add bottom offset if this is not the last item - if (position < state.itemCount - 1) { - outRect.bottom = divider?.intrinsicHeight ?: 0 - } else { - outRect.bottom = 0 - } - } -} diff --git a/app/src/main/java/com/itsaky/androidide/ui/CustomSnackbar.kt b/app/src/main/java/com/itsaky/androidide/ui/CustomSnackbar.kt deleted file mode 100644 index d59c3bb1c5..0000000000 --- a/app/src/main/java/com/itsaky/androidide/ui/CustomSnackbar.kt +++ /dev/null @@ -1,76 +0,0 @@ -package com.itsaky.androidide.ui - -import android.annotation.SuppressLint -import android.content.Context -import android.view.LayoutInflater -import android.view.View -import android.widget.Button -import android.widget.TextView -import com.google.android.material.snackbar.Snackbar -import com.itsaky.androidide.R - -class CustomSnackbar(private val context: Context, private val rootView: View) { - - private var snackbar: Snackbar? = null - - @SuppressLint("RestrictedApi") - fun show( - message: String, - textFirstAction: String?, - textSecondaryAction: String?, - actionFirst: (() -> Unit)? = null, - actionSecondary: (() -> Unit)? = null - ) { - snackbar = Snackbar.make(rootView, "", Snackbar.LENGTH_INDEFINITE) - - val snackbarView = snackbar?.view - val inflater = LayoutInflater.from(context) - - val customView = inflater.inflate(R.layout.snackbar_custom, null) - - val textView = customView.findViewById(R.id.snackbar_message) - textView.text = message - - val btnFirstAction = customView.findViewById