diff --git a/.agents/skills/magisk-app/SKILL.md b/.agents/skills/magisk-app/SKILL.md index 231d41862..4bedcb742 100644 --- a/.agents/skills/magisk-app/SKILL.md +++ b/.agents/skills/magisk-app/SKILL.md @@ -1,6 +1,6 @@ --- name: magisk-app -description: Guidelines, architecture, development conventions, and build workflows for the Magisk Android application (app/ subproject). Use when working on, modifying, building, or testing code in app/ or any of its submodules (:core, :apk-ng, :shared, :stub, :stub-res, :test, :build-logic, :apk). +description: Guidelines, architecture, development conventions, and build workflows for the Magisk Android application (app/ subproject). Use when working on, modifying, building, or testing code in app/ or any of its submodules (:core, :apk, :shared, :stub, :stub-res, :test, :build-logic, :apk-legacy). --- # Magisk App Subproject Guidelines @@ -11,24 +11,24 @@ Guidelines and workflows for developing and building the Android application in - **General Guidelines:** Always follow the top-level [`AGENTS.md`](../../../AGENTS.md) and [`magisk-git`](../magisk-git/SKILL.md) for repository rules, environment execution setup, and commit control policies. - **Working Directory:** Set working directory to `app/` when running standalone Gradle commands, or execute build commands via `./build.py` from the repository root. -- **Environment Wrapper:** Standalone `./gradlew` commands MUST be prefixed with `../scripts/env.py` (e.g., `../scripts/env.py ./gradlew :apk-ng:assembleDebug`). Alternatively, run `./build.py app-ng` from the repository root (which configures the environment automatically and builds `:apk-ng`). +- **Environment Wrapper:** Standalone `./gradlew` commands MUST be prefixed with `../scripts/env.py` (e.g., `../scripts/env.py ./gradlew :apk:assembleDebug`). Alternatively, run `./build.py app` from the repository root (which configures the environment automatically and builds `:apk`). ## 2. Architecture & Submodules Multi-module Gradle project structure: -- **`:apk-ng`** (`apk-ng/`): Next-gen app variant. Primary target for UI and application features. +- **`:apk`** (`apk/`): Main Magisk app (modern Jetpack Compose UI). Primary target for UI and application features. - **`:core`** (`core/`): Core domain logic, resources, Room DB, services. Primary target for core feature development. - **`:shared`** (`shared/`): Shared utilities and common data structures. - **`:stub`** (`stub/`): Lightweight stub app loader for hidden installs. - **`:stub-res`** (`stub-res/`): Stub-specific Android resources. - **`:test`** (`test/`): Application testing target. - **`:build-logic`** (`build-logic/`): Custom Gradle plugins and build logic. -- **`:apk`** (`apk/`): Legacy app APK. **Maintenance mode:** Do NOT modify unless explicitly requested. +- **`:apk-legacy`** (`apk-legacy/`): Legacy app APK (View-based UI). **Maintenance mode:** Do NOT modify unless explicitly requested. ## 3. Development Guidelines -- **Target Modules:** All active app development occurs in `:core` and `:apk-ng`. Do NOT make changes to `:apk` unless explicitly requested. -- **Legacy Compatibility:** When modifying `:core` and `:shared`, make sure the `:apk` module is still buildable. +- **Target Modules:** All active app development occurs in `:core` and `:apk`. Do NOT make changes to `:apk-legacy` unless explicitly requested. +- **Legacy Compatibility:** When modifying `:core` and `:shared`, make sure the `:apk-legacy` module is still buildable. - **Language & UI:** Written in Kotlin/Java. **Prefer Kotlin for all new code.** Uses Jetpack Compose for UI (prefer over View XML). - **String Resources:** Default strings in `core/src/main/res/values/strings.xml` and `stub-res/src/main/res/values/strings.xml`. Translations go in `values-[lang]/strings.xml`. - **Data Stack:** Room, KSP, Wire (Protocol Buffers), Moshi. @@ -36,15 +36,15 @@ Multi-module Gradle project structure: ## 4. Workflows & Verification ### From `app/` directory (prefixed with `../scripts/env.py`): -- **Build App (`:apk-ng` Debug):** `../scripts/env.py ./gradlew :apk-ng:assembleDebug` +- **Build App (`:apk` Debug):** `../scripts/env.py ./gradlew :apk:assembleDebug` - **Build Stub APK:** `../scripts/env.py ./gradlew :stub:assembleDebug` -- **Build Legacy APK (`:apk` Debug):** `../scripts/env.py ./gradlew :apk:assembleDebug` -- **Run Lint:** `../scripts/env.py ./gradlew lint` (or `../scripts/env.py ./gradlew :apk-ng:lintDebug`) +- **Build Legacy APK (`:apk-legacy` Debug):** `../scripts/env.py ./gradlew :apk-legacy:assembleDebug` +- **Run Lint:** `../scripts/env.py ./gradlew lint` (or `../scripts/env.py ./gradlew :apk:lintDebug`) - **Run Unit Tests:** `../scripts/env.py ./gradlew test` - **Clean Artifacts:** `../scripts/env.py ./gradlew clean` ### From repository root (via `build.py`): -- **Build App (`:apk-ng`):** `./build.py app-ng` +- **Build App (`:apk`):** `./build.py app` - **Build Stub App:** `./build.py stub` -- **Build Legacy App (`:apk`):** `./build.py app` +- **Build Legacy App (`:apk-legacy`):** `./build.py app-legacy` - **Run App Tests:** `./build.py test` diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 7fd97b56a..6e641ad41 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -103,7 +103,7 @@ jobs: - name: Run AVD test timeout-minutes: 18 - run: scripts/avd.sh test -l -v ${{ matrix.version }} -t "${{ matrix.type }}" out/apk-ng-*.apk + run: scripts/avd.sh test -l -v ${{ matrix.version }} -t "${{ matrix.type }}" - name: Upload logs on error if: ${{ failure() }} @@ -139,7 +139,7 @@ jobs: - name: Run AVD test timeout-minutes: 18 - run: scripts/avd.sh test -l -a x86 -v ${{ matrix.version }} out/apk-ng-*.apk + run: scripts/avd.sh test -l -a x86 -v ${{ matrix.version }} - name: Upload logs on error if: ${{ failure() }} diff --git a/app/apk-legacy/build.gradle.kts b/app/apk-legacy/build.gradle.kts new file mode 100644 index 000000000..61ebc64d2 --- /dev/null +++ b/app/apk-legacy/build.gradle.kts @@ -0,0 +1,62 @@ +plugins { + alias(libs.plugins.android.application) + kotlin("plugin.parcelize") + alias(libs.plugins.legacy.kapt) + alias(libs.plugins.navigation.safeargs) +} + +setupMainApk() + +kapt { + correctErrorTypes = true + useBuildCache = true + mapDiagnosticLocations = true + javacOptions { + option("-Xmaxerrs", "1000") + } +} + +android { + buildFeatures { + dataBinding = true + } + + compileOptions { + isCoreLibraryDesugaringEnabled = true + } + + defaultConfig { + proguardFile("proguard-rules.pro") + } + + buildTypes { + release { + isMinifyEnabled = true + isShrinkResources = true + } + } +} + +dependencies { + implementation(project(":core")) + coreLibraryDesugaring(libs.jdk.libs) + + implementation(libs.indeterminate.checkbox) + implementation(libs.rikka.layoutinflater) + implementation(libs.rikka.insets) + implementation(libs.rikka.recyclerview) + + implementation(libs.navigation.fragment.ktx) + implementation(libs.navigation.ui.ktx) + + implementation(libs.constraintlayout) + implementation(libs.swiperefreshlayout) + implementation(libs.recyclerview) + implementation(libs.transition) + implementation(libs.fragment.ktx) + implementation(libs.appcompat) + implementation(libs.material) + + // Make sure kapt runs with a proper kotlin-stdlib + kapt(kotlin("stdlib")) +} diff --git a/app/apk-ng/proguard-rules.pro b/app/apk-legacy/proguard-rules.pro similarity index 100% rename from app/apk-ng/proguard-rules.pro rename to app/apk-legacy/proguard-rules.pro diff --git a/app/apk-ng/src/main/AndroidManifest.xml b/app/apk-legacy/src/main/AndroidManifest.xml similarity index 81% rename from app/apk-ng/src/main/AndroidManifest.xml rename to app/apk-legacy/src/main/AndroidManifest.xml index a55c4e523..63f0dcba6 100644 --- a/app/apk-ng/src/main/AndroidManifest.xml +++ b/app/apk-legacy/src/main/AndroidManifest.xml @@ -2,6 +2,15 @@ + + () + val viewEvents: LiveData get() = _viewEvents + + open fun onSaveState(state: Bundle) {} + open fun onRestoreState(state: Bundle) {} + open fun onNetworkChanged(network: Boolean) {} + + fun withPermission(permission: String, callback: (Boolean) -> Unit) { + PermissionEvent(permission, callback).publish() + } + + inline fun withExternalRW(crossinline callback: () -> Unit) { + withPermission(WRITE_EXTERNAL_STORAGE) { + if (!it) { + SnackbarEvent(R.string.external_rw_permission_denied).publish() + } else { + callback() + } + } + } + + @SuppressLint("InlinedApi") + inline fun withInstallPermission(crossinline callback: () -> Unit) { + withPermission(REQUEST_INSTALL_PACKAGES) { + if (!it) { + SnackbarEvent(R.string.install_unknown_denied).publish() + } else { + callback() + } + } + } + + @SuppressLint("InlinedApi") + inline fun withPostNotificationPermission(crossinline callback: () -> Unit) { + withPermission(POST_NOTIFICATIONS) { + if (!it) { + SnackbarEvent(R.string.post_notifications_denied).publish() + } else { + callback() + } + } + } + + fun back() = BackPressEvent().publish() + + fun ViewEvent.publish() { + _viewEvents.postValue(this) + } + + fun DialogBuilder.show() { + DialogEvent(this).publish() + } + + fun NavDirections.navigate(pop: Boolean = false) { + _viewEvents.postValue(NavigationEvent(this, pop)) + } + +} diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/arch/NavigationActivity.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/arch/NavigationActivity.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/arch/NavigationActivity.kt rename to app/apk-legacy/src/main/java/com/topjohnwu/magisk/arch/NavigationActivity.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/arch/UIActivity.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/arch/UIActivity.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/arch/UIActivity.kt rename to app/apk-legacy/src/main/java/com/topjohnwu/magisk/arch/UIActivity.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/arch/ViewEvent.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/arch/ViewEvent.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/arch/ViewEvent.kt rename to app/apk-legacy/src/main/java/com/topjohnwu/magisk/arch/ViewEvent.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/arch/ViewModelHolder.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/arch/ViewModelHolder.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/arch/ViewModelHolder.kt rename to app/apk-legacy/src/main/java/com/topjohnwu/magisk/arch/ViewModelHolder.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/databinding/DataBindingAdapters.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/databinding/DataBindingAdapters.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/databinding/DataBindingAdapters.kt rename to app/apk-legacy/src/main/java/com/topjohnwu/magisk/databinding/DataBindingAdapters.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/databinding/DiffObservableList.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/databinding/DiffObservableList.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/databinding/DiffObservableList.kt rename to app/apk-legacy/src/main/java/com/topjohnwu/magisk/databinding/DiffObservableList.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/databinding/MergeObservableList.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/databinding/MergeObservableList.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/databinding/MergeObservableList.kt rename to app/apk-legacy/src/main/java/com/topjohnwu/magisk/databinding/MergeObservableList.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/databinding/ObservableHost.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/databinding/ObservableHost.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/databinding/ObservableHost.kt rename to app/apk-legacy/src/main/java/com/topjohnwu/magisk/databinding/ObservableHost.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/databinding/RecyclerViewItems.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/databinding/RecyclerViewItems.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/databinding/RecyclerViewItems.kt rename to app/apk-legacy/src/main/java/com/topjohnwu/magisk/databinding/RecyclerViewItems.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/databinding/RvItemAdapter.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/databinding/RvItemAdapter.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/databinding/RvItemAdapter.kt rename to app/apk-legacy/src/main/java/com/topjohnwu/magisk/databinding/RvItemAdapter.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/dialog/DarkThemeDialog.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/dialog/DarkThemeDialog.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/dialog/DarkThemeDialog.kt rename to app/apk-legacy/src/main/java/com/topjohnwu/magisk/dialog/DarkThemeDialog.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/dialog/DownloadDialog.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/dialog/DownloadDialog.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/dialog/DownloadDialog.kt rename to app/apk-legacy/src/main/java/com/topjohnwu/magisk/dialog/DownloadDialog.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/dialog/EnvFixDialog.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/dialog/EnvFixDialog.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/dialog/EnvFixDialog.kt rename to app/apk-legacy/src/main/java/com/topjohnwu/magisk/dialog/EnvFixDialog.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/dialog/LocalModuleInstallDialog.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/dialog/LocalModuleInstallDialog.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/dialog/LocalModuleInstallDialog.kt rename to app/apk-legacy/src/main/java/com/topjohnwu/magisk/dialog/LocalModuleInstallDialog.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/dialog/ManagerInstallDialog.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/dialog/ManagerInstallDialog.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/dialog/ManagerInstallDialog.kt rename to app/apk-legacy/src/main/java/com/topjohnwu/magisk/dialog/ManagerInstallDialog.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/dialog/MarkDownDialog.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/dialog/MarkDownDialog.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/dialog/MarkDownDialog.kt rename to app/apk-legacy/src/main/java/com/topjohnwu/magisk/dialog/MarkDownDialog.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/dialog/OnlineModuleInstallDialog.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/dialog/OnlineModuleInstallDialog.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/dialog/OnlineModuleInstallDialog.kt rename to app/apk-legacy/src/main/java/com/topjohnwu/magisk/dialog/OnlineModuleInstallDialog.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/dialog/SecondSlotWarningDialog.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/dialog/SecondSlotWarningDialog.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/dialog/SecondSlotWarningDialog.kt rename to app/apk-legacy/src/main/java/com/topjohnwu/magisk/dialog/SecondSlotWarningDialog.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/dialog/SuperuserRevokeDialog.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/dialog/SuperuserRevokeDialog.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/dialog/SuperuserRevokeDialog.kt rename to app/apk-legacy/src/main/java/com/topjohnwu/magisk/dialog/SuperuserRevokeDialog.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/dialog/UninstallDialog.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/dialog/UninstallDialog.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/dialog/UninstallDialog.kt rename to app/apk-legacy/src/main/java/com/topjohnwu/magisk/dialog/UninstallDialog.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/events/ViewEvents.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/events/ViewEvents.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/events/ViewEvents.kt rename to app/apk-legacy/src/main/java/com/topjohnwu/magisk/events/ViewEvents.kt diff --git a/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/MainActivity.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/MainActivity.kt new file mode 100644 index 000000000..a277224ca --- /dev/null +++ b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/MainActivity.kt @@ -0,0 +1,278 @@ +package com.topjohnwu.magisk.ui + +import android.Manifest +import android.Manifest.permission.REQUEST_INSTALL_PACKAGES +import android.annotation.SuppressLint +import android.content.Intent +import android.content.pm.ApplicationInfo +import android.os.Bundle +import android.view.MenuItem +import android.view.View +import android.view.WindowManager +import android.widget.Toast +import androidx.core.content.pm.ShortcutManagerCompat +import androidx.core.view.forEach +import androidx.core.view.isGone +import androidx.core.view.isVisible +import androidx.lifecycle.lifecycleScope +import androidx.navigation.NavDirections +import com.topjohnwu.magisk.MainDirections +import com.topjohnwu.magisk.R +import com.topjohnwu.magisk.arch.BaseViewModel +import com.topjohnwu.magisk.arch.NavigationActivity +import com.topjohnwu.magisk.arch.startAnimations +import com.topjohnwu.magisk.arch.viewModel +import com.topjohnwu.magisk.core.Config +import com.topjohnwu.magisk.core.Const +import com.topjohnwu.magisk.core.Info +import com.topjohnwu.magisk.core.base.SplashController +import com.topjohnwu.magisk.core.base.SplashScreenHost +import com.topjohnwu.magisk.core.isRunningAsStub +import com.topjohnwu.magisk.core.ktx.toast +import com.topjohnwu.magisk.core.model.module.LocalModule +import com.topjohnwu.magisk.core.tasks.AppMigration +import com.topjohnwu.magisk.databinding.ActivityMainMd2Binding +import com.topjohnwu.magisk.ui.home.HomeFragmentDirections +import com.topjohnwu.magisk.ui.theme.Theme +import com.topjohnwu.magisk.view.MagiskDialog +import com.topjohnwu.magisk.view.Shortcuts +import kotlinx.coroutines.launch +import java.io.File +import com.topjohnwu.magisk.core.R as CoreR + +class MainViewModel : BaseViewModel() + +class MainActivity : NavigationActivity(), SplashScreenHost { + + override val layoutRes = R.layout.activity_main_md2 + override val viewModel by viewModel() + override val navHostId: Int = R.id.main_nav_host + override val splashController = SplashController(this) + override val snackbarView: View + get() { + val fragmentOverride = currentFragment?.snackbarView + return fragmentOverride ?: super.snackbarView + } + override val snackbarAnchorView: View? + get() { + val fragmentAnchor = currentFragment?.snackbarAnchorView + return when { + fragmentAnchor?.isVisible == true -> fragmentAnchor + binding.mainNavigation.isVisible -> return binding.mainNavigation + else -> null + } + } + + private var isRootFragment = true + + override fun onCreate(savedInstanceState: Bundle?) { + setTheme(Theme.selected.themeRes) + splashController.preOnCreate() + super.onCreate(savedInstanceState) + splashController.onCreate(savedInstanceState) + } + + override fun onResume() { + super.onResume() + splashController.onResume() + } + + @SuppressLint("InlinedApi") + override fun onCreateUi(savedInstanceState: Bundle?) { + setContentView() + showUnsupportedMessage() + askForHomeShortcut() + + // Ask permission to post notifications for background update check + if (Config.checkUpdate) { + withPermission(Manifest.permission.POST_NOTIFICATIONS) { + Config.checkUpdate = it + } + } + + window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE) + + navigation.addOnDestinationChangedListener { _, destination, _ -> + isRootFragment = when (destination.id) { + R.id.homeFragment, + R.id.modulesFragment, + R.id.superuserFragment, + R.id.logFragment -> true + else -> false + } + + setDisplayHomeAsUpEnabled(!isRootFragment) + requestNavigationHidden(!isRootFragment) + + binding.mainNavigation.menu.forEach { + if (it.itemId == destination.id) { + it.isChecked = true + } + } + } + + setSupportActionBar(binding.mainToolbar) + + binding.mainNavigation.setOnItemSelectedListener { + getScreen(it.itemId)?.navigate() + true + } + binding.mainNavigation.setOnItemReselectedListener { + // https://issuetracker.google.com/issues/124538620 + } + binding.mainNavigation.menu.apply { + findItem(R.id.superuserFragment)?.isEnabled = Info.showSuperUser + findItem(R.id.modulesFragment)?.isEnabled = Info.env.isActive && LocalModule.loaded() + } + + val section = + if (intent.action == Intent.ACTION_APPLICATION_PREFERENCES) + Const.Nav.SETTINGS + else + intent.getStringExtra(Const.Key.OPEN_SECTION) + + getScreen(section)?.navigate() + + if (!isRootFragment) { + requestNavigationHidden(requiresAnimation = savedInstanceState == null) + } + } + + override fun onOptionsItemSelected(item: MenuItem): Boolean { + when (item.itemId) { + android.R.id.home -> onBackPressed() + else -> return super.onOptionsItemSelected(item) + } + return true + } + + fun setDisplayHomeAsUpEnabled(isEnabled: Boolean) { + binding.mainToolbar.startAnimations() + when { + isEnabled -> binding.mainToolbar.setNavigationIcon(R.drawable.ic_back_md2) + else -> binding.mainToolbar.navigationIcon = null + } + } + + internal fun requestNavigationHidden(hide: Boolean = true, requiresAnimation: Boolean = true) { + val bottomView = binding.mainNavigation + if (requiresAnimation) { + bottomView.isVisible = true + bottomView.isHidden = hide + } else { + bottomView.isGone = hide + } + } + + fun invalidateToolbar() { + //binding.mainToolbar.startAnimations() + binding.mainToolbar.invalidate() + } + + private fun getScreen(name: String?): NavDirections? { + return when (name) { + Const.Nav.SUPERUSER -> MainDirections.actionSuperuserFragment() + Const.Nav.MODULES -> MainDirections.actionModuleFragment() + Const.Nav.SETTINGS -> HomeFragmentDirections.actionHomeFragmentToSettingsFragment() + else -> null + } + } + + private fun getScreen(id: Int): NavDirections? { + return when (id) { + R.id.homeFragment -> MainDirections.actionHomeFragment() + R.id.modulesFragment -> MainDirections.actionModuleFragment() + R.id.superuserFragment -> MainDirections.actionSuperuserFragment() + R.id.logFragment -> MainDirections.actionLogFragment() + else -> null + } + } + + @SuppressLint("InlinedApi") + override fun showInvalidStateMessage(): Unit = runOnUiThread { + MagiskDialog(this).apply { + setTitle(CoreR.string.unsupport_nonroot_stub_title) + setMessage(CoreR.string.unsupport_nonroot_stub_msg) + setButton(MagiskDialog.ButtonType.POSITIVE) { + text = CoreR.string.install + onClick { + withPermission(REQUEST_INSTALL_PACKAGES) { + if (!it) { + toast(CoreR.string.install_unknown_denied, Toast.LENGTH_SHORT) + showInvalidStateMessage() + } else { + lifecycleScope.launch { + AppMigration.restore(this@MainActivity) + } + } + } + } + } + setCancelable(false) + show() + } + } + + private fun showUnsupportedMessage() { + if (Info.env.isUnsupported) { + MagiskDialog(this).apply { + setTitle(CoreR.string.unsupport_magisk_title) + setMessage(CoreR.string.unsupport_magisk_msg, Const.Version.MIN_VERSION) + setButton(MagiskDialog.ButtonType.POSITIVE) { text = android.R.string.ok } + setCancelable(false) + }.show() + } + + if (!Info.isEmulator && Info.env.isActive && System.getenv("PATH") + ?.split(':') + ?.filterNot { File("$it/magisk").exists() } + ?.any { File("$it/su").exists() } == true) { + MagiskDialog(this).apply { + setTitle(CoreR.string.unsupport_general_title) + setMessage(CoreR.string.unsupport_other_su_msg) + setButton(MagiskDialog.ButtonType.POSITIVE) { text = android.R.string.ok } + setCancelable(false) + }.show() + } + + if (applicationInfo.flags and ApplicationInfo.FLAG_SYSTEM != 0) { + MagiskDialog(this).apply { + setTitle(CoreR.string.unsupport_general_title) + setMessage(CoreR.string.unsupport_system_app_msg) + setButton(MagiskDialog.ButtonType.POSITIVE) { text = android.R.string.ok } + setCancelable(false) + }.show() + } + + if (applicationInfo.flags and ApplicationInfo.FLAG_EXTERNAL_STORAGE != 0) { + MagiskDialog(this).apply { + setTitle(CoreR.string.unsupport_general_title) + setMessage(CoreR.string.unsupport_external_storage_msg) + setButton(MagiskDialog.ButtonType.POSITIVE) { text = android.R.string.ok } + setCancelable(false) + }.show() + } + } + + private fun askForHomeShortcut() { + if (isRunningAsStub && !Config.askedHome && + ShortcutManagerCompat.isRequestPinShortcutSupported(this)) { + // Ask and show dialog + Config.askedHome = true + MagiskDialog(this).apply { + setTitle(CoreR.string.add_shortcut_title) + setMessage(CoreR.string.add_shortcut_msg) + setButton(MagiskDialog.ButtonType.NEGATIVE) { + text = android.R.string.cancel + } + setButton(MagiskDialog.ButtonType.POSITIVE) { + text = android.R.string.ok + onClick { + Shortcuts.addHomeIcon(this@MainActivity) + } + } + setCancelable(true) + }.show() + } + } +} diff --git a/app/apk-ng/src/main/java/com/topjohnwu/magisk/ui/deny/AppProcessInfo.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/deny/AppProcessInfo.kt similarity index 59% rename from app/apk-ng/src/main/java/com/topjohnwu/magisk/ui/deny/AppProcessInfo.kt rename to app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/deny/AppProcessInfo.kt index 7f701174a..9863279d0 100644 --- a/app/apk-ng/src/main/java/com/topjohnwu/magisk/ui/deny/AppProcessInfo.kt +++ b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/deny/AppProcessInfo.kt @@ -12,6 +12,8 @@ import android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS import android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES import android.content.pm.ServiceInfo import android.graphics.drawable.Drawable +import android.os.Build +import android.os.Build.VERSION.SDK_INT import androidx.core.os.ProcessCompat import com.topjohnwu.magisk.core.ktx.getLabel import java.util.Locale @@ -29,36 +31,28 @@ class CmdlineListItem(line: String) { } const val ISOLATED_MAGIC = "isolated" -const val WEBVIEW_ZYGOTE_MAGIC = "webview_zygote" -const val WEBVIEW_ZYGOTE_UID = 1053 @SuppressLint("InlinedApi") class AppProcessInfo( private val info: ApplicationInfo, pm: PackageManager, - denyList: List, - private val labelOverride: String? = null, - private val processesOverride: Collection? = null, + denyList: List ) : Comparable { private val denyList = denyList.filter { it.packageName == info.packageName || it.packageName == ISOLATED_MAGIC } - val label = labelOverride ?: info.getLabel(pm) + val label = info.getLabel(pm) val iconImage: Drawable = runCatching { info.loadIcon(pm) }.getOrDefault(pm.defaultActivityIcon) val packageName: String get() = info.packageName - var firstInstallTime: Long = 0L - private set - var lastUpdateTime: Long = 0L - private set - val processes = processesOverride ?: fetchProcesses(pm) + val processes = fetchProcesses(pm) override fun compareTo(other: AppProcessInfo) = comparator.compare(this, other) fun isSystemApp() = info.flags and ApplicationInfo.FLAG_SYSTEM != 0 - fun isApp() = packageName == WEBVIEW_ZYGOTE_MAGIC || ProcessCompat.isApplicationUid(info.uid) + fun isApp() = ProcessCompat.isApplicationUid(info.uid) private fun createProcess(name: String, pkg: String = info.packageName) = ProcessInfo(name, pkg, denyList.any { it.process == name && it.packageName == pkg }) @@ -73,30 +67,19 @@ class AppProcessInfo( private fun Array?.toProcessList() = orEmpty().map { createProcess(it.getProcName()) } - private fun Array?.toProcessList(): List { - if (this == null) return emptyList() - val result = mutableListOf() - var hasIsolated = false - for (si in this) { - if (si.isIsolated) { - if (si.useAppZygote) { - val proc = info.processName ?: info.packageName - result.add(createProcess("${proc}_zygote")) - } else { - hasIsolated = true - } + private fun Array?.toProcessList() = orEmpty().map { + if (it.isIsolated) { + if (it.useAppZygote) { + val proc = info.processName ?: info.packageName + createProcess("${proc}_zygote") } else { - result.add(createProcess(si.getProcName())) + val proc = if (SDK_INT >= Build.VERSION_CODES.Q) + "${it.getProcName()}:${it.name}" else it.getProcName() + createProcess(proc, ISOLATED_MAGIC) } + } else { + createProcess(it.getProcName()) } - if (hasIsolated) { - val prefix = "${info.processName ?: info.packageName}:" - val isEnabled = denyList.any { - it.packageName == ISOLATED_MAGIC && it.process.startsWith(prefix) - } - result.add(ProcessInfo(prefix, ISOLATED_MAGIC, isEnabled)) - } - return result } private fun fetchProcesses(pm: PackageManager): Collection { @@ -109,9 +92,6 @@ class AppProcessInfo( pm.getPackageArchiveInfo(info.sourceDir, flag) ?: return emptyList() } - firstInstallTime = packageInfo.firstInstallTime - lastUpdateTime = packageInfo.lastUpdateTime - val processSet = TreeSet(compareBy({ it.name }, { it.isIsolated })) processSet += packageInfo.activities.toProcessList() processSet += packageInfo.services.toProcessList() @@ -121,30 +101,6 @@ class AppProcessInfo( } companion object { - fun webViewZygote( - pm: PackageManager, - denyList: List, - label: String, - ): AppProcessInfo { - val info = ApplicationInfo().apply { - packageName = WEBVIEW_ZYGOTE_MAGIC - uid = WEBVIEW_ZYGOTE_UID - } - val enabled = denyList.any { - it.packageName == WEBVIEW_ZYGOTE_MAGIC && - it.process == WEBVIEW_ZYGOTE_MAGIC - } - return AppProcessInfo( - info, - pm, - denyList, - labelOverride = label, - processesOverride = listOf( - ProcessInfo(WEBVIEW_ZYGOTE_MAGIC, WEBVIEW_ZYGOTE_MAGIC, enabled) - ), - ) - } - private val comparator = compareBy( { it.label.lowercase(Locale.ROOT) }, { it.info.packageName } @@ -158,4 +114,5 @@ data class ProcessInfo( var isEnabled: Boolean ) { val isIsolated = packageName == ISOLATED_MAGIC + val isAppZygote = name.endsWith("_zygote") } diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/deny/DenyListFragment.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/deny/DenyListFragment.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/ui/deny/DenyListFragment.kt rename to app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/deny/DenyListFragment.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/deny/DenyListRvItem.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/deny/DenyListRvItem.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/ui/deny/DenyListRvItem.kt rename to app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/deny/DenyListRvItem.kt diff --git a/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/deny/DenyListViewModel.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/deny/DenyListViewModel.kt new file mode 100644 index 000000000..dfca9852d --- /dev/null +++ b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/deny/DenyListViewModel.kt @@ -0,0 +1,89 @@ +package com.topjohnwu.magisk.ui.deny + +import android.annotation.SuppressLint +import android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES +import androidx.databinding.Bindable +import androidx.lifecycle.viewModelScope +import com.topjohnwu.magisk.BR +import com.topjohnwu.magisk.arch.AsyncLoadViewModel +import com.topjohnwu.magisk.core.AppContext +import com.topjohnwu.magisk.core.ktx.concurrentMap +import com.topjohnwu.magisk.databinding.bindExtra +import com.topjohnwu.magisk.databinding.filterList +import com.topjohnwu.magisk.databinding.set +import com.topjohnwu.superuser.Shell +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.asFlow +import kotlinx.coroutines.flow.filter +import kotlinx.coroutines.flow.toCollection +import kotlinx.coroutines.withContext + +class DenyListViewModel : AsyncLoadViewModel() { + + var isShowSystem = false + set(value) { + field = value + doQuery(query) + } + + var isShowOS = false + set(value) { + field = value + doQuery(query) + } + + var query = "" + set(value) { + field = value + doQuery(value) + } + + val items = filterList(viewModelScope) + val extraBindings = bindExtra { + it.put(BR.viewModel, this) + } + + @get:Bindable + var loading = true + private set(value) = set(value, field, { field = it }, BR.loading) + + @SuppressLint("InlinedApi") + override suspend fun doLoadWork() { + loading = true + val apps = withContext(Dispatchers.Default) { + val pm = AppContext.packageManager + val denyList = Shell.cmd("magisk --denylist ls").exec().out + .map { CmdlineListItem(it) } + val apps = pm.getInstalledApplications(MATCH_UNINSTALLED_PACKAGES).run { + asFlow() + .filter { AppContext.packageName != it.packageName } + .concurrentMap { AppProcessInfo(it, pm, denyList) } + .filter { it.processes.isNotEmpty() } + .concurrentMap { DenyListRvItem(it) } + .toCollection(ArrayList(size)) + } + apps.sort() + apps + } + items.set(apps) + doQuery(query) + } + + private fun doQuery(s: String) { + items.filter { + fun filterSystem() = isShowSystem || !it.info.isSystemApp() + + fun filterOS() = (isShowSystem && isShowOS) || it.info.isApp() + + fun filterQuery(): Boolean { + fun inName() = it.info.label.contains(s, true) + fun inPackage() = it.info.packageName.contains(s, true) + fun inProcesses() = it.processes.any { p -> p.process.name.contains(s, true) } + return inName() || inPackage() || inProcesses() + } + + (it.isChecked || (filterSystem() && filterOS())) && filterQuery() + } + loading = false + } +} diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/flash/ConsoleItem.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/flash/ConsoleItem.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/ui/flash/ConsoleItem.kt rename to app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/flash/ConsoleItem.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/flash/FlashFragment.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/flash/FlashFragment.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/ui/flash/FlashFragment.kt rename to app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/flash/FlashFragment.kt diff --git a/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/flash/FlashViewModel.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/flash/FlashViewModel.kt new file mode 100644 index 000000000..53abaff82 --- /dev/null +++ b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/flash/FlashViewModel.kt @@ -0,0 +1,128 @@ +package com.topjohnwu.magisk.ui.flash + +import android.os.Build +import android.view.MenuItem +import androidx.databinding.Bindable +import androidx.databinding.ObservableArrayList +import androidx.lifecycle.LiveData +import androidx.lifecycle.MutableLiveData +import androidx.lifecycle.map +import androidx.lifecycle.viewModelScope +import com.topjohnwu.magisk.BR +import com.topjohnwu.magisk.R +import com.topjohnwu.magisk.arch.BaseViewModel +import com.topjohnwu.magisk.core.Const +import com.topjohnwu.magisk.core.Info +import com.topjohnwu.magisk.core.ktx.reboot +import com.topjohnwu.magisk.core.ktx.synchronized +import com.topjohnwu.magisk.core.ktx.timeFormatStandard +import com.topjohnwu.magisk.core.ktx.toTime +import com.topjohnwu.magisk.core.tasks.FlashZip +import com.topjohnwu.magisk.core.tasks.MagiskInstaller +import com.topjohnwu.magisk.core.utils.MediaStoreUtils +import com.topjohnwu.magisk.core.utils.MediaStoreUtils.outputStream +import com.topjohnwu.magisk.databinding.set +import com.topjohnwu.magisk.events.SnackbarEvent +import com.topjohnwu.superuser.CallbackList +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch + +class FlashViewModel : BaseViewModel() { + + enum class State { + FLASHING, SUCCESS, FAILED + } + + private val _state = MutableLiveData(State.FLASHING) + val state: LiveData get() = _state + val flashing = state.map { it == State.FLASHING } + + @get:Bindable + var showReboot = Info.isRooted + set(value) = set(value, field, { field = it }, BR.showReboot) + + val items = ObservableArrayList() + lateinit var args: FlashFragmentArgs + + private val logItems = mutableListOf().synchronized() + private val outItems = object : CallbackList() { + override fun onAddElement(e: String?) { + e ?: return + items.add(ConsoleItem(e)) + logItems.add(e) + } + } + + fun startFlashing() { + val (action, uri) = args + + viewModelScope.launch { + val result = when (action) { + Const.Value.FLASH_ZIP -> { + uri ?: return@launch + FlashZip(uri, outItems, logItems).exec() + } + Const.Value.UNINSTALL -> { + showReboot = false + MagiskInstaller.Uninstall(outItems, logItems).exec() + } + Const.Value.FLASH_MAGISK -> { + if (Info.isEmulator) + MagiskInstaller.Emulator(outItems, logItems).exec() + else + MagiskInstaller.Direct(outItems, logItems).exec() + } + Const.Value.FLASH_INACTIVE_SLOT -> { + showReboot = false + MagiskInstaller.SecondSlot(outItems, logItems).exec() + } + Const.Value.PATCH_FILE -> { + uri ?: return@launch + showReboot = false + MagiskInstaller.Patch(uri, outItems, logItems).exec() + } + Const.Value.DOWNLOAD -> { + uri ?: return@launch + showReboot = false + MagiskInstaller.Download(uri.toString(), outItems, logItems).exec() + } + else -> { + back() + return@launch + } + } + onResult(result) + } + } + + private fun onResult(success: Boolean) { + _state.value = if (success) State.SUCCESS else State.FAILED + } + + fun onMenuItemClicked(item: MenuItem): Boolean { + when (item.itemId) { + R.id.action_save -> savePressed() + } + return true + } + + private fun savePressed() = withExternalRW { + viewModelScope.launch(Dispatchers.IO) { + val name = "magisk_install_log_%s.log".format( + System.currentTimeMillis().toTime(timeFormatStandard) + ) + val file = MediaStoreUtils.getFile(name) + file.uri.outputStream().bufferedWriter().use { writer -> + synchronized(logItems) { + logItems.forEach { + writer.write(it) + writer.newLine() + } + } + } + SnackbarEvent(file.toString()).publish() + } + } + + fun restartPressed() = reboot() +} diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/home/DeveloperItem.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/home/DeveloperItem.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/ui/home/DeveloperItem.kt rename to app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/home/DeveloperItem.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/home/HomeFragment.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/home/HomeFragment.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/ui/home/HomeFragment.kt rename to app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/home/HomeFragment.kt diff --git a/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/home/HomeViewModel.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/home/HomeViewModel.kt new file mode 100644 index 000000000..4a0aa8275 --- /dev/null +++ b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/home/HomeViewModel.kt @@ -0,0 +1,166 @@ +package com.topjohnwu.magisk.ui.home + +import android.content.ActivityNotFoundException +import android.content.Context +import android.content.Intent +import android.widget.Toast +import androidx.core.net.toUri +import androidx.databinding.Bindable +import com.topjohnwu.magisk.BR +import com.topjohnwu.magisk.R +import com.topjohnwu.magisk.arch.ActivityExecutor +import com.topjohnwu.magisk.arch.AsyncLoadViewModel +import com.topjohnwu.magisk.arch.ContextExecutor +import com.topjohnwu.magisk.arch.UIActivity +import com.topjohnwu.magisk.arch.ViewEvent +import com.topjohnwu.magisk.core.BuildConfig +import com.topjohnwu.magisk.core.Config +import com.topjohnwu.magisk.core.Info +import com.topjohnwu.magisk.core.download.Subject +import com.topjohnwu.magisk.core.download.Subject.App +import com.topjohnwu.magisk.core.ktx.await +import com.topjohnwu.magisk.core.ktx.toast +import com.topjohnwu.magisk.core.repository.NetworkService +import com.topjohnwu.magisk.core.utils.asText +import com.topjohnwu.magisk.databinding.bindExtra +import com.topjohnwu.magisk.databinding.set +import com.topjohnwu.magisk.dialog.EnvFixDialog +import com.topjohnwu.magisk.dialog.ManagerInstallDialog +import com.topjohnwu.magisk.dialog.UninstallDialog +import com.topjohnwu.magisk.events.SnackbarEvent +import com.topjohnwu.superuser.Shell +import kotlin.math.roundToInt +import com.topjohnwu.magisk.core.R as CoreR + +class HomeViewModel( + private val svc: NetworkService +) : AsyncLoadViewModel() { + + enum class State { + LOADING, INVALID, OUTDATED, UP_TO_DATE + } + + val magiskTitleBarrierIds = + intArrayOf(R.id.home_magisk_icon, R.id.home_magisk_title, R.id.home_magisk_button) + val appTitleBarrierIds = + intArrayOf(R.id.home_manager_icon, R.id.home_manager_title, R.id.home_manager_button) + + @get:Bindable + var isNoticeVisible = Config.safetyNotice + set(value) = set(value, field, { field = it }, BR.noticeVisible) + + val magiskState + get() = when { + Info.isRooted && Info.env.isUnsupported -> State.OUTDATED + !Info.env.isActive -> State.INVALID + Info.env.versionCode < BuildConfig.APP_VERSION_CODE -> State.OUTDATED + else -> State.UP_TO_DATE + } + + @get:Bindable + var appState = State.LOADING + set(value) = set(value, field, { field = it }, BR.appState) + + val magiskInstalledVersion + get() = Info.env.run { + if (isActive) + ("$versionString ($versionCode)" + if (isDebug) " (D)" else "").asText() + else + CoreR.string.not_available.asText() + } + + @get:Bindable + var managerRemoteVersion = CoreR.string.loading.asText() + set(value) = set(value, field, { field = it }, BR.managerRemoteVersion) + + val managerInstalledVersion + get() = "${BuildConfig.APP_VERSION_NAME} (${BuildConfig.APP_VERSION_CODE})" + + if (BuildConfig.DEBUG) " (D)" else "" + + @get:Bindable + var stateManagerProgress = 0 + set(value) = set(value, field, { field = it }, BR.stateManagerProgress) + + val extraBindings = bindExtra { + it.put(BR.viewModel, this) + } + + companion object { + private var checkedEnv = false + } + + override suspend fun doLoadWork() { + appState = State.LOADING + Info.fetchUpdate(svc)?.apply { + appState = when { + BuildConfig.APP_VERSION_CODE < versionCode -> State.OUTDATED + else -> State.UP_TO_DATE + } + + val isDebug = Config.updateChannel == Config.Value.DEBUG_CHANNEL + managerRemoteVersion = + ("$version (${versionCode})" + if (isDebug) " (D)" else "").asText() + } ?: run { + appState = State.INVALID + managerRemoteVersion = CoreR.string.not_available.asText() + } + ensureEnv() + } + + override fun onNetworkChanged(network: Boolean) = startLoading() + + fun onProgressUpdate(progress: Float, subject: Subject) { + if (subject is App) + stateManagerProgress = progress.times(100f).roundToInt() + } + + fun onLinkPressed(link: String) = object : ViewEvent(), ContextExecutor { + override fun invoke(context: Context) { + val intent = Intent(Intent.ACTION_VIEW, link.toUri()) + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + try { + context.startActivity(intent) + } catch (e: ActivityNotFoundException) { + context.toast(CoreR.string.open_link_failed_toast, Toast.LENGTH_SHORT) + } + } + }.publish() + + fun onDeletePressed() = UninstallDialog().show() + + fun onManagerPressed() = when (appState) { + State.LOADING -> SnackbarEvent(CoreR.string.loading).publish() + State.INVALID -> SnackbarEvent(CoreR.string.no_connection).publish() + else -> withExternalRW { + withInstallPermission { + ManagerInstallDialog().show() + } + } + } + + fun onMagiskPressed() = withExternalRW { + HomeFragmentDirections.actionHomeFragmentToInstallFragment().navigate() + } + + fun hideNotice() { + Config.safetyNotice = false + isNoticeVisible = false + } + + private suspend fun ensureEnv() { + if (magiskState == State.INVALID || checkedEnv) return + val cmd = "env_check ${Info.env.versionString} ${Info.env.versionCode}" + val code = Shell.cmd(cmd).await().code + if (code != 0) { + EnvFixDialog(this, code).show() + } + checkedEnv = true + } + + val showTest = false + fun onTestPressed() = object : ViewEvent(), ActivityExecutor { + override fun invoke(activity: UIActivity<*>) { + /* Entry point to trigger test events within the app */ + } + }.publish() +} diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/home/RebootMenu.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/home/RebootMenu.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/ui/home/RebootMenu.kt rename to app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/home/RebootMenu.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/install/InstallFragment.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/install/InstallFragment.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/ui/install/InstallFragment.kt rename to app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/install/InstallFragment.kt diff --git a/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/install/InstallViewModel.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/install/InstallViewModel.kt new file mode 100644 index 000000000..40e323962 --- /dev/null +++ b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/install/InstallViewModel.kt @@ -0,0 +1,191 @@ +package com.topjohnwu.magisk.ui.install + +import android.net.Uri +import android.os.Bundle +import android.os.Parcelable +import android.text.Spanned +import android.text.SpannedString +import android.widget.Toast +import androidx.databinding.Bindable +import androidx.lifecycle.LiveData +import androidx.lifecycle.MutableLiveData +import androidx.lifecycle.Observer +import androidx.lifecycle.viewModelScope +import com.topjohnwu.magisk.BR +import com.topjohnwu.magisk.R +import com.topjohnwu.magisk.arch.BaseViewModel +import com.topjohnwu.magisk.core.AppContext +import com.topjohnwu.magisk.core.BuildConfig.APP_VERSION_CODE +import com.topjohnwu.magisk.core.Config +import com.topjohnwu.magisk.core.Info +import com.topjohnwu.magisk.core.base.ContentResultCallback +import com.topjohnwu.magisk.core.ktx.toast +import com.topjohnwu.magisk.core.repository.NetworkService +import com.topjohnwu.magisk.databinding.set +import com.topjohnwu.magisk.dialog.DownloadDialog +import com.topjohnwu.magisk.dialog.SecondSlotWarningDialog +import com.topjohnwu.magisk.events.GetContentEvent +import com.topjohnwu.magisk.ui.flash.FlashFragment +import io.noties.markwon.Markwon +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import kotlinx.parcelize.Parcelize +import timber.log.Timber +import java.io.File +import java.io.IOException +import com.topjohnwu.magisk.core.R as CoreR + +class InstallViewModel(svc: NetworkService, markwon: Markwon) : BaseViewModel() { + + val isRooted get() = Info.isRooted + val skipOptions = Info.isEmulator || (Info.isSAR && !Info.isFDE && Info.ramdisk) + val noSecondSlot = !isRooted || !Info.isAB || Info.isEmulator + + @get:Bindable + var step = if (skipOptions) 1 else 0 + set(value) = set(value, field, { field = it }, BR.step) + + private var methodId = -1 + private var spuriousMethodId = -1 + + @get:Bindable + var method + get() = methodId + set(value) = set(value, methodId, { methodId = it }, BR.method) { + if (it == spuriousMethodId) { + spuriousMethodId = -1 + return@set + } + when (it) { + R.id.method_patch -> { + GetContentEvent("*/*", UriCallback()).publish() + } + R.id.method_download -> { + DownloadDialog( + callback = { url -> _uri.value = url }, + onCancel = { resetMethod() }, + ).show() + } + R.id.method_inactive_slot -> { + SecondSlotWarningDialog().show() + } + } + } + + private fun resetMethod() { + spuriousMethodId = methodId + method = -1 + } + + private val _uri = MutableLiveData() + val data: LiveData get() = _uri + + private val sourceObserver = Observer { source -> + when (source) { + is PatchSource.File -> _uri.value = source.uri + PatchSource.Cancelled -> resetMethod() + null -> return@Observer + } + patchSource.value = null + } + + @get:Bindable + var notes: Spanned = SpannedString("") + set(value) = set(value, field, { field = it }, BR.notes) + + init { + patchSource.observeForever(sourceObserver) + viewModelScope.launch(Dispatchers.IO) { + try { + val noteFile = File(AppContext.cacheDir, "${APP_VERSION_CODE}.md") + val noteText = when { + noteFile.exists() -> noteFile.readText() + else -> { + val note = svc.fetchUpdate(APP_VERSION_CODE)?.note.orEmpty() + if (note.isEmpty()) return@launch + noteFile.writeText(note) + note + } + } + val spanned = markwon.toMarkdown(noteText) + withContext(Dispatchers.Main) { + notes = spanned + } + } catch (e: IOException) { + Timber.e(e) + } + } + } + + fun install() { + when (method) { + R.id.method_patch -> FlashFragment.patch(data.value!!).navigate(true) + R.id.method_download -> FlashFragment.download(data.value!!).navigate(true) + R.id.method_direct -> FlashFragment.flash(false).navigate(true) + R.id.method_inactive_slot -> FlashFragment.flash(true).navigate(true) + else -> error("Unknown value") + } + } + + override fun onSaveState(state: Bundle) { + state.putParcelable( + INSTALL_STATE_KEY, InstallState( + methodId, + step, + Config.keepVerity, + Config.keepEnc, + Config.recovery + ) + ) + } + + override fun onRestoreState(state: Bundle) { + state.getParcelable(INSTALL_STATE_KEY)?.let { + methodId = it.method + step = it.step + Config.keepVerity = it.keepVerity + Config.keepEnc = it.keepEnc + Config.recovery = it.recovery + } + } + + override fun onCleared() { + patchSource.removeObserver(sourceObserver) + super.onCleared() + } + + private sealed interface PatchSource { + data class File(val uri: Uri) : PatchSource + data object Cancelled : PatchSource + } + + @Parcelize + class UriCallback : ContentResultCallback { + override fun onActivityLaunch() { + AppContext.toast(CoreR.string.patch_file_msg, Toast.LENGTH_LONG) + } + + override fun onActivityResult(result: Uri) { + patchSource.value = PatchSource.File(result) + } + + override fun onActivityCancel() { + patchSource.value = PatchSource.Cancelled + } + } + + @Parcelize + class InstallState( + val method: Int, + val step: Int, + val keepVerity: Boolean, + val keepEnc: Boolean, + val recovery: Boolean, + ) : Parcelable + + companion object { + private const val INSTALL_STATE_KEY = "install_state" + private val patchSource = MutableLiveData() + } +} diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/log/LogFragment.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/log/LogFragment.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/ui/log/LogFragment.kt rename to app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/log/LogFragment.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/log/LogRvItem.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/log/LogRvItem.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/ui/log/LogRvItem.kt rename to app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/log/LogRvItem.kt diff --git a/app/apk-ng/src/main/java/com/topjohnwu/magisk/ui/log/LogViewModel.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/log/LogViewModel.kt similarity index 64% rename from app/apk-ng/src/main/java/com/topjohnwu/magisk/ui/log/LogViewModel.kt rename to app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/log/LogViewModel.kt index 96eaf3411..928a6f823 100644 --- a/app/apk-ng/src/main/java/com/topjohnwu/magisk/ui/log/LogViewModel.kt +++ b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/log/LogViewModel.kt @@ -1,24 +1,24 @@ package com.topjohnwu.magisk.ui.log import android.system.Os +import androidx.databinding.Bindable import androidx.lifecycle.viewModelScope +import com.topjohnwu.magisk.BR import com.topjohnwu.magisk.arch.AsyncLoadViewModel import com.topjohnwu.magisk.core.BuildConfig import com.topjohnwu.magisk.core.Info import com.topjohnwu.magisk.core.R import com.topjohnwu.magisk.core.ktx.timeFormatStandard import com.topjohnwu.magisk.core.ktx.toTime -import com.topjohnwu.magisk.core.model.su.SuLog import com.topjohnwu.magisk.core.repository.LogRepository -import com.topjohnwu.magisk.core.su.SuEvents import com.topjohnwu.magisk.core.utils.MediaStoreUtils import com.topjohnwu.magisk.core.utils.MediaStoreUtils.outputStream +import com.topjohnwu.magisk.databinding.bindExtra +import com.topjohnwu.magisk.databinding.diffList +import com.topjohnwu.magisk.databinding.set +import com.topjohnwu.magisk.events.SnackbarEvent +import com.topjohnwu.magisk.view.TextItem import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.flow.asStateFlow -import kotlinx.coroutines.flow.debounce -import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.io.FileInputStream @@ -26,42 +26,46 @@ import java.io.FileInputStream class LogViewModel( private val repo: LogRepository ) : AsyncLoadViewModel() { + @get:Bindable + var loading = true + private set(value) = set(value, field, { field = it }, BR.loading) - init { - @OptIn(kotlinx.coroutines.FlowPreview::class) - viewModelScope.launch { - SuEvents.logUpdated.debounce(500).collect { reload() } - } + // --- empty view + + val itemEmpty = TextItem(R.string.log_data_none) + val itemMagiskEmpty = TextItem(R.string.log_data_magisk_none) + + // --- su log + + val items = diffList() + val extraBindings = bindExtra { + it.put(BR.viewModel, this) } - data class UiState( - val loading: Boolean = true, - val magiskLog: String = "", - val magiskLogEntries: List = emptyList(), - val suLogs: List = emptyList(), - ) - - private val _uiState = MutableStateFlow(UiState()) - val uiState: StateFlow = _uiState.asStateFlow() - - private var magiskLogRaw = "" + // --- magisk log + val logs = diffList() + var magiskLogRaw = " " override suspend fun doLoadWork() { - _uiState.update { it.copy(loading = true) } - withContext(Dispatchers.Default) { + loading = true + + val (suLogs, suDiff) = withContext(Dispatchers.Default) { magiskLogRaw = repo.fetchMagiskLogs() - val suLogs = repo.fetchSuLogs() - val entries = MagiskLogParser.parse(magiskLogRaw) - _uiState.update { it.copy( - loading = false, - magiskLog = magiskLogRaw, - magiskLogEntries = entries, - suLogs = suLogs, - ) } + val newLogs = magiskLogRaw.split('\n').map { LogRvItem(it) } + logs.update(newLogs) + val suLogs = repo.fetchSuLogs().map { SuLogRvItem(it) } + suLogs to items.calculateDiff(suLogs) } + + items.firstOrNull()?.isTop = false + items.lastOrNull()?.isBottom = false + items.update(suLogs, suDiff) + items.firstOrNull()?.isTop = true + items.lastOrNull()?.isBottom = true + loading = false } - fun saveMagiskLog() { + fun saveMagiskLog() = withExternalRW { viewModelScope.launch(Dispatchers.IO) { val filename = "magisk_log_%s.log".format( System.currentTimeMillis().toTime(timeFormatStandard)) @@ -93,18 +97,18 @@ class LogViewModel( ProcessBuilder("logcat", "-d").start() .inputStream.reader().use { it.copyTo(file) } } - showSnackbar(logFile.toString()) + SnackbarEvent(logFile.toString()).publish() } } fun clearMagiskLog() = repo.clearMagiskLogs { - showSnackbar(R.string.logs_cleared) + SnackbarEvent(R.string.logs_cleared).publish() startLoading() } fun clearLog() = viewModelScope.launch { repo.clearLogs() - showSnackbar(R.string.logs_cleared) + SnackbarEvent(R.string.logs_cleared).publish() startLoading() } } diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/log/SuLogRvItem.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/log/SuLogRvItem.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/ui/log/SuLogRvItem.kt rename to app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/log/SuLogRvItem.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/module/ActionFragment.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/module/ActionFragment.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/ui/module/ActionFragment.kt rename to app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/module/ActionFragment.kt diff --git a/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/module/ActionViewModel.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/module/ActionViewModel.kt new file mode 100644 index 000000000..2591aadd1 --- /dev/null +++ b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/module/ActionViewModel.kt @@ -0,0 +1,88 @@ +package com.topjohnwu.magisk.ui.module + +import android.view.MenuItem +import androidx.databinding.ObservableArrayList +import androidx.lifecycle.LiveData +import androidx.lifecycle.MutableLiveData +import androidx.lifecycle.viewModelScope +import com.topjohnwu.magisk.R +import com.topjohnwu.magisk.arch.BaseViewModel +import com.topjohnwu.magisk.core.ktx.synchronized +import com.topjohnwu.magisk.core.ktx.timeFormatStandard +import com.topjohnwu.magisk.core.ktx.toTime +import com.topjohnwu.magisk.core.utils.MediaStoreUtils +import com.topjohnwu.magisk.core.utils.MediaStoreUtils.outputStream +import com.topjohnwu.magisk.events.SnackbarEvent +import com.topjohnwu.magisk.ui.flash.ConsoleItem +import com.topjohnwu.superuser.CallbackList +import com.topjohnwu.superuser.Shell +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import timber.log.Timber +import java.io.IOException + +class ActionViewModel : BaseViewModel() { + + enum class State { + RUNNING, SUCCESS, FAILED + } + + private val _state = MutableLiveData(State.RUNNING) + val state: LiveData get() = _state + + val items = ObservableArrayList() + lateinit var args: ActionFragmentArgs + + private val logItems = mutableListOf().synchronized() + private val outItems = object : CallbackList() { + override fun onAddElement(e: String?) { + e ?: return + items.add(ConsoleItem(e)) + logItems.add(e) + } + } + + fun startRunAction() = viewModelScope.launch { + onResult(withContext(Dispatchers.IO) { + try { + Shell.cmd("run_action \'${args.id}\'") + .to(outItems, logItems) + .exec().isSuccess + } catch (e: IOException) { + Timber.e(e) + false + } + }) + } + + private fun onResult(success: Boolean) { + _state.value = if (success) State.SUCCESS else State.FAILED + } + + fun onMenuItemClicked(item: MenuItem): Boolean { + when (item.itemId) { + R.id.action_save -> savePressed() + } + return true + } + + private fun savePressed() = withExternalRW { + viewModelScope.launch(Dispatchers.IO) { + val name = "%s_action_log_%s.log".format( + args.name, + System.currentTimeMillis().toTime(timeFormatStandard) + ) + val file = MediaStoreUtils.getFile(name) + file.uri.outputStream().bufferedWriter().use { writer -> + synchronized(logItems) { + logItems.forEach { + writer.write(it) + writer.newLine() + } + } + } + SnackbarEvent(file.toString()).publish() + } + } +} diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/module/ModuleFragment.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/module/ModuleFragment.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/ui/module/ModuleFragment.kt rename to app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/module/ModuleFragment.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/module/ModuleRvItem.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/module/ModuleRvItem.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/ui/module/ModuleRvItem.kt rename to app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/module/ModuleRvItem.kt diff --git a/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/module/ModuleViewModel.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/module/ModuleViewModel.kt new file mode 100644 index 000000000..863206338 --- /dev/null +++ b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/module/ModuleViewModel.kt @@ -0,0 +1,108 @@ +package com.topjohnwu.magisk.ui.module + +import android.net.Uri +import androidx.databinding.Bindable +import androidx.lifecycle.MutableLiveData +import com.topjohnwu.magisk.BR +import com.topjohnwu.magisk.MainDirections +import com.topjohnwu.magisk.R +import com.topjohnwu.magisk.arch.AsyncLoadViewModel +import com.topjohnwu.magisk.core.Const +import com.topjohnwu.magisk.core.Info +import com.topjohnwu.magisk.core.base.ContentResultCallback +import com.topjohnwu.magisk.core.model.module.LocalModule +import com.topjohnwu.magisk.core.model.module.OnlineModule +import com.topjohnwu.magisk.databinding.MergeObservableList +import com.topjohnwu.magisk.databinding.RvItem +import com.topjohnwu.magisk.databinding.bindExtra +import com.topjohnwu.magisk.databinding.diffList +import com.topjohnwu.magisk.databinding.set +import com.topjohnwu.magisk.dialog.LocalModuleInstallDialog +import com.topjohnwu.magisk.dialog.OnlineModuleInstallDialog +import com.topjohnwu.magisk.events.GetContentEvent +import com.topjohnwu.magisk.events.SnackbarEvent +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import kotlinx.parcelize.Parcelize +import com.topjohnwu.magisk.core.R as CoreR + +class ModuleViewModel : AsyncLoadViewModel() { + + val bottomBarBarrierIds = intArrayOf(R.id.module_update, R.id.module_remove) + + private val itemsInstalled = diffList() + + val items = MergeObservableList() + val extraBindings = bindExtra { + it.put(BR.viewModel, this) + } + + val data get() = uri + + @get:Bindable + var loading = true + private set(value) = set(value, field, { field = it }, BR.loading) + + override suspend fun doLoadWork() { + loading = true + val moduleLoaded = Info.env.isActive && + withContext(Dispatchers.IO) { LocalModule.loaded() } + if (moduleLoaded) { + loadInstalled() + if (items.isEmpty()) { + items.insertItem(InstallModule) + .insertList(itemsInstalled) + } + } + loading = false + loadUpdateInfo() + } + + override fun onNetworkChanged(network: Boolean) = startLoading() + + private suspend fun loadInstalled() { + withContext(Dispatchers.Default) { + val installed = LocalModule.installed().map { LocalModuleRvItem(it) } + itemsInstalled.update(installed) + } + } + + private suspend fun loadUpdateInfo() { + withContext(Dispatchers.IO) { + itemsInstalled.forEach { + if (it.item.fetch()) + it.fetchedUpdateInfo() + } + } + } + + fun downloadPressed(item: OnlineModule?) = + if (item != null && Info.isConnected.value == true) { + withExternalRW { OnlineModuleInstallDialog(item).show() } + } else { + SnackbarEvent(CoreR.string.no_connection).publish() + } + + fun installPressed() = withExternalRW { + GetContentEvent("application/zip", UriCallback()).publish() + } + + fun requestInstallLocalModule(uri: Uri, displayName: String) { + LocalModuleInstallDialog(this, uri, displayName).show() + } + + @Parcelize + class UriCallback : ContentResultCallback { + override fun onActivityResult(result: Uri) { + uri.value = result + } + } + + fun runAction(id: String, name: String) { + MainDirections.actionActionFragment(id, name).navigate() + } + + companion object { + private val uri = MutableLiveData() + } +} diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/settings/BaseSettingsItem.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/settings/BaseSettingsItem.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/ui/settings/BaseSettingsItem.kt rename to app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/settings/BaseSettingsItem.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/settings/SettingsFragment.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/settings/SettingsFragment.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/ui/settings/SettingsFragment.kt rename to app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/settings/SettingsFragment.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/settings/SettingsItems.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/settings/SettingsItems.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/ui/settings/SettingsItems.kt rename to app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/settings/SettingsItems.kt diff --git a/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/settings/SettingsViewModel.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/settings/SettingsViewModel.kt new file mode 100644 index 000000000..e8dd010f9 --- /dev/null +++ b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/settings/SettingsViewModel.kt @@ -0,0 +1,132 @@ +package com.topjohnwu.magisk.ui.settings + +import android.app.Activity +import android.content.Intent +import android.net.Uri +import android.os.Build +import android.provider.Settings +import android.view.View +import android.widget.Toast +import androidx.core.content.pm.ShortcutManagerCompat +import androidx.lifecycle.viewModelScope +import com.topjohnwu.magisk.BR +import com.topjohnwu.magisk.arch.BaseViewModel +import com.topjohnwu.magisk.core.AppContext +import com.topjohnwu.magisk.core.BuildConfig +import com.topjohnwu.magisk.core.Config +import com.topjohnwu.magisk.core.Const +import com.topjohnwu.magisk.core.Info +import com.topjohnwu.magisk.core.R +import com.topjohnwu.magisk.core.isRunningAsStub +import com.topjohnwu.magisk.core.ktx.activity +import com.topjohnwu.magisk.core.ktx.toast +import com.topjohnwu.magisk.core.tasks.AppMigration +import com.topjohnwu.magisk.core.utils.LocaleSetting +import com.topjohnwu.magisk.core.utils.RootUtils +import com.topjohnwu.magisk.databinding.bindExtra +import com.topjohnwu.magisk.events.AddHomeIconEvent +import com.topjohnwu.magisk.events.AuthEvent +import com.topjohnwu.magisk.events.SnackbarEvent +import kotlinx.coroutines.launch + +class SettingsViewModel : BaseViewModel(), BaseSettingsItem.Handler { + + val items = createItems() + val extraBindings = bindExtra { + it.put(BR.handler, this) + } + + private fun createItems(): List { + val context = AppContext + val hidden = context.packageName != BuildConfig.APP_PACKAGE_NAME + + // Customization + val list = mutableListOf( + Customization, + Theme, if (LocaleSetting.useLocaleManager) LanguageSystem else Language + ) + if (isRunningAsStub && ShortcutManagerCompat.isRequestPinShortcutSupported(context)) + list.add(AddShortcut) + + // Manager + list.addAll(listOf( + AppSettings, + UpdateChannel, UpdateChannelUrl, DoHToggle, UpdateChecker, DownloadPath, RandNameToggle + )) + if (Info.env.isActive && Const.USER_ID == 0) { + if (hidden) list.add(Restore) else list.add(Hide) + } + + // Magisk + if (Info.env.isActive) { + list.addAll(listOf( + Magisk, + SystemlessHosts + )) + if (Const.Version.atLeast_24_0()) { + list.addAll(listOf(Zygisk, DenyList, DenyListConfig)) + } + } + + // Superuser + if (Info.showSuperUser) { + list.addAll(listOf( + Superuser, + Tapjack, Authentication, AccessMode, MultiuserMode, MountNamespaceMode, + AutomaticResponse, RequestTimeout, SUNotification + )) + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { + // Re-authenticate is not feasible on 8.0+ + list.add(Reauthenticate) + } + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + // Can hide overlay windows on 12.0+ + list.remove(Tapjack) + } + if (Const.Version.atLeast_30_1()) { + list.add(Restrict) + } + } + + return list + } + + override fun onItemPressed(view: View, item: BaseSettingsItem, doAction: () -> Unit) { + when (item) { + DownloadPath -> withExternalRW(doAction) + UpdateChecker -> withPostNotificationPermission(doAction) + Authentication -> AuthEvent(doAction).publish() + AutomaticResponse -> if (Config.suAuth) AuthEvent(doAction).publish() else doAction() + else -> doAction() + } + } + + override fun onItemAction(view: View, item: BaseSettingsItem) { + when (item) { + Theme -> SettingsFragmentDirections.actionSettingsFragmentToThemeFragment().navigate() + LanguageSystem -> view.activity.startActivity(LocaleSetting.localeSettingsIntent) + AddShortcut -> AddHomeIconEvent().publish() + SystemlessHosts -> createHosts() + DenyListConfig -> SettingsFragmentDirections.actionSettingsFragmentToDenyFragment().navigate() + UpdateChannel -> openUrlIfNecessary(view) + is Hide -> viewModelScope.launch { AppMigration.hide(view.activity, item.value) } + Restore -> viewModelScope.launch { AppMigration.restore(view.activity) } + Zygisk -> if (Zygisk.mismatch) SnackbarEvent(R.string.reboot_apply_change).publish() + else -> Unit + } + } + + private fun openUrlIfNecessary(view: View) { + UpdateChannelUrl.refresh() + if (UpdateChannelUrl.isEnabled && UpdateChannelUrl.value.isBlank()) { + UpdateChannelUrl.onPressed(view, this) + } + } + + private fun createHosts() { + viewModelScope.launch { + RootUtils.addSystemlessHosts() + AppContext.toast(R.string.settings_hosts_toast, Toast.LENGTH_SHORT) + } + } +} diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/superuser/PolicyRvItem.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/superuser/PolicyRvItem.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/ui/superuser/PolicyRvItem.kt rename to app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/superuser/PolicyRvItem.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/superuser/SuperuserFragment.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/superuser/SuperuserFragment.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/ui/superuser/SuperuserFragment.kt rename to app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/superuser/SuperuserFragment.kt diff --git a/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/superuser/SuperuserViewModel.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/superuser/SuperuserViewModel.kt new file mode 100644 index 000000000..3e0116b2b --- /dev/null +++ b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/superuser/SuperuserViewModel.kt @@ -0,0 +1,180 @@ +package com.topjohnwu.magisk.ui.superuser + +import android.annotation.SuppressLint +import android.content.pm.PackageManager +import android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES +import android.os.Process +import androidx.databinding.Bindable +import androidx.databinding.ObservableArrayList +import androidx.lifecycle.viewModelScope +import com.topjohnwu.magisk.BR +import com.topjohnwu.magisk.arch.AsyncLoadViewModel +import com.topjohnwu.magisk.core.AppContext +import com.topjohnwu.magisk.core.Config +import com.topjohnwu.magisk.core.Info +import com.topjohnwu.magisk.core.R +import com.topjohnwu.magisk.core.data.magiskdb.PolicyDao +import com.topjohnwu.magisk.core.ktx.getLabel +import com.topjohnwu.magisk.core.model.su.SuPolicy +import com.topjohnwu.magisk.core.utils.asText +import com.topjohnwu.magisk.databinding.MergeObservableList +import com.topjohnwu.magisk.databinding.RvItem +import com.topjohnwu.magisk.databinding.bindExtra +import com.topjohnwu.magisk.databinding.diffList +import com.topjohnwu.magisk.databinding.set +import com.topjohnwu.magisk.dialog.SuperuserRevokeDialog +import com.topjohnwu.magisk.events.AuthEvent +import com.topjohnwu.magisk.events.SnackbarEvent +import com.topjohnwu.magisk.view.TextItem +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import java.util.Locale + +class SuperuserViewModel( + private val db: PolicyDao +) : AsyncLoadViewModel() { + + private val itemNoData = TextItem(R.string.superuser_policy_none) + + private val itemsHelpers = ObservableArrayList() + private val itemsPolicies = diffList() + + val items = MergeObservableList() + .insertList(itemsHelpers) + .insertList(itemsPolicies) + val extraBindings = bindExtra { + it.put(BR.listener, this) + } + + @get:Bindable + var loading = true + private set(value) = set(value, field, { field = it }, BR.loading) + + @SuppressLint("InlinedApi") + override suspend fun doLoadWork() { + if (!Info.showSuperUser) { + loading = false + return + } + loading = true + withContext(Dispatchers.IO) { + db.deleteOutdated() + db.delete(AppContext.applicationInfo.uid) + val policies = ArrayList() + val pm = AppContext.packageManager + for (policy in db.fetchAll()) { + val pkgs = + if (policy.uid == Process.SYSTEM_UID) arrayOf("android") + else pm.getPackagesForUid(policy.uid) + if (pkgs == null) { + db.delete(policy.uid) + continue + } + val map = pkgs.mapNotNull { pkg -> + try { + val info = pm.getPackageInfo(pkg, MATCH_UNINSTALLED_PACKAGES) + PolicyRvItem( + this@SuperuserViewModel, policy, + info.packageName, + info.sharedUserId != null, + info.applicationInfo?.loadIcon(pm) ?: pm.defaultActivityIcon, + info.applicationInfo?.getLabel(pm) ?: info.packageName + ) + } catch (e: PackageManager.NameNotFoundException) { + null + } + } + if (map.isEmpty()) { + db.delete(policy.uid) + continue + } + policies.addAll(map) + } + policies.sortWith(compareBy( + { it.appName.lowercase(Locale.ROOT) }, + { it.packageName } + )) + itemsPolicies.update(policies) + } + if (itemsPolicies.isNotEmpty()) + itemsHelpers.clear() + else if (itemsHelpers.isEmpty()) + itemsHelpers.add(itemNoData) + loading = false + } + + // --- + + fun deletePressed(item: PolicyRvItem) { + fun updateState() = viewModelScope.launch { + db.delete(item.item.uid) + val list = ArrayList(itemsPolicies) + list.removeAll { it.item.uid == item.item.uid } + itemsPolicies.update(list) + if (list.isEmpty() && itemsHelpers.isEmpty()) { + itemsHelpers.add(itemNoData) + } + } + + if (Config.suAuth) { + AuthEvent { updateState() }.publish() + } else { + SuperuserRevokeDialog(item.title) { updateState() }.show() + } + } + + fun updateNotify(item: PolicyRvItem) { + viewModelScope.launch { + db.update(item.item) + val res = when { + item.item.notification -> R.string.su_snack_notif_on + else -> R.string.su_snack_notif_off + } + itemsPolicies.forEach { + if (it.item.uid == item.item.uid) { + it.notifyPropertyChanged(BR.shouldNotify) + } + } + SnackbarEvent(res.asText(item.appName)).publish() + } + } + + fun updateLogging(item: PolicyRvItem) { + viewModelScope.launch { + db.update(item.item) + val res = when { + item.item.logging -> R.string.su_snack_log_on + else -> R.string.su_snack_log_off + } + itemsPolicies.forEach { + if (it.item.uid == item.item.uid) { + it.notifyPropertyChanged(BR.shouldLog) + } + } + SnackbarEvent(res.asText(item.appName)).publish() + } + } + + fun updatePolicy(item: PolicyRvItem, policy: Int) { + val items = itemsPolicies.filter { it.item.uid == item.item.uid } + fun updateState() { + viewModelScope.launch { + val res = if (policy >= SuPolicy.ALLOW) R.string.su_snack_grant else R.string.su_snack_deny + item.item.policy = policy + db.update(item.item) + items.forEach { + it.notifyPropertyChanged(BR.enabled) + it.notifyPropertyChanged(BR.sliderValue) + } + SnackbarEvent(res.asText(item.appName)).publish() + } + } + + if (Config.suAuth) { + AuthEvent { updateState() }.publish() + } else { + updateState() + } + } +} diff --git a/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/surequest/SuRequestActivity.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/surequest/SuRequestActivity.kt new file mode 100644 index 000000000..9e04c0f53 --- /dev/null +++ b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/surequest/SuRequestActivity.kt @@ -0,0 +1,69 @@ +package com.topjohnwu.magisk.ui.surequest + +import android.content.Intent +import android.content.pm.ActivityInfo +import android.content.res.Resources +import android.os.Build +import android.os.Bundle +import android.view.Window +import android.view.WindowManager +import androidx.lifecycle.lifecycleScope +import com.topjohnwu.magisk.R +import com.topjohnwu.magisk.arch.UIActivity +import com.topjohnwu.magisk.arch.viewModel +import com.topjohnwu.magisk.core.base.UntrackedActivity +import com.topjohnwu.magisk.core.su.SuCallbackHandler +import com.topjohnwu.magisk.core.su.SuCallbackHandler.REQUEST +import com.topjohnwu.magisk.databinding.ActivityRequestBinding +import com.topjohnwu.magisk.ui.theme.Theme +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext + +open class SuRequestActivity : UIActivity(), UntrackedActivity { + + override val layoutRes: Int = R.layout.activity_request + override val viewModel: SuRequestViewModel by viewModel() + + override fun onCreate(savedInstanceState: Bundle?) { + supportRequestWindowFeature(Window.FEATURE_NO_TITLE) + requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LOCKED + window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) + window.addFlags(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + window.setHideOverlayWindows(true) + } + setTheme(Theme.selected.themeRes) + super.onCreate(savedInstanceState) + + if (intent.action == Intent.ACTION_VIEW) { + val action = intent.getStringExtra("action") + if (action == REQUEST) { + viewModel.handleRequest(intent) + } else { + lifecycleScope.launch { + withContext(Dispatchers.IO) { + SuCallbackHandler.run(this@SuRequestActivity, action, intent.extras) + } + finish() + } + } + } else { + finish() + } + } + + override fun getTheme(): Resources.Theme { + val theme = super.getTheme() + theme.applyStyle(R.style.Foundation_Floating, true) + return theme + } + + override fun onBackPressed() { + viewModel.denyPressed() + } + + override fun finish() { + super.finishAndRemoveTask() + } +} diff --git a/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/surequest/SuRequestViewModel.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/surequest/SuRequestViewModel.kt new file mode 100644 index 000000000..ed7be09b4 --- /dev/null +++ b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/surequest/SuRequestViewModel.kt @@ -0,0 +1,199 @@ +package com.topjohnwu.magisk.ui.surequest + +import android.annotation.SuppressLint +import android.content.Intent +import android.content.SharedPreferences +import android.content.res.Resources +import android.graphics.drawable.Drawable +import android.os.Bundle +import android.os.CountDownTimer +import android.view.MotionEvent +import android.view.View +import android.view.ViewGroup +import android.view.accessibility.AccessibilityEvent +import android.view.accessibility.AccessibilityNodeInfo +import android.view.accessibility.AccessibilityNodeProvider +import android.widget.Toast +import androidx.databinding.Bindable +import androidx.lifecycle.viewModelScope +import com.topjohnwu.magisk.BR +import com.topjohnwu.magisk.arch.BaseViewModel +import com.topjohnwu.magisk.core.AppContext +import com.topjohnwu.magisk.core.Config +import com.topjohnwu.magisk.core.R +import com.topjohnwu.magisk.core.data.magiskdb.PolicyDao +import com.topjohnwu.magisk.core.ktx.getLabel +import com.topjohnwu.magisk.core.ktx.toast +import com.topjohnwu.magisk.core.model.su.SuPolicy.Companion.ALLOW +import com.topjohnwu.magisk.core.model.su.SuPolicy.Companion.DENY +import com.topjohnwu.magisk.core.su.SuRequestHandler +import com.topjohnwu.magisk.core.utils.TextHolder +import com.topjohnwu.magisk.databinding.set +import com.topjohnwu.magisk.events.AuthEvent +import com.topjohnwu.magisk.events.DieEvent +import com.topjohnwu.magisk.events.ShowUIEvent +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import java.util.concurrent.TimeUnit.SECONDS + +class SuRequestViewModel( + policyDB: PolicyDao, + private val timeoutPrefs: SharedPreferences +) : BaseViewModel() { + + lateinit var icon: Drawable + lateinit var title: String + lateinit var packageName: String + + @get:Bindable + val denyText = DenyText() + + @get:Bindable + var selectedItemPosition = 0 + set(value) = set(value, field, { field = it }, BR.selectedItemPosition) + + @get:Bindable + var grantEnabled = false + set(value) = set(value, field, { field = it }, BR.grantEnabled) + + @SuppressLint("ClickableViewAccessibility") + val grantTouchListener = View.OnTouchListener { _: View, event: MotionEvent -> + // Filter obscured touches by consuming them. + if (event.flags and MotionEvent.FLAG_WINDOW_IS_OBSCURED != 0 + || event.flags and MotionEvent.FLAG_WINDOW_IS_PARTIALLY_OBSCURED != 0) { + if (event.action == MotionEvent.ACTION_UP) { + AppContext.toast(R.string.touch_filtered_warning, Toast.LENGTH_SHORT) + } + return@OnTouchListener Config.suTapjack + } + false + } + + private val handler = SuRequestHandler(AppContext.packageManager, policyDB) + private val millis = SECONDS.toMillis(Config.suDefaultTimeout.toLong()) + private var timer = SuTimer(millis, 1000) + private var initialized = false + + fun grantPressed() { + cancelTimer() + if (Config.suAuth) { + AuthEvent { respond(ALLOW) }.publish() + } else { + respond(ALLOW) + } + } + + fun denyPressed() { + respond(DENY) + } + + fun spinnerTouched(): Boolean { + cancelTimer() + return false + } + + fun handleRequest(intent: Intent) { + viewModelScope.launch(Dispatchers.Default) { + if (handler.start(intent)) + showDialog() + else + DieEvent().publish() + } + } + + private fun showDialog() { + val pm = handler.pm + val info = handler.pkgInfo + val app = info.applicationInfo + + if (app == null) { + // The request is not coming from an app process, and the UID is a + // shared UID. We have no way to know where this request comes from. + icon = pm.defaultActivityIcon + title = "[SharedUID] ${info.sharedUserId}" + packageName = info.sharedUserId.toString() + } else { + val prefix = if (info.sharedUserId == null) "" else "[SharedUID] " + icon = app.loadIcon(pm) + title = "$prefix${app.getLabel(pm)}" + packageName = info.packageName + } + + selectedItemPosition = timeoutPrefs.getInt(packageName, 0) + + // Set timer + timer.start() + + // Actually show the UI + ShowUIEvent(if (Config.suTapjack) EmptyAccessibilityDelegate else null).publish() + initialized = true + } + + private fun respond(action: Int) { + if (!initialized) { + // ignore the response until showDialog done + return + } + + timer.cancel() + + val pos = selectedItemPosition + timeoutPrefs.edit().putInt(packageName, pos).apply() + + viewModelScope.launch { + handler.respond(action, Config.Value.TIMEOUT_LIST[pos]) + // Kill activity after response + DieEvent().publish() + } + } + + private fun cancelTimer() { + timer.cancel() + denyText.seconds = 0 + } + + private inner class SuTimer( + private val millis: Long, + interval: Long + ) : CountDownTimer(millis, interval) { + + override fun onTick(remains: Long) { + if (!grantEnabled && remains <= millis - 1000) { + grantEnabled = true + } + denyText.seconds = (remains / 1000).toInt() + 1 + } + + override fun onFinish() { + denyText.seconds = 0 + respond(DENY) + } + + } + + inner class DenyText : TextHolder() { + var seconds = 0 + set(value) = set(value, field, { field = it }, BR.denyText) + + override fun getText(resources: Resources): String { + return if (seconds != 0) + "${resources.getString(R.string.deny)} ($seconds)" + else + resources.getString(R.string.deny) + } + } + + // Invisible for accessibility services + object EmptyAccessibilityDelegate : View.AccessibilityDelegate() { + override fun sendAccessibilityEvent(host: View, eventType: Int) {} + override fun performAccessibilityAction(host: View, action: Int, args: Bundle?) = true + override fun sendAccessibilityEventUnchecked(host: View, event: AccessibilityEvent) {} + override fun dispatchPopulateAccessibilityEvent(host: View, event: AccessibilityEvent) = true + override fun onPopulateAccessibilityEvent(host: View, event: AccessibilityEvent) {} + override fun onInitializeAccessibilityEvent(host: View, event: AccessibilityEvent) {} + override fun onInitializeAccessibilityNodeInfo(host: View, info: AccessibilityNodeInfo) {} + override fun addExtraDataToAccessibilityNodeInfo(host: View, info: AccessibilityNodeInfo, extraDataKey: String, arguments: Bundle?) {} + override fun onRequestSendAccessibilityEvent(host: ViewGroup, child: View, event: AccessibilityEvent): Boolean = false + override fun getAccessibilityNodeProvider(host: View): AccessibilityNodeProvider? = null + } +} diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/theme/Theme.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/theme/Theme.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/ui/theme/Theme.kt rename to app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/theme/Theme.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/theme/ThemeFragment.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/theme/ThemeFragment.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/ui/theme/ThemeFragment.kt rename to app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/theme/ThemeFragment.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/theme/ThemeViewModel.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/theme/ThemeViewModel.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/ui/theme/ThemeViewModel.kt rename to app/apk-legacy/src/main/java/com/topjohnwu/magisk/ui/theme/ThemeViewModel.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/utils/AccessibilityUtils.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/utils/AccessibilityUtils.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/utils/AccessibilityUtils.kt rename to app/apk-legacy/src/main/java/com/topjohnwu/magisk/utils/AccessibilityUtils.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/utils/MotionRevealHelper.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/utils/MotionRevealHelper.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/utils/MotionRevealHelper.kt rename to app/apk-legacy/src/main/java/com/topjohnwu/magisk/utils/MotionRevealHelper.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/view/MagiskDialog.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/view/MagiskDialog.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/view/MagiskDialog.kt rename to app/apk-legacy/src/main/java/com/topjohnwu/magisk/view/MagiskDialog.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/view/TappableHeadlineItem.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/view/TappableHeadlineItem.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/view/TappableHeadlineItem.kt rename to app/apk-legacy/src/main/java/com/topjohnwu/magisk/view/TappableHeadlineItem.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/view/TextItem.kt b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/view/TextItem.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/view/TextItem.kt rename to app/apk-legacy/src/main/java/com/topjohnwu/magisk/view/TextItem.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/widget/ConcealableBottomNavigationView.java b/app/apk-legacy/src/main/java/com/topjohnwu/magisk/widget/ConcealableBottomNavigationView.java similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/widget/ConcealableBottomNavigationView.java rename to app/apk-legacy/src/main/java/com/topjohnwu/magisk/widget/ConcealableBottomNavigationView.java diff --git a/app/apk/src/main/res/anim/fragment_enter.xml b/app/apk-legacy/src/main/res/anim/fragment_enter.xml similarity index 100% rename from app/apk/src/main/res/anim/fragment_enter.xml rename to app/apk-legacy/src/main/res/anim/fragment_enter.xml diff --git a/app/apk/src/main/res/anim/fragment_enter_pop.xml b/app/apk-legacy/src/main/res/anim/fragment_enter_pop.xml similarity index 100% rename from app/apk/src/main/res/anim/fragment_enter_pop.xml rename to app/apk-legacy/src/main/res/anim/fragment_enter_pop.xml diff --git a/app/apk/src/main/res/anim/fragment_exit.xml b/app/apk-legacy/src/main/res/anim/fragment_exit.xml similarity index 100% rename from app/apk/src/main/res/anim/fragment_exit.xml rename to app/apk-legacy/src/main/res/anim/fragment_exit.xml diff --git a/app/apk/src/main/res/anim/fragment_exit_pop.xml b/app/apk-legacy/src/main/res/anim/fragment_exit_pop.xml similarity index 100% rename from app/apk/src/main/res/anim/fragment_exit_pop.xml rename to app/apk-legacy/src/main/res/anim/fragment_exit_pop.xml diff --git a/app/apk/src/main/res/color/color_card_background_color_selector.xml b/app/apk-legacy/src/main/res/color/color_card_background_color_selector.xml similarity index 100% rename from app/apk/src/main/res/color/color_card_background_color_selector.xml rename to app/apk-legacy/src/main/res/color/color_card_background_color_selector.xml diff --git a/app/apk/src/main/res/color/color_error_transient.xml b/app/apk-legacy/src/main/res/color/color_error_transient.xml similarity index 100% rename from app/apk/src/main/res/color/color_error_transient.xml rename to app/apk-legacy/src/main/res/color/color_error_transient.xml diff --git a/app/apk/src/main/res/color/color_menu_tint.xml b/app/apk-legacy/src/main/res/color/color_menu_tint.xml similarity index 100% rename from app/apk/src/main/res/color/color_menu_tint.xml rename to app/apk-legacy/src/main/res/color/color_menu_tint.xml diff --git a/app/apk/src/main/res/color/color_on_primary_transient.xml b/app/apk-legacy/src/main/res/color/color_on_primary_transient.xml similarity index 100% rename from app/apk/src/main/res/color/color_on_primary_transient.xml rename to app/apk-legacy/src/main/res/color/color_on_primary_transient.xml diff --git a/app/apk/src/main/res/color/color_primary_error_transient.xml b/app/apk-legacy/src/main/res/color/color_primary_error_transient.xml similarity index 100% rename from app/apk/src/main/res/color/color_primary_error_transient.xml rename to app/apk-legacy/src/main/res/color/color_primary_error_transient.xml diff --git a/app/apk/src/main/res/color/color_primary_transient.xml b/app/apk-legacy/src/main/res/color/color_primary_transient.xml similarity index 100% rename from app/apk/src/main/res/color/color_primary_transient.xml rename to app/apk-legacy/src/main/res/color/color_primary_transient.xml diff --git a/app/apk/src/main/res/color/color_state_primary_transient.xml b/app/apk-legacy/src/main/res/color/color_state_primary_transient.xml similarity index 100% rename from app/apk/src/main/res/color/color_state_primary_transient.xml rename to app/apk-legacy/src/main/res/color/color_state_primary_transient.xml diff --git a/app/apk/src/main/res/color/color_text_transient.xml b/app/apk-legacy/src/main/res/color/color_text_transient.xml similarity index 100% rename from app/apk/src/main/res/color/color_text_transient.xml rename to app/apk-legacy/src/main/res/color/color_text_transient.xml diff --git a/app/apk/src/main/res/drawable/avd_bug_from_filled.xml b/app/apk-legacy/src/main/res/drawable/avd_bug_from_filled.xml similarity index 100% rename from app/apk/src/main/res/drawable/avd_bug_from_filled.xml rename to app/apk-legacy/src/main/res/drawable/avd_bug_from_filled.xml diff --git a/app/apk/src/main/res/drawable/avd_bug_to_filled.xml b/app/apk-legacy/src/main/res/drawable/avd_bug_to_filled.xml similarity index 100% rename from app/apk/src/main/res/drawable/avd_bug_to_filled.xml rename to app/apk-legacy/src/main/res/drawable/avd_bug_to_filled.xml diff --git a/app/apk/src/main/res/drawable/avd_circle_check_from_filled.xml b/app/apk-legacy/src/main/res/drawable/avd_circle_check_from_filled.xml similarity index 100% rename from app/apk/src/main/res/drawable/avd_circle_check_from_filled.xml rename to app/apk-legacy/src/main/res/drawable/avd_circle_check_from_filled.xml diff --git a/app/apk/src/main/res/drawable/avd_circle_check_to_filled.xml b/app/apk-legacy/src/main/res/drawable/avd_circle_check_to_filled.xml similarity index 100% rename from app/apk/src/main/res/drawable/avd_circle_check_to_filled.xml rename to app/apk-legacy/src/main/res/drawable/avd_circle_check_to_filled.xml diff --git a/app/apk/src/main/res/drawable/avd_home_from_filled.xml b/app/apk-legacy/src/main/res/drawable/avd_home_from_filled.xml similarity index 100% rename from app/apk/src/main/res/drawable/avd_home_from_filled.xml rename to app/apk-legacy/src/main/res/drawable/avd_home_from_filled.xml diff --git a/app/apk/src/main/res/drawable/avd_home_to_filled.xml b/app/apk-legacy/src/main/res/drawable/avd_home_to_filled.xml similarity index 100% rename from app/apk/src/main/res/drawable/avd_home_to_filled.xml rename to app/apk-legacy/src/main/res/drawable/avd_home_to_filled.xml diff --git a/app/apk/src/main/res/drawable/avd_module_from_filled.xml b/app/apk-legacy/src/main/res/drawable/avd_module_from_filled.xml similarity index 100% rename from app/apk/src/main/res/drawable/avd_module_from_filled.xml rename to app/apk-legacy/src/main/res/drawable/avd_module_from_filled.xml diff --git a/app/apk/src/main/res/drawable/avd_module_to_filled.xml b/app/apk-legacy/src/main/res/drawable/avd_module_to_filled.xml similarity index 100% rename from app/apk/src/main/res/drawable/avd_module_to_filled.xml rename to app/apk-legacy/src/main/res/drawable/avd_module_to_filled.xml diff --git a/app/apk/src/main/res/drawable/avd_settings_from_filled.xml b/app/apk-legacy/src/main/res/drawable/avd_settings_from_filled.xml similarity index 100% rename from app/apk/src/main/res/drawable/avd_settings_from_filled.xml rename to app/apk-legacy/src/main/res/drawable/avd_settings_from_filled.xml diff --git a/app/apk/src/main/res/drawable/avd_settings_to_filled.xml b/app/apk-legacy/src/main/res/drawable/avd_settings_to_filled.xml similarity index 100% rename from app/apk/src/main/res/drawable/avd_settings_to_filled.xml rename to app/apk-legacy/src/main/res/drawable/avd_settings_to_filled.xml diff --git a/app/apk/src/main/res/drawable/avd_superuser_from_filled.xml b/app/apk-legacy/src/main/res/drawable/avd_superuser_from_filled.xml similarity index 100% rename from app/apk/src/main/res/drawable/avd_superuser_from_filled.xml rename to app/apk-legacy/src/main/res/drawable/avd_superuser_from_filled.xml diff --git a/app/apk/src/main/res/drawable/avd_superuser_to_filled.xml b/app/apk-legacy/src/main/res/drawable/avd_superuser_to_filled.xml similarity index 100% rename from app/apk/src/main/res/drawable/avd_superuser_to_filled.xml rename to app/apk-legacy/src/main/res/drawable/avd_superuser_to_filled.xml diff --git a/app/apk/src/main/res/drawable/bg_line_bottom_rounded.xml b/app/apk-legacy/src/main/res/drawable/bg_line_bottom_rounded.xml similarity index 100% rename from app/apk/src/main/res/drawable/bg_line_bottom_rounded.xml rename to app/apk-legacy/src/main/res/drawable/bg_line_bottom_rounded.xml diff --git a/app/apk/src/main/res/drawable/bg_line_top_rounded.xml b/app/apk-legacy/src/main/res/drawable/bg_line_top_rounded.xml similarity index 100% rename from app/apk/src/main/res/drawable/bg_line_top_rounded.xml rename to app/apk-legacy/src/main/res/drawable/bg_line_top_rounded.xml diff --git a/app/apk/src/main/res/drawable/bg_selection_circle_green.xml b/app/apk-legacy/src/main/res/drawable/bg_selection_circle_green.xml similarity index 100% rename from app/apk/src/main/res/drawable/bg_selection_circle_green.xml rename to app/apk-legacy/src/main/res/drawable/bg_selection_circle_green.xml diff --git a/app/apk/src/main/res/drawable/ic_action_md2.xml b/app/apk-legacy/src/main/res/drawable/ic_action_md2.xml similarity index 100% rename from app/apk/src/main/res/drawable/ic_action_md2.xml rename to app/apk-legacy/src/main/res/drawable/ic_action_md2.xml diff --git a/app/apk/src/main/res/drawable/ic_back_md2.xml b/app/apk-legacy/src/main/res/drawable/ic_back_md2.xml similarity index 100% rename from app/apk/src/main/res/drawable/ic_back_md2.xml rename to app/apk-legacy/src/main/res/drawable/ic_back_md2.xml diff --git a/app/apk/src/main/res/drawable/ic_bug_filled_md2.xml b/app/apk-legacy/src/main/res/drawable/ic_bug_filled_md2.xml similarity index 100% rename from app/apk/src/main/res/drawable/ic_bug_filled_md2.xml rename to app/apk-legacy/src/main/res/drawable/ic_bug_filled_md2.xml diff --git a/app/apk/src/main/res/drawable/ic_bug_md2.xml b/app/apk-legacy/src/main/res/drawable/ic_bug_md2.xml similarity index 100% rename from app/apk/src/main/res/drawable/ic_bug_md2.xml rename to app/apk-legacy/src/main/res/drawable/ic_bug_md2.xml diff --git a/app/apk/src/main/res/drawable/ic_bug_outlined_md2.xml b/app/apk-legacy/src/main/res/drawable/ic_bug_outlined_md2.xml similarity index 100% rename from app/apk/src/main/res/drawable/ic_bug_outlined_md2.xml rename to app/apk-legacy/src/main/res/drawable/ic_bug_outlined_md2.xml diff --git a/app/apk/src/main/res/drawable/ic_check_circle_checked_md2.xml b/app/apk-legacy/src/main/res/drawable/ic_check_circle_checked_md2.xml similarity index 100% rename from app/apk/src/main/res/drawable/ic_check_circle_checked_md2.xml rename to app/apk-legacy/src/main/res/drawable/ic_check_circle_checked_md2.xml diff --git a/app/apk/src/main/res/drawable/ic_check_circle_md2.xml b/app/apk-legacy/src/main/res/drawable/ic_check_circle_md2.xml similarity index 100% rename from app/apk/src/main/res/drawable/ic_check_circle_md2.xml rename to app/apk-legacy/src/main/res/drawable/ic_check_circle_md2.xml diff --git a/app/apk/src/main/res/drawable/ic_check_circle_unchecked_md2.xml b/app/apk-legacy/src/main/res/drawable/ic_check_circle_unchecked_md2.xml similarity index 100% rename from app/apk/src/main/res/drawable/ic_check_circle_unchecked_md2.xml rename to app/apk-legacy/src/main/res/drawable/ic_check_circle_unchecked_md2.xml diff --git a/app/apk/src/main/res/drawable/ic_check_md2.xml b/app/apk-legacy/src/main/res/drawable/ic_check_md2.xml similarity index 100% rename from app/apk/src/main/res/drawable/ic_check_md2.xml rename to app/apk-legacy/src/main/res/drawable/ic_check_md2.xml diff --git a/app/apk/src/main/res/drawable/ic_close_md2.xml b/app/apk-legacy/src/main/res/drawable/ic_close_md2.xml similarity index 100% rename from app/apk/src/main/res/drawable/ic_close_md2.xml rename to app/apk-legacy/src/main/res/drawable/ic_close_md2.xml diff --git a/app/apk/src/main/res/drawable/ic_day.xml b/app/apk-legacy/src/main/res/drawable/ic_day.xml similarity index 100% rename from app/apk/src/main/res/drawable/ic_day.xml rename to app/apk-legacy/src/main/res/drawable/ic_day.xml diff --git a/app/apk/src/main/res/drawable/ic_day_night.xml b/app/apk-legacy/src/main/res/drawable/ic_day_night.xml similarity index 100% rename from app/apk/src/main/res/drawable/ic_day_night.xml rename to app/apk-legacy/src/main/res/drawable/ic_day_night.xml diff --git a/app/apk/src/main/res/drawable/ic_delete_md2.xml b/app/apk-legacy/src/main/res/drawable/ic_delete_md2.xml similarity index 100% rename from app/apk/src/main/res/drawable/ic_delete_md2.xml rename to app/apk-legacy/src/main/res/drawable/ic_delete_md2.xml diff --git a/app/apk/src/main/res/drawable/ic_download_md2.xml b/app/apk-legacy/src/main/res/drawable/ic_download_md2.xml similarity index 100% rename from app/apk/src/main/res/drawable/ic_download_md2.xml rename to app/apk-legacy/src/main/res/drawable/ic_download_md2.xml diff --git a/app/apk/src/main/res/drawable/ic_folder_list.xml b/app/apk-legacy/src/main/res/drawable/ic_folder_list.xml similarity index 100% rename from app/apk/src/main/res/drawable/ic_folder_list.xml rename to app/apk-legacy/src/main/res/drawable/ic_folder_list.xml diff --git a/app/apk/src/main/res/drawable/ic_forth_md2.xml b/app/apk-legacy/src/main/res/drawable/ic_forth_md2.xml similarity index 100% rename from app/apk/src/main/res/drawable/ic_forth_md2.xml rename to app/apk-legacy/src/main/res/drawable/ic_forth_md2.xml diff --git a/app/apk/src/main/res/drawable/ic_home_filled_md2.xml b/app/apk-legacy/src/main/res/drawable/ic_home_filled_md2.xml similarity index 100% rename from app/apk/src/main/res/drawable/ic_home_filled_md2.xml rename to app/apk-legacy/src/main/res/drawable/ic_home_filled_md2.xml diff --git a/app/apk/src/main/res/drawable/ic_home_md2.xml b/app/apk-legacy/src/main/res/drawable/ic_home_md2.xml similarity index 100% rename from app/apk/src/main/res/drawable/ic_home_md2.xml rename to app/apk-legacy/src/main/res/drawable/ic_home_md2.xml diff --git a/app/apk/src/main/res/drawable/ic_home_outlined_md2.xml b/app/apk-legacy/src/main/res/drawable/ic_home_outlined_md2.xml similarity index 100% rename from app/apk/src/main/res/drawable/ic_home_outlined_md2.xml rename to app/apk-legacy/src/main/res/drawable/ic_home_outlined_md2.xml diff --git a/app/apk/src/main/res/drawable/ic_install.xml b/app/apk-legacy/src/main/res/drawable/ic_install.xml similarity index 100% rename from app/apk/src/main/res/drawable/ic_install.xml rename to app/apk-legacy/src/main/res/drawable/ic_install.xml diff --git a/app/apk-ng/src/main/res/drawable/ic_manager.xml b/app/apk-legacy/src/main/res/drawable/ic_manager.xml similarity index 96% rename from app/apk-ng/src/main/res/drawable/ic_manager.xml rename to app/apk-legacy/src/main/res/drawable/ic_manager.xml index 3a918c5f1..001df45e3 100644 --- a/app/apk-ng/src/main/res/drawable/ic_manager.xml +++ b/app/apk-legacy/src/main/res/drawable/ic_manager.xml @@ -4,6 +4,6 @@ android:viewportWidth="24" android:viewportHeight="24"> diff --git a/app/apk/src/main/res/drawable/ic_module_filled_md2.xml b/app/apk-legacy/src/main/res/drawable/ic_module_filled_md2.xml similarity index 100% rename from app/apk/src/main/res/drawable/ic_module_filled_md2.xml rename to app/apk-legacy/src/main/res/drawable/ic_module_filled_md2.xml diff --git a/app/apk/src/main/res/drawable/ic_module_md2.xml b/app/apk-legacy/src/main/res/drawable/ic_module_md2.xml similarity index 100% rename from app/apk/src/main/res/drawable/ic_module_md2.xml rename to app/apk-legacy/src/main/res/drawable/ic_module_md2.xml diff --git a/app/apk/src/main/res/drawable/ic_module_outlined_md2.xml b/app/apk-legacy/src/main/res/drawable/ic_module_outlined_md2.xml similarity index 100% rename from app/apk/src/main/res/drawable/ic_module_outlined_md2.xml rename to app/apk-legacy/src/main/res/drawable/ic_module_outlined_md2.xml diff --git a/app/apk/src/main/res/drawable/ic_module_storage_md2.xml b/app/apk-legacy/src/main/res/drawable/ic_module_storage_md2.xml similarity index 100% rename from app/apk/src/main/res/drawable/ic_module_storage_md2.xml rename to app/apk-legacy/src/main/res/drawable/ic_module_storage_md2.xml diff --git a/app/apk/src/main/res/drawable/ic_night.xml b/app/apk-legacy/src/main/res/drawable/ic_night.xml similarity index 100% rename from app/apk/src/main/res/drawable/ic_night.xml rename to app/apk-legacy/src/main/res/drawable/ic_night.xml diff --git a/app/apk/src/main/res/drawable/ic_notifications_md2.xml b/app/apk-legacy/src/main/res/drawable/ic_notifications_md2.xml similarity index 100% rename from app/apk/src/main/res/drawable/ic_notifications_md2.xml rename to app/apk-legacy/src/main/res/drawable/ic_notifications_md2.xml diff --git a/app/apk/src/main/res/drawable/ic_paint.xml b/app/apk-legacy/src/main/res/drawable/ic_paint.xml similarity index 100% rename from app/apk/src/main/res/drawable/ic_paint.xml rename to app/apk-legacy/src/main/res/drawable/ic_paint.xml diff --git a/app/apk-ng/src/main/res/drawable/ic_restart.xml b/app/apk-legacy/src/main/res/drawable/ic_restart.xml similarity index 93% rename from app/apk-ng/src/main/res/drawable/ic_restart.xml rename to app/apk-legacy/src/main/res/drawable/ic_restart.xml index 3151a7b21..b4f8eaee9 100644 --- a/app/apk-ng/src/main/res/drawable/ic_restart.xml +++ b/app/apk-legacy/src/main/res/drawable/ic_restart.xml @@ -5,6 +5,6 @@ android:viewportWidth="24" android:viewportHeight="24"> diff --git a/app/apk/src/main/res/drawable/ic_save_md2.xml b/app/apk-legacy/src/main/res/drawable/ic_save_md2.xml similarity index 100% rename from app/apk/src/main/res/drawable/ic_save_md2.xml rename to app/apk-legacy/src/main/res/drawable/ic_save_md2.xml diff --git a/app/apk/src/main/res/drawable/ic_search_md2.xml b/app/apk-legacy/src/main/res/drawable/ic_search_md2.xml similarity index 100% rename from app/apk/src/main/res/drawable/ic_search_md2.xml rename to app/apk-legacy/src/main/res/drawable/ic_search_md2.xml diff --git a/app/apk/src/main/res/drawable/ic_settings_filled_md2.xml b/app/apk-legacy/src/main/res/drawable/ic_settings_filled_md2.xml similarity index 100% rename from app/apk/src/main/res/drawable/ic_settings_filled_md2.xml rename to app/apk-legacy/src/main/res/drawable/ic_settings_filled_md2.xml diff --git a/app/apk/src/main/res/drawable/ic_settings_md2.xml b/app/apk-legacy/src/main/res/drawable/ic_settings_md2.xml similarity index 100% rename from app/apk/src/main/res/drawable/ic_settings_md2.xml rename to app/apk-legacy/src/main/res/drawable/ic_settings_md2.xml diff --git a/app/apk/src/main/res/drawable/ic_settings_outlined_md2.xml b/app/apk-legacy/src/main/res/drawable/ic_settings_outlined_md2.xml similarity index 100% rename from app/apk/src/main/res/drawable/ic_settings_outlined_md2.xml rename to app/apk-legacy/src/main/res/drawable/ic_settings_outlined_md2.xml diff --git a/app/apk/src/main/res/drawable/ic_superuser_filled_md2.xml b/app/apk-legacy/src/main/res/drawable/ic_superuser_filled_md2.xml similarity index 100% rename from app/apk/src/main/res/drawable/ic_superuser_filled_md2.xml rename to app/apk-legacy/src/main/res/drawable/ic_superuser_filled_md2.xml diff --git a/app/apk/src/main/res/drawable/ic_superuser_md2.xml b/app/apk-legacy/src/main/res/drawable/ic_superuser_md2.xml similarity index 100% rename from app/apk/src/main/res/drawable/ic_superuser_md2.xml rename to app/apk-legacy/src/main/res/drawable/ic_superuser_md2.xml diff --git a/app/apk/src/main/res/drawable/ic_superuser_outlined_md2.xml b/app/apk-legacy/src/main/res/drawable/ic_superuser_outlined_md2.xml similarity index 100% rename from app/apk/src/main/res/drawable/ic_superuser_outlined_md2.xml rename to app/apk-legacy/src/main/res/drawable/ic_superuser_outlined_md2.xml diff --git a/app/apk/src/main/res/drawable/ic_update_md2.xml b/app/apk-legacy/src/main/res/drawable/ic_update_md2.xml similarity index 100% rename from app/apk/src/main/res/drawable/ic_update_md2.xml rename to app/apk-legacy/src/main/res/drawable/ic_update_md2.xml diff --git a/app/apk/src/main/res/layout/activity_main_md2.xml b/app/apk-legacy/src/main/res/layout/activity_main_md2.xml similarity index 100% rename from app/apk/src/main/res/layout/activity_main_md2.xml rename to app/apk-legacy/src/main/res/layout/activity_main_md2.xml diff --git a/app/apk/src/main/res/layout/activity_request.xml b/app/apk-legacy/src/main/res/layout/activity_request.xml similarity index 100% rename from app/apk/src/main/res/layout/activity_request.xml rename to app/apk-legacy/src/main/res/layout/activity_request.xml diff --git a/app/apk/src/main/res/layout/dialog_magisk_base.xml b/app/apk-legacy/src/main/res/layout/dialog_magisk_base.xml similarity index 100% rename from app/apk/src/main/res/layout/dialog_magisk_base.xml rename to app/apk-legacy/src/main/res/layout/dialog_magisk_base.xml diff --git a/app/apk/src/main/res/layout/dialog_settings_app_name.xml b/app/apk-legacy/src/main/res/layout/dialog_settings_app_name.xml similarity index 100% rename from app/apk/src/main/res/layout/dialog_settings_app_name.xml rename to app/apk-legacy/src/main/res/layout/dialog_settings_app_name.xml diff --git a/app/apk/src/main/res/layout/dialog_settings_download_path.xml b/app/apk-legacy/src/main/res/layout/dialog_settings_download_path.xml similarity index 100% rename from app/apk/src/main/res/layout/dialog_settings_download_path.xml rename to app/apk-legacy/src/main/res/layout/dialog_settings_download_path.xml diff --git a/app/apk/src/main/res/layout/dialog_settings_update_channel.xml b/app/apk-legacy/src/main/res/layout/dialog_settings_update_channel.xml similarity index 100% rename from app/apk/src/main/res/layout/dialog_settings_update_channel.xml rename to app/apk-legacy/src/main/res/layout/dialog_settings_update_channel.xml diff --git a/app/apk/src/main/res/layout/fragment_action_md2.xml b/app/apk-legacy/src/main/res/layout/fragment_action_md2.xml similarity index 100% rename from app/apk/src/main/res/layout/fragment_action_md2.xml rename to app/apk-legacy/src/main/res/layout/fragment_action_md2.xml diff --git a/app/apk/src/main/res/layout/fragment_deny_md2.xml b/app/apk-legacy/src/main/res/layout/fragment_deny_md2.xml similarity index 100% rename from app/apk/src/main/res/layout/fragment_deny_md2.xml rename to app/apk-legacy/src/main/res/layout/fragment_deny_md2.xml diff --git a/app/apk/src/main/res/layout/fragment_flash_md2.xml b/app/apk-legacy/src/main/res/layout/fragment_flash_md2.xml similarity index 100% rename from app/apk/src/main/res/layout/fragment_flash_md2.xml rename to app/apk-legacy/src/main/res/layout/fragment_flash_md2.xml diff --git a/app/apk/src/main/res/layout/fragment_home_md2.xml b/app/apk-legacy/src/main/res/layout/fragment_home_md2.xml similarity index 100% rename from app/apk/src/main/res/layout/fragment_home_md2.xml rename to app/apk-legacy/src/main/res/layout/fragment_home_md2.xml diff --git a/app/apk/src/main/res/layout/fragment_install_md2.xml b/app/apk-legacy/src/main/res/layout/fragment_install_md2.xml similarity index 100% rename from app/apk/src/main/res/layout/fragment_install_md2.xml rename to app/apk-legacy/src/main/res/layout/fragment_install_md2.xml diff --git a/app/apk/src/main/res/layout/fragment_log_md2.xml b/app/apk-legacy/src/main/res/layout/fragment_log_md2.xml similarity index 100% rename from app/apk/src/main/res/layout/fragment_log_md2.xml rename to app/apk-legacy/src/main/res/layout/fragment_log_md2.xml diff --git a/app/apk/src/main/res/layout/fragment_module_md2.xml b/app/apk-legacy/src/main/res/layout/fragment_module_md2.xml similarity index 100% rename from app/apk/src/main/res/layout/fragment_module_md2.xml rename to app/apk-legacy/src/main/res/layout/fragment_module_md2.xml diff --git a/app/apk/src/main/res/layout/fragment_settings_md2.xml b/app/apk-legacy/src/main/res/layout/fragment_settings_md2.xml similarity index 100% rename from app/apk/src/main/res/layout/fragment_settings_md2.xml rename to app/apk-legacy/src/main/res/layout/fragment_settings_md2.xml diff --git a/app/apk/src/main/res/layout/fragment_superuser_md2.xml b/app/apk-legacy/src/main/res/layout/fragment_superuser_md2.xml similarity index 100% rename from app/apk/src/main/res/layout/fragment_superuser_md2.xml rename to app/apk-legacy/src/main/res/layout/fragment_superuser_md2.xml diff --git a/app/apk/src/main/res/layout/fragment_theme_md2.xml b/app/apk-legacy/src/main/res/layout/fragment_theme_md2.xml similarity index 100% rename from app/apk/src/main/res/layout/fragment_theme_md2.xml rename to app/apk-legacy/src/main/res/layout/fragment_theme_md2.xml diff --git a/app/apk/src/main/res/layout/include_home_magisk.xml b/app/apk-legacy/src/main/res/layout/include_home_magisk.xml similarity index 100% rename from app/apk/src/main/res/layout/include_home_magisk.xml rename to app/apk-legacy/src/main/res/layout/include_home_magisk.xml diff --git a/app/apk/src/main/res/layout/include_home_manager.xml b/app/apk-legacy/src/main/res/layout/include_home_manager.xml similarity index 100% rename from app/apk/src/main/res/layout/include_home_manager.xml rename to app/apk-legacy/src/main/res/layout/include_home_manager.xml diff --git a/app/apk/src/main/res/layout/include_log_magisk.xml b/app/apk-legacy/src/main/res/layout/include_log_magisk.xml similarity index 100% rename from app/apk/src/main/res/layout/include_log_magisk.xml rename to app/apk-legacy/src/main/res/layout/include_log_magisk.xml diff --git a/app/apk/src/main/res/layout/include_log_superuser.xml b/app/apk-legacy/src/main/res/layout/include_log_superuser.xml similarity index 100% rename from app/apk/src/main/res/layout/include_log_superuser.xml rename to app/apk-legacy/src/main/res/layout/include_log_superuser.xml diff --git a/app/apk/src/main/res/layout/item_console_md2.xml b/app/apk-legacy/src/main/res/layout/item_console_md2.xml similarity index 100% rename from app/apk/src/main/res/layout/item_console_md2.xml rename to app/apk-legacy/src/main/res/layout/item_console_md2.xml diff --git a/app/apk/src/main/res/layout/item_developer.xml b/app/apk-legacy/src/main/res/layout/item_developer.xml similarity index 100% rename from app/apk/src/main/res/layout/item_developer.xml rename to app/apk-legacy/src/main/res/layout/item_developer.xml diff --git a/app/apk/src/main/res/layout/item_hide_md2.xml b/app/apk-legacy/src/main/res/layout/item_hide_md2.xml similarity index 100% rename from app/apk/src/main/res/layout/item_hide_md2.xml rename to app/apk-legacy/src/main/res/layout/item_hide_md2.xml diff --git a/app/apk/src/main/res/layout/item_hide_process_md2.xml b/app/apk-legacy/src/main/res/layout/item_hide_process_md2.xml similarity index 100% rename from app/apk/src/main/res/layout/item_hide_process_md2.xml rename to app/apk-legacy/src/main/res/layout/item_hide_process_md2.xml diff --git a/app/apk/src/main/res/layout/item_icon_link.xml b/app/apk-legacy/src/main/res/layout/item_icon_link.xml similarity index 100% rename from app/apk/src/main/res/layout/item_icon_link.xml rename to app/apk-legacy/src/main/res/layout/item_icon_link.xml diff --git a/app/apk/src/main/res/layout/item_list_single_line.xml b/app/apk-legacy/src/main/res/layout/item_list_single_line.xml similarity index 100% rename from app/apk/src/main/res/layout/item_list_single_line.xml rename to app/apk-legacy/src/main/res/layout/item_list_single_line.xml diff --git a/app/apk/src/main/res/layout/item_log_access_md2.xml b/app/apk-legacy/src/main/res/layout/item_log_access_md2.xml similarity index 100% rename from app/apk/src/main/res/layout/item_log_access_md2.xml rename to app/apk-legacy/src/main/res/layout/item_log_access_md2.xml diff --git a/app/apk/src/main/res/layout/item_log_textview.xml b/app/apk-legacy/src/main/res/layout/item_log_textview.xml similarity index 100% rename from app/apk/src/main/res/layout/item_log_textview.xml rename to app/apk-legacy/src/main/res/layout/item_log_textview.xml diff --git a/app/apk/src/main/res/layout/item_log_track_md2.xml b/app/apk-legacy/src/main/res/layout/item_log_track_md2.xml similarity index 100% rename from app/apk/src/main/res/layout/item_log_track_md2.xml rename to app/apk-legacy/src/main/res/layout/item_log_track_md2.xml diff --git a/app/apk/src/main/res/layout/item_module_download.xml b/app/apk-legacy/src/main/res/layout/item_module_download.xml similarity index 100% rename from app/apk/src/main/res/layout/item_module_download.xml rename to app/apk-legacy/src/main/res/layout/item_module_download.xml diff --git a/app/apk/src/main/res/layout/item_module_md2.xml b/app/apk-legacy/src/main/res/layout/item_module_md2.xml similarity index 100% rename from app/apk/src/main/res/layout/item_module_md2.xml rename to app/apk-legacy/src/main/res/layout/item_module_md2.xml diff --git a/app/apk/src/main/res/layout/item_policy_md2.xml b/app/apk-legacy/src/main/res/layout/item_policy_md2.xml similarity index 100% rename from app/apk/src/main/res/layout/item_policy_md2.xml rename to app/apk-legacy/src/main/res/layout/item_policy_md2.xml diff --git a/app/apk/src/main/res/layout/item_settings.xml b/app/apk-legacy/src/main/res/layout/item_settings.xml similarity index 100% rename from app/apk/src/main/res/layout/item_settings.xml rename to app/apk-legacy/src/main/res/layout/item_settings.xml diff --git a/app/apk/src/main/res/layout/item_settings_section.xml b/app/apk-legacy/src/main/res/layout/item_settings_section.xml similarity index 100% rename from app/apk/src/main/res/layout/item_settings_section.xml rename to app/apk-legacy/src/main/res/layout/item_settings_section.xml diff --git a/app/apk/src/main/res/layout/item_spinner.xml b/app/apk-legacy/src/main/res/layout/item_spinner.xml similarity index 100% rename from app/apk/src/main/res/layout/item_spinner.xml rename to app/apk-legacy/src/main/res/layout/item_spinner.xml diff --git a/app/apk/src/main/res/layout/item_tappable_headline.xml b/app/apk-legacy/src/main/res/layout/item_tappable_headline.xml similarity index 100% rename from app/apk/src/main/res/layout/item_tappable_headline.xml rename to app/apk-legacy/src/main/res/layout/item_tappable_headline.xml diff --git a/app/apk/src/main/res/layout/item_text.xml b/app/apk-legacy/src/main/res/layout/item_text.xml similarity index 100% rename from app/apk/src/main/res/layout/item_text.xml rename to app/apk-legacy/src/main/res/layout/item_text.xml diff --git a/app/apk/src/main/res/layout/item_theme.xml b/app/apk-legacy/src/main/res/layout/item_theme.xml similarity index 100% rename from app/apk/src/main/res/layout/item_theme.xml rename to app/apk-legacy/src/main/res/layout/item_theme.xml diff --git a/app/apk/src/main/res/layout/item_theme_container.xml b/app/apk-legacy/src/main/res/layout/item_theme_container.xml similarity index 100% rename from app/apk/src/main/res/layout/item_theme_container.xml rename to app/apk-legacy/src/main/res/layout/item_theme_container.xml diff --git a/app/apk/src/main/res/layout/markdown_window_md2.xml b/app/apk-legacy/src/main/res/layout/markdown_window_md2.xml similarity index 100% rename from app/apk/src/main/res/layout/markdown_window_md2.xml rename to app/apk-legacy/src/main/res/layout/markdown_window_md2.xml diff --git a/app/apk/src/main/res/menu/menu_bottom_nav.xml b/app/apk-legacy/src/main/res/menu/menu_bottom_nav.xml similarity index 100% rename from app/apk/src/main/res/menu/menu_bottom_nav.xml rename to app/apk-legacy/src/main/res/menu/menu_bottom_nav.xml diff --git a/app/apk/src/main/res/menu/menu_deny_md2.xml b/app/apk-legacy/src/main/res/menu/menu_deny_md2.xml similarity index 100% rename from app/apk/src/main/res/menu/menu_deny_md2.xml rename to app/apk-legacy/src/main/res/menu/menu_deny_md2.xml diff --git a/app/apk/src/main/res/menu/menu_flash.xml b/app/apk-legacy/src/main/res/menu/menu_flash.xml similarity index 100% rename from app/apk/src/main/res/menu/menu_flash.xml rename to app/apk-legacy/src/main/res/menu/menu_flash.xml diff --git a/app/apk/src/main/res/menu/menu_home_md2.xml b/app/apk-legacy/src/main/res/menu/menu_home_md2.xml similarity index 100% rename from app/apk/src/main/res/menu/menu_home_md2.xml rename to app/apk-legacy/src/main/res/menu/menu_home_md2.xml diff --git a/app/apk/src/main/res/menu/menu_log_md2.xml b/app/apk-legacy/src/main/res/menu/menu_log_md2.xml similarity index 100% rename from app/apk/src/main/res/menu/menu_log_md2.xml rename to app/apk-legacy/src/main/res/menu/menu_log_md2.xml diff --git a/app/apk/src/main/res/menu/menu_reboot.xml b/app/apk-legacy/src/main/res/menu/menu_reboot.xml similarity index 100% rename from app/apk/src/main/res/menu/menu_reboot.xml rename to app/apk-legacy/src/main/res/menu/menu_reboot.xml diff --git a/app/apk/src/main/res/navigation/main.xml b/app/apk-legacy/src/main/res/navigation/main.xml similarity index 100% rename from app/apk/src/main/res/navigation/main.xml rename to app/apk-legacy/src/main/res/navigation/main.xml diff --git a/app/apk/src/main/res/values-night/styles_md2.xml b/app/apk-legacy/src/main/res/values-night/styles_md2.xml similarity index 100% rename from app/apk/src/main/res/values-night/styles_md2.xml rename to app/apk-legacy/src/main/res/values-night/styles_md2.xml diff --git a/app/apk/src/main/res/values-night/themes_md2.xml b/app/apk-legacy/src/main/res/values-night/themes_md2.xml similarity index 100% rename from app/apk/src/main/res/values-night/themes_md2.xml rename to app/apk-legacy/src/main/res/values-night/themes_md2.xml diff --git a/app/apk/src/main/res/values-v27/themes.xml b/app/apk-legacy/src/main/res/values-v27/themes.xml similarity index 100% rename from app/apk/src/main/res/values-v27/themes.xml rename to app/apk-legacy/src/main/res/values-v27/themes.xml diff --git a/app/apk/src/main/res/values/attrs.xml b/app/apk-legacy/src/main/res/values/attrs.xml similarity index 100% rename from app/apk/src/main/res/values/attrs.xml rename to app/apk-legacy/src/main/res/values/attrs.xml diff --git a/app/apk/src/main/res/values/dimens.xml b/app/apk-legacy/src/main/res/values/dimens.xml similarity index 100% rename from app/apk/src/main/res/values/dimens.xml rename to app/apk-legacy/src/main/res/values/dimens.xml diff --git a/app/apk/src/main/res/values/ids.xml b/app/apk-legacy/src/main/res/values/ids.xml similarity index 100% rename from app/apk/src/main/res/values/ids.xml rename to app/apk-legacy/src/main/res/values/ids.xml diff --git a/app/apk/src/main/res/values/styles_md2.xml b/app/apk-legacy/src/main/res/values/styles_md2.xml similarity index 100% rename from app/apk/src/main/res/values/styles_md2.xml rename to app/apk-legacy/src/main/res/values/styles_md2.xml diff --git a/app/apk/src/main/res/values/styles_md2_appearance.xml b/app/apk-legacy/src/main/res/values/styles_md2_appearance.xml similarity index 100% rename from app/apk/src/main/res/values/styles_md2_appearance.xml rename to app/apk-legacy/src/main/res/values/styles_md2_appearance.xml diff --git a/app/apk/src/main/res/values/styles_md2_impl.xml b/app/apk-legacy/src/main/res/values/styles_md2_impl.xml similarity index 100% rename from app/apk/src/main/res/values/styles_md2_impl.xml rename to app/apk-legacy/src/main/res/values/styles_md2_impl.xml diff --git a/app/apk/src/main/res/values/styles_view_md2.xml b/app/apk-legacy/src/main/res/values/styles_view_md2.xml similarity index 100% rename from app/apk/src/main/res/values/styles_view_md2.xml rename to app/apk-legacy/src/main/res/values/styles_view_md2.xml diff --git a/app/apk/src/main/res/values/theme_overlay.xml b/app/apk-legacy/src/main/res/values/theme_overlay.xml similarity index 100% rename from app/apk/src/main/res/values/theme_overlay.xml rename to app/apk-legacy/src/main/res/values/theme_overlay.xml diff --git a/app/apk-legacy/src/main/res/values/themes.xml b/app/apk-legacy/src/main/res/values/themes.xml new file mode 100644 index 000000000..09078e38e --- /dev/null +++ b/app/apk-legacy/src/main/res/values/themes.xml @@ -0,0 +1,32 @@ + + + + + + + + + + - - - - diff --git a/app/apk/build.gradle.kts b/app/apk/build.gradle.kts index 61ebc64d2..015931db3 100644 --- a/app/apk/build.gradle.kts +++ b/app/apk/build.gradle.kts @@ -1,30 +1,26 @@ plugins { alias(libs.plugins.android.application) kotlin("plugin.parcelize") - alias(libs.plugins.legacy.kapt) - alias(libs.plugins.navigation.safeargs) + alias(libs.plugins.compose.compiler) } setupMainApk() -kapt { - correctErrorTypes = true - useBuildCache = true - mapDiagnosticLocations = true - javacOptions { - option("-Xmaxerrs", "1000") - } -} - android { buildFeatures { - dataBinding = true + compose = true } compileOptions { isCoreLibraryDesugaringEnabled = true } + packaging { + jniLibs { + excludes += "lib/*/libandroidx.graphics.path.so" + } + } + defaultConfig { proguardFile("proguard-rules.pro") } @@ -41,22 +37,20 @@ dependencies { implementation(project(":core")) coreLibraryDesugaring(libs.jdk.libs) - implementation(libs.indeterminate.checkbox) - implementation(libs.rikka.layoutinflater) - implementation(libs.rikka.insets) - implementation(libs.rikka.recyclerview) + // Compose + implementation(libs.compose.ui) + implementation(libs.accompanist.drawablepainter) + implementation(libs.compose.ui.tooling.preview) + debugImplementation(libs.compose.ui.tooling) + implementation(libs.compose.material.icons.extended) + implementation(libs.activity.compose) + implementation(libs.lifecycle.runtime.compose) + implementation(libs.lifecycle.viewmodel.compose) + implementation(libs.compose.material3) - implementation(libs.navigation.fragment.ktx) - implementation(libs.navigation.ui.ktx) - - implementation(libs.constraintlayout) - implementation(libs.swiperefreshlayout) - implementation(libs.recyclerview) - implementation(libs.transition) - implementation(libs.fragment.ktx) - implementation(libs.appcompat) - implementation(libs.material) - - // Make sure kapt runs with a proper kotlin-stdlib - kapt(kotlin("stdlib")) + // Navigation3 + implementation(libs.navigation3.runtime) + implementation(libs.navigationevent.compose) + implementation(libs.lifecycle.viewmodel.navigation3) + implementation(libs.navigation3.ui) } diff --git a/app/apk/src/main/AndroidManifest.xml b/app/apk/src/main/AndroidManifest.xml index 63f0dcba6..a55c4e523 100644 --- a/app/apk/src/main/AndroidManifest.xml +++ b/app/apk/src/main/AndroidManifest.xml @@ -2,15 +2,6 @@ - - (extraBufferCapacity = 1) + val navEvents: SharedFlow = _navEvents - private val _viewEvents = MutableLiveData() - val viewEvents: LiveData get() = _viewEvents - - open fun onSaveState(state: Bundle) {} - open fun onRestoreState(state: Bundle) {} - open fun onNetworkChanged(network: Boolean) {} - - fun withPermission(permission: String, callback: (Boolean) -> Unit) { - PermissionEvent(permission, callback).publish() + fun showSnackbar(@StringRes resId: Int) { + AppContext.toast(resId, Toast.LENGTH_SHORT) } - inline fun withExternalRW(crossinline callback: () -> Unit) { - withPermission(WRITE_EXTERNAL_STORAGE) { - if (!it) { - SnackbarEvent(R.string.external_rw_permission_denied).publish() - } else { - callback() - } - } + fun showSnackbar(msg: String) { + AppContext.toast(msg, Toast.LENGTH_SHORT) } - @SuppressLint("InlinedApi") - inline fun withInstallPermission(crossinline callback: () -> Unit) { - withPermission(REQUEST_INSTALL_PACKAGES) { - if (!it) { - SnackbarEvent(R.string.install_unknown_denied).publish() - } else { - callback() - } - } + fun navigateTo(route: Route) { + _navEvents.tryEmit(route) } - - @SuppressLint("InlinedApi") - inline fun withPostNotificationPermission(crossinline callback: () -> Unit) { - withPermission(POST_NOTIFICATIONS) { - if (!it) { - SnackbarEvent(R.string.post_notifications_denied).publish() - } else { - callback() - } - } - } - - fun back() = BackPressEvent().publish() - - fun ViewEvent.publish() { - _viewEvents.postValue(this) - } - - fun DialogBuilder.show() { - DialogEvent(this).publish() - } - - fun NavDirections.navigate(pop: Boolean = false) { - _viewEvents.postValue(NavigationEvent(this, pop)) - } - } diff --git a/app/apk-ng/src/main/java/com/topjohnwu/magisk/arch/ViewModelFactory.kt b/app/apk/src/main/java/com/topjohnwu/magisk/arch/ViewModelFactory.kt similarity index 100% rename from app/apk-ng/src/main/java/com/topjohnwu/magisk/arch/ViewModelFactory.kt rename to app/apk/src/main/java/com/topjohnwu/magisk/arch/ViewModelFactory.kt diff --git a/app/apk-ng/src/main/java/com/topjohnwu/magisk/terminal/TerminalBuffer.kt b/app/apk/src/main/java/com/topjohnwu/magisk/terminal/TerminalBuffer.kt similarity index 100% rename from app/apk-ng/src/main/java/com/topjohnwu/magisk/terminal/TerminalBuffer.kt rename to app/apk/src/main/java/com/topjohnwu/magisk/terminal/TerminalBuffer.kt diff --git a/app/apk-ng/src/main/java/com/topjohnwu/magisk/terminal/TerminalEmulator.kt b/app/apk/src/main/java/com/topjohnwu/magisk/terminal/TerminalEmulator.kt similarity index 100% rename from app/apk-ng/src/main/java/com/topjohnwu/magisk/terminal/TerminalEmulator.kt rename to app/apk/src/main/java/com/topjohnwu/magisk/terminal/TerminalEmulator.kt diff --git a/app/apk-ng/src/main/java/com/topjohnwu/magisk/terminal/TerminalProcess.kt b/app/apk/src/main/java/com/topjohnwu/magisk/terminal/TerminalProcess.kt similarity index 100% rename from app/apk-ng/src/main/java/com/topjohnwu/magisk/terminal/TerminalProcess.kt rename to app/apk/src/main/java/com/topjohnwu/magisk/terminal/TerminalProcess.kt diff --git a/app/apk-ng/src/main/java/com/topjohnwu/magisk/terminal/TerminalRow.kt b/app/apk/src/main/java/com/topjohnwu/magisk/terminal/TerminalRow.kt similarity index 100% rename from app/apk-ng/src/main/java/com/topjohnwu/magisk/terminal/TerminalRow.kt rename to app/apk/src/main/java/com/topjohnwu/magisk/terminal/TerminalRow.kt diff --git a/app/apk-ng/src/main/java/com/topjohnwu/magisk/terminal/TerminalStyle.kt b/app/apk/src/main/java/com/topjohnwu/magisk/terminal/TerminalStyle.kt similarity index 100% rename from app/apk-ng/src/main/java/com/topjohnwu/magisk/terminal/TerminalStyle.kt rename to app/apk/src/main/java/com/topjohnwu/magisk/terminal/TerminalStyle.kt diff --git a/app/apk-ng/src/main/java/com/topjohnwu/magisk/terminal/WcWidth.kt b/app/apk/src/main/java/com/topjohnwu/magisk/terminal/WcWidth.kt similarity index 100% rename from app/apk-ng/src/main/java/com/topjohnwu/magisk/terminal/WcWidth.kt rename to app/apk/src/main/java/com/topjohnwu/magisk/terminal/WcWidth.kt diff --git a/app/apk-ng/src/main/java/com/topjohnwu/magisk/ui/MagiskTheme.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/MagiskTheme.kt similarity index 100% rename from app/apk-ng/src/main/java/com/topjohnwu/magisk/ui/MagiskTheme.kt rename to app/apk/src/main/java/com/topjohnwu/magisk/ui/MagiskTheme.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/MainActivity.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/MainActivity.kt index a277224ca..578e2e256 100644 --- a/app/apk/src/main/java/com/topjohnwu/magisk/ui/MainActivity.kt +++ b/app/apk/src/main/java/com/topjohnwu/magisk/ui/MainActivity.kt @@ -3,71 +3,84 @@ package com.topjohnwu.magisk.ui import android.Manifest import android.Manifest.permission.REQUEST_INSTALL_PACKAGES import android.annotation.SuppressLint +import android.content.Context import android.content.Intent import android.content.pm.ApplicationInfo import android.os.Bundle -import android.view.MenuItem -import android.view.View import android.view.WindowManager import android.widget.Toast +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalResources import androidx.core.content.pm.ShortcutManagerCompat -import androidx.core.view.forEach -import androidx.core.view.isGone -import androidx.core.view.isVisible +import androidx.core.net.toUri +import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.lifecycleScope -import androidx.navigation.NavDirections -import com.topjohnwu.magisk.MainDirections +import androidx.lifecycle.viewmodel.compose.viewModel +import androidx.lifecycle.viewmodel.navigation3.rememberViewModelStoreNavEntryDecorator +import androidx.navigation3.runtime.entryProvider +import androidx.navigation3.runtime.rememberSaveableStateHolderNavEntryDecorator +import androidx.navigation3.ui.NavDisplay import com.topjohnwu.magisk.R -import com.topjohnwu.magisk.arch.BaseViewModel -import com.topjohnwu.magisk.arch.NavigationActivity -import com.topjohnwu.magisk.arch.startAnimations -import com.topjohnwu.magisk.arch.viewModel +import com.topjohnwu.magisk.arch.VMFactory import com.topjohnwu.magisk.core.Config import com.topjohnwu.magisk.core.Const import com.topjohnwu.magisk.core.Info +import com.topjohnwu.magisk.core.base.ActivityExtension import com.topjohnwu.magisk.core.base.SplashController import com.topjohnwu.magisk.core.base.SplashScreenHost import com.topjohnwu.magisk.core.isRunningAsStub import com.topjohnwu.magisk.core.ktx.toast -import com.topjohnwu.magisk.core.model.module.LocalModule import com.topjohnwu.magisk.core.tasks.AppMigration -import com.topjohnwu.magisk.databinding.ActivityMainMd2Binding -import com.topjohnwu.magisk.ui.home.HomeFragmentDirections -import com.topjohnwu.magisk.ui.theme.Theme -import com.topjohnwu.magisk.view.MagiskDialog +import com.topjohnwu.magisk.core.wrap +import com.topjohnwu.magisk.ui.component.rememberConfirmDialog +import com.topjohnwu.magisk.ui.deny.DenyListScreen +import com.topjohnwu.magisk.ui.deny.DenyListViewModel +import com.topjohnwu.magisk.ui.flash.FlashScreen +import com.topjohnwu.magisk.ui.flash.FlashUtils +import com.topjohnwu.magisk.ui.flash.FlashViewModel +import com.topjohnwu.magisk.ui.module.ActionScreen +import com.topjohnwu.magisk.ui.module.ActionViewModel +import com.topjohnwu.magisk.ui.navigation.LocalNavigator +import com.topjohnwu.magisk.ui.navigation.Navigator +import com.topjohnwu.magisk.ui.navigation.Route +import com.topjohnwu.magisk.ui.navigation.rememberNavigator +import com.topjohnwu.magisk.ui.superuser.SuperuserDetailScreen +import com.topjohnwu.magisk.ui.superuser.SuperuserViewModel import com.topjohnwu.magisk.view.Shortcuts +import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.launch import java.io.File import com.topjohnwu.magisk.core.R as CoreR -class MainViewModel : BaseViewModel() +class MainActivity : ComponentActivity(), SplashScreenHost { -class MainActivity : NavigationActivity(), SplashScreenHost { - - override val layoutRes = R.layout.activity_main_md2 - override val viewModel by viewModel() - override val navHostId: Int = R.id.main_nav_host + override val extension = ActivityExtension(this) override val splashController = SplashController(this) - override val snackbarView: View - get() { - val fragmentOverride = currentFragment?.snackbarView - return fragmentOverride ?: super.snackbarView - } - override val snackbarAnchorView: View? - get() { - val fragmentAnchor = currentFragment?.snackbarAnchorView - return when { - fragmentAnchor?.isVisible == true -> fragmentAnchor - binding.mainNavigation.isVisible -> return binding.mainNavigation - else -> null - } - } - private var isRootFragment = true + private val intentState = MutableStateFlow(0) + internal val showInvalidState = MutableStateFlow(false) + internal val showUnsupported = MutableStateFlow>>(emptyList()) + internal val showShortcutPrompt = MutableStateFlow(false) + + override fun attachBaseContext(base: Context) { + super.attachBaseContext(base.wrap()) + } override fun onCreate(savedInstanceState: Bundle?) { - setTheme(Theme.selected.themeRes) + extension.onCreate(savedInstanceState) splashController.preOnCreate() + theme.applyStyle(R.style.Main, true) super.onCreate(savedInstanceState) splashController.onCreate(savedInstanceState) } @@ -77,202 +90,264 @@ class MainActivity : NavigationActivity(), SplashScreenH splashController.onResume() } + override fun onSaveInstanceState(outState: Bundle) { + super.onSaveInstanceState(outState) + extension.onSaveInstanceState(outState) + } + @SuppressLint("InlinedApi") override fun onCreateUi(savedInstanceState: Bundle?) { - setContentView() showUnsupportedMessage() askForHomeShortcut() - // Ask permission to post notifications for background update check if (Config.checkUpdate) { - withPermission(Manifest.permission.POST_NOTIFICATIONS) { + extension.withPermission(Manifest.permission.POST_NOTIFICATIONS) { Config.checkUpdate = it } } window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE) - navigation.addOnDestinationChangedListener { _, destination, _ -> - isRootFragment = when (destination.id) { - R.id.homeFragment, - R.id.modulesFragment, - R.id.superuserFragment, - R.id.logFragment -> true - else -> false - } + val initialTab = getInitialTab(intent) - setDisplayHomeAsUpEnabled(!isRootFragment) - requestNavigationHidden(!isRootFragment) + setContent { + MagiskTheme { + Box(modifier = Modifier.fillMaxSize()) { + val navigator = rememberNavigator(Route.Main) + CompositionLocalProvider(LocalNavigator provides navigator) { + HandleFlashIntent(navigator) - binding.mainNavigation.menu.forEach { - if (it.itemId == destination.id) { - it.isChecked = true + NavDisplay( + backStack = navigator.backStack, + onBack = { navigator.pop() }, + entryDecorators = listOf( + rememberSaveableStateHolderNavEntryDecorator(), + rememberViewModelStoreNavEntryDecorator() + ), + entryProvider = entryProvider { + entry { + val superuserVm: SuperuserViewModel = viewModel( + viewModelStoreOwner = this@MainActivity, factory = VMFactory + ) + MainScreen( + initialTab = initialTab, + superuserViewModel = superuserVm, + onAuthenticate = { action -> + extension.withAuthentication { if (it) action() } + } + ) + } + entry { _ -> + val vm: DenyListViewModel = viewModel(factory = VMFactory) + LaunchedEffect(Unit) { vm.startLoading() } + DenyListScreen(vm, onBack = { navigator.pop() }) + } + entry { key -> + val vm: FlashViewModel = viewModel(factory = VMFactory) + LaunchedEffect(key) { + if (vm.flashAction.isEmpty()) { + vm.flashAction = key.action + vm.flashUri = key.additionalData?.toUri() + vm.startFlashing() + } + } + FlashScreen(vm, action = key.action, onBack = { navigator.pop() }) + } + entry { key -> + val vm: SuperuserViewModel = viewModel( + viewModelStoreOwner = this@MainActivity, factory = VMFactory + ) + LaunchedEffect(Unit) { + vm.authenticate = { onSuccess -> + extension.withAuthentication { if (it) onSuccess() } + } + } + SuperuserDetailScreen( + uid = key.uid, + viewModel = vm, + onBack = { navigator.pop() }, + onAuthenticate = { action -> + extension.withAuthentication { if (it) action() } + } + ) + } + entry { key -> + val vm: ActionViewModel = viewModel(factory = VMFactory) + LaunchedEffect(key) { + if (vm.actionId.isEmpty()) { + vm.actionId = key.id + vm.actionName = key.name + vm.startRunAction() + } + } + ActionScreen(vm, actionName = key.name, onBack = { navigator.pop() }) + } + } + ) + } + MainActivityDialogs( + showInvalid = showInvalidState.collectAsStateWithLifecycle().value, + unsupportedMessages = showUnsupported.collectAsStateWithLifecycle().value, + showShortcut = showShortcutPrompt.collectAsStateWithLifecycle().value, + onInvalidConfirmed = { + showInvalidState.value = false + handleInvalidStateInstall() + }, + onShortcutConfirmed = { + showShortcutPrompt.value = false + Shortcuts.addHomeIcon(this@MainActivity) + }, + onShortcutDismissed = { + showShortcutPrompt.value = false + } + ) } } } + } - setSupportActionBar(binding.mainToolbar) - - binding.mainNavigation.setOnItemSelectedListener { - getScreen(it.itemId)?.navigate() - true - } - binding.mainNavigation.setOnItemReselectedListener { - // https://issuetracker.google.com/issues/124538620 - } - binding.mainNavigation.menu.apply { - findItem(R.id.superuserFragment)?.isEnabled = Info.showSuperUser - findItem(R.id.modulesFragment)?.isEnabled = Info.env.isActive && LocalModule.loaded() - } - - val section = - if (intent.action == Intent.ACTION_APPLICATION_PREFERENCES) - Const.Nav.SETTINGS - else - intent.getStringExtra(Const.Key.OPEN_SECTION) - - getScreen(section)?.navigate() - - if (!isRootFragment) { - requestNavigationHidden(requiresAnimation = savedInstanceState == null) + @Composable + private fun HandleFlashIntent(navigator: Navigator) { + val intentVersion by intentState.collectAsStateWithLifecycle() + LaunchedEffect(intentVersion) { + val currentIntent = intent ?: return@LaunchedEffect + if (currentIntent.action == FlashUtils.INTENT_FLASH) { + val action = currentIntent.getStringExtra(FlashUtils.EXTRA_FLASH_ACTION) + ?: return@LaunchedEffect + val uri = currentIntent.getStringExtra(FlashUtils.EXTRA_FLASH_URI) + navigator.push(Route.Flash(action, uri)) + currentIntent.action = null + } } } - override fun onOptionsItemSelected(item: MenuItem): Boolean { - when (item.itemId) { - android.R.id.home -> onBackPressed() - else -> return super.onOptionsItemSelected(item) - } - return true + override fun onNewIntent(intent: Intent) { + super.onNewIntent(intent) + setIntent(intent) + intentState.value += 1 } - fun setDisplayHomeAsUpEnabled(isEnabled: Boolean) { - binding.mainToolbar.startAnimations() - when { - isEnabled -> binding.mainToolbar.setNavigationIcon(R.drawable.ic_back_md2) - else -> binding.mainToolbar.navigationIcon = null - } - } - - internal fun requestNavigationHidden(hide: Boolean = true, requiresAnimation: Boolean = true) { - val bottomView = binding.mainNavigation - if (requiresAnimation) { - bottomView.isVisible = true - bottomView.isHidden = hide + private fun getInitialTab(intent: Intent?): Int { + val section = if (intent?.action == Intent.ACTION_APPLICATION_PREFERENCES) { + Const.Nav.SETTINGS } else { - bottomView.isGone = hide + intent?.getStringExtra(Const.Key.OPEN_SECTION) } - } - - fun invalidateToolbar() { - //binding.mainToolbar.startAnimations() - binding.mainToolbar.invalidate() - } - - private fun getScreen(name: String?): NavDirections? { - return when (name) { - Const.Nav.SUPERUSER -> MainDirections.actionSuperuserFragment() - Const.Nav.MODULES -> MainDirections.actionModuleFragment() - Const.Nav.SETTINGS -> HomeFragmentDirections.actionHomeFragmentToSettingsFragment() - else -> null - } - } - - private fun getScreen(id: Int): NavDirections? { - return when (id) { - R.id.homeFragment -> MainDirections.actionHomeFragment() - R.id.modulesFragment -> MainDirections.actionModuleFragment() - R.id.superuserFragment -> MainDirections.actionSuperuserFragment() - R.id.logFragment -> MainDirections.actionLogFragment() - else -> null + return when (section) { + Const.Nav.SUPERUSER -> Tab.SUPERUSER.ordinal + Const.Nav.MODULES -> Tab.MODULES.ordinal + Const.Nav.SETTINGS -> Tab.SETTINGS.ordinal + else -> Tab.HOME.ordinal } } @SuppressLint("InlinedApi") - override fun showInvalidStateMessage(): Unit = runOnUiThread { - MagiskDialog(this).apply { - setTitle(CoreR.string.unsupport_nonroot_stub_title) - setMessage(CoreR.string.unsupport_nonroot_stub_msg) - setButton(MagiskDialog.ButtonType.POSITIVE) { - text = CoreR.string.install - onClick { - withPermission(REQUEST_INSTALL_PACKAGES) { - if (!it) { - toast(CoreR.string.install_unknown_denied, Toast.LENGTH_SHORT) - showInvalidStateMessage() - } else { - lifecycleScope.launch { - AppMigration.restore(this@MainActivity) - } - } + override fun showInvalidStateMessage() { + showInvalidState.value = true + } + + internal fun handleInvalidStateInstall() { + extension.withPermission(REQUEST_INSTALL_PACKAGES) { + if (!it) { + toast(CoreR.string.install_unknown_denied, Toast.LENGTH_SHORT) + showInvalidState.value = true + } else { + lifecycleScope.launch { + if (!AppMigration.restoreApp(this@MainActivity)) { + toast(CoreR.string.failure, Toast.LENGTH_LONG) } } } - setCancelable(false) - show() } } private fun showUnsupportedMessage() { - if (Info.env.isUnsupported) { - MagiskDialog(this).apply { - setTitle(CoreR.string.unsupport_magisk_title) - setMessage(CoreR.string.unsupport_magisk_msg, Const.Version.MIN_VERSION) - setButton(MagiskDialog.ButtonType.POSITIVE) { text = android.R.string.ok } - setCancelable(false) - }.show() - } + val messages = mutableListOf>() + if (Info.env.isUnsupported) { + messages.add(CoreR.string.unsupport_magisk_title to CoreR.string.unsupport_magisk_msg) + } if (!Info.isEmulator && Info.env.isActive && System.getenv("PATH") ?.split(':') ?.filterNot { File("$it/magisk").exists() } ?.any { File("$it/su").exists() } == true) { - MagiskDialog(this).apply { - setTitle(CoreR.string.unsupport_general_title) - setMessage(CoreR.string.unsupport_other_su_msg) - setButton(MagiskDialog.ButtonType.POSITIVE) { text = android.R.string.ok } - setCancelable(false) - }.show() + messages.add(CoreR.string.unsupport_general_title to CoreR.string.unsupport_other_su_msg) } - if (applicationInfo.flags and ApplicationInfo.FLAG_SYSTEM != 0) { - MagiskDialog(this).apply { - setTitle(CoreR.string.unsupport_general_title) - setMessage(CoreR.string.unsupport_system_app_msg) - setButton(MagiskDialog.ButtonType.POSITIVE) { text = android.R.string.ok } - setCancelable(false) - }.show() + messages.add(CoreR.string.unsupport_general_title to CoreR.string.unsupport_system_app_msg) + } + if (applicationInfo.flags and ApplicationInfo.FLAG_EXTERNAL_STORAGE != 0) { + messages.add(CoreR.string.unsupport_general_title to CoreR.string.unsupport_external_storage_msg) } - if (applicationInfo.flags and ApplicationInfo.FLAG_EXTERNAL_STORAGE != 0) { - MagiskDialog(this).apply { - setTitle(CoreR.string.unsupport_general_title) - setMessage(CoreR.string.unsupport_external_storage_msg) - setButton(MagiskDialog.ButtonType.POSITIVE) { text = android.R.string.ok } - setCancelable(false) - }.show() + if (messages.isNotEmpty()) { + showUnsupported.value = messages } } private fun askForHomeShortcut() { if (isRunningAsStub && !Config.askedHome && ShortcutManagerCompat.isRequestPinShortcutSupported(this)) { - // Ask and show dialog Config.askedHome = true - MagiskDialog(this).apply { - setTitle(CoreR.string.add_shortcut_title) - setMessage(CoreR.string.add_shortcut_msg) - setButton(MagiskDialog.ButtonType.NEGATIVE) { - text = android.R.string.cancel - } - setButton(MagiskDialog.ButtonType.POSITIVE) { - text = android.R.string.ok - onClick { - Shortcuts.addHomeIcon(this@MainActivity) - } - } - setCancelable(true) - }.show() + showShortcutPrompt.value = true + } + } +} + +@Composable +private fun MainActivityDialogs( + showInvalid: Boolean, + unsupportedMessages: List>, + showShortcut: Boolean, + onInvalidConfirmed: () -> Unit, + onShortcutConfirmed: () -> Unit, + onShortcutDismissed: () -> Unit, + modifier: Modifier = Modifier +) { + val resources = LocalResources.current + val invalidDialog = rememberConfirmDialog( + onConfirm = onInvalidConfirmed, + onDismiss = {} + ) + + LaunchedEffect(showInvalid) { + if (showInvalid) { + invalidDialog.showConfirm( + title = resources.getString(CoreR.string.unsupport_nonroot_stub_title), + content = resources.getString(CoreR.string.unsupport_nonroot_stub_msg), + confirm = resources.getString(CoreR.string.install), + ) + } + } + + var currentUnsupportedIndex by rememberSaveable { mutableIntStateOf(0) } + val unsupportedDialog = rememberConfirmDialog( + onConfirm = { currentUnsupportedIndex++ }, + onDismiss = { currentUnsupportedIndex++ } + ) + + val currentUnsupported = unsupportedMessages.getOrNull(currentUnsupportedIndex) + LaunchedEffect(currentUnsupported) { + if (currentUnsupported != null) { + val (titleRes, msgRes) = currentUnsupported + unsupportedDialog.showConfirm( + title = resources.getString(titleRes), + content = resources.getString(msgRes), + ) + } + } + + val shortcutDialog = rememberConfirmDialog( + onConfirm = onShortcutConfirmed, + onDismiss = onShortcutDismissed + ) + + LaunchedEffect(showShortcut) { + if (showShortcut) { + shortcutDialog.showConfirm( + title = resources.getString(CoreR.string.add_shortcut_title), + content = resources.getString(CoreR.string.add_shortcut_msg), + ) } } } diff --git a/app/apk-ng/src/main/java/com/topjohnwu/magisk/ui/MainScreen.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/MainScreen.kt similarity index 100% rename from app/apk-ng/src/main/java/com/topjohnwu/magisk/ui/MainScreen.kt rename to app/apk/src/main/java/com/topjohnwu/magisk/ui/MainScreen.kt diff --git a/app/apk-ng/src/main/java/com/topjohnwu/magisk/ui/component/Dialog.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/component/Dialog.kt similarity index 100% rename from app/apk-ng/src/main/java/com/topjohnwu/magisk/ui/component/Dialog.kt rename to app/apk/src/main/java/com/topjohnwu/magisk/ui/component/Dialog.kt diff --git a/app/apk-ng/src/main/java/com/topjohnwu/magisk/ui/component/Permissions.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/component/Permissions.kt similarity index 100% rename from app/apk-ng/src/main/java/com/topjohnwu/magisk/ui/component/Permissions.kt rename to app/apk/src/main/java/com/topjohnwu/magisk/ui/component/Permissions.kt diff --git a/app/apk-ng/src/main/java/com/topjohnwu/magisk/ui/component/Scrollbar.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/component/Scrollbar.kt similarity index 100% rename from app/apk-ng/src/main/java/com/topjohnwu/magisk/ui/component/Scrollbar.kt rename to app/apk/src/main/java/com/topjohnwu/magisk/ui/component/Scrollbar.kt diff --git a/app/apk-ng/src/main/java/com/topjohnwu/magisk/ui/component/SettingsComponents.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/component/SettingsComponents.kt similarity index 100% rename from app/apk-ng/src/main/java/com/topjohnwu/magisk/ui/component/SettingsComponents.kt rename to app/apk/src/main/java/com/topjohnwu/magisk/ui/component/SettingsComponents.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/deny/AppProcessInfo.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/deny/AppProcessInfo.kt index 9863279d0..7f701174a 100644 --- a/app/apk/src/main/java/com/topjohnwu/magisk/ui/deny/AppProcessInfo.kt +++ b/app/apk/src/main/java/com/topjohnwu/magisk/ui/deny/AppProcessInfo.kt @@ -12,8 +12,6 @@ import android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS import android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES import android.content.pm.ServiceInfo import android.graphics.drawable.Drawable -import android.os.Build -import android.os.Build.VERSION.SDK_INT import androidx.core.os.ProcessCompat import com.topjohnwu.magisk.core.ktx.getLabel import java.util.Locale @@ -31,28 +29,36 @@ class CmdlineListItem(line: String) { } const val ISOLATED_MAGIC = "isolated" +const val WEBVIEW_ZYGOTE_MAGIC = "webview_zygote" +const val WEBVIEW_ZYGOTE_UID = 1053 @SuppressLint("InlinedApi") class AppProcessInfo( private val info: ApplicationInfo, pm: PackageManager, - denyList: List + denyList: List, + private val labelOverride: String? = null, + private val processesOverride: Collection? = null, ) : Comparable { private val denyList = denyList.filter { it.packageName == info.packageName || it.packageName == ISOLATED_MAGIC } - val label = info.getLabel(pm) + val label = labelOverride ?: info.getLabel(pm) val iconImage: Drawable = runCatching { info.loadIcon(pm) }.getOrDefault(pm.defaultActivityIcon) val packageName: String get() = info.packageName - val processes = fetchProcesses(pm) + var firstInstallTime: Long = 0L + private set + var lastUpdateTime: Long = 0L + private set + val processes = processesOverride ?: fetchProcesses(pm) override fun compareTo(other: AppProcessInfo) = comparator.compare(this, other) fun isSystemApp() = info.flags and ApplicationInfo.FLAG_SYSTEM != 0 - fun isApp() = ProcessCompat.isApplicationUid(info.uid) + fun isApp() = packageName == WEBVIEW_ZYGOTE_MAGIC || ProcessCompat.isApplicationUid(info.uid) private fun createProcess(name: String, pkg: String = info.packageName) = ProcessInfo(name, pkg, denyList.any { it.process == name && it.packageName == pkg }) @@ -67,19 +73,30 @@ class AppProcessInfo( private fun Array?.toProcessList() = orEmpty().map { createProcess(it.getProcName()) } - private fun Array?.toProcessList() = orEmpty().map { - if (it.isIsolated) { - if (it.useAppZygote) { - val proc = info.processName ?: info.packageName - createProcess("${proc}_zygote") + private fun Array?.toProcessList(): List { + if (this == null) return emptyList() + val result = mutableListOf() + var hasIsolated = false + for (si in this) { + if (si.isIsolated) { + if (si.useAppZygote) { + val proc = info.processName ?: info.packageName + result.add(createProcess("${proc}_zygote")) + } else { + hasIsolated = true + } } else { - val proc = if (SDK_INT >= Build.VERSION_CODES.Q) - "${it.getProcName()}:${it.name}" else it.getProcName() - createProcess(proc, ISOLATED_MAGIC) + result.add(createProcess(si.getProcName())) } - } else { - createProcess(it.getProcName()) } + if (hasIsolated) { + val prefix = "${info.processName ?: info.packageName}:" + val isEnabled = denyList.any { + it.packageName == ISOLATED_MAGIC && it.process.startsWith(prefix) + } + result.add(ProcessInfo(prefix, ISOLATED_MAGIC, isEnabled)) + } + return result } private fun fetchProcesses(pm: PackageManager): Collection { @@ -92,6 +109,9 @@ class AppProcessInfo( pm.getPackageArchiveInfo(info.sourceDir, flag) ?: return emptyList() } + firstInstallTime = packageInfo.firstInstallTime + lastUpdateTime = packageInfo.lastUpdateTime + val processSet = TreeSet(compareBy({ it.name }, { it.isIsolated })) processSet += packageInfo.activities.toProcessList() processSet += packageInfo.services.toProcessList() @@ -101,6 +121,30 @@ class AppProcessInfo( } companion object { + fun webViewZygote( + pm: PackageManager, + denyList: List, + label: String, + ): AppProcessInfo { + val info = ApplicationInfo().apply { + packageName = WEBVIEW_ZYGOTE_MAGIC + uid = WEBVIEW_ZYGOTE_UID + } + val enabled = denyList.any { + it.packageName == WEBVIEW_ZYGOTE_MAGIC && + it.process == WEBVIEW_ZYGOTE_MAGIC + } + return AppProcessInfo( + info, + pm, + denyList, + labelOverride = label, + processesOverride = listOf( + ProcessInfo(WEBVIEW_ZYGOTE_MAGIC, WEBVIEW_ZYGOTE_MAGIC, enabled) + ), + ) + } + private val comparator = compareBy( { it.label.lowercase(Locale.ROOT) }, { it.info.packageName } @@ -114,5 +158,4 @@ data class ProcessInfo( var isEnabled: Boolean ) { val isIsolated = packageName == ISOLATED_MAGIC - val isAppZygote = name.endsWith("_zygote") } diff --git a/app/apk-ng/src/main/java/com/topjohnwu/magisk/ui/deny/DenyListScreen.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/deny/DenyListScreen.kt similarity index 100% rename from app/apk-ng/src/main/java/com/topjohnwu/magisk/ui/deny/DenyListScreen.kt rename to app/apk/src/main/java/com/topjohnwu/magisk/ui/deny/DenyListScreen.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/deny/DenyListViewModel.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/deny/DenyListViewModel.kt index dfca9852d..7716612af 100644 --- a/app/apk/src/main/java/com/topjohnwu/magisk/ui/deny/DenyListViewModel.kt +++ b/app/apk/src/main/java/com/topjohnwu/magisk/ui/deny/DenyListViewModel.kt @@ -2,54 +2,184 @@ package com.topjohnwu.magisk.ui.deny import android.annotation.SuppressLint import android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES -import androidx.databinding.Bindable import androidx.lifecycle.viewModelScope -import com.topjohnwu.magisk.BR import com.topjohnwu.magisk.arch.AsyncLoadViewModel import com.topjohnwu.magisk.core.AppContext import com.topjohnwu.magisk.core.ktx.concurrentMap -import com.topjohnwu.magisk.databinding.bindExtra -import com.topjohnwu.magisk.databinding.filterList -import com.topjohnwu.magisk.databinding.set import com.topjohnwu.superuser.Shell import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.SharingStarted +import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.filter +import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.flow.toCollection +import kotlinx.coroutines.flow.update import kotlinx.coroutines.withContext +enum class SortBy { NAME, PACKAGE_NAME, INSTALL_TIME, UPDATE_TIME } + +data class DenyProcessState( + val process: ProcessInfo, + val isEnabled: Boolean = process.isEnabled, +) { + val displayName: String = + if (process.isIsolated) "(isolated) ${process.name}*" else process.name +} + +data class DenyAppState( + val info: AppProcessInfo, + val processes: List = info.processes.map { DenyProcessState(it) }, + val isExpanded: Boolean = false, +) : Comparable { + + val itemsChecked: Int get() = processes.count { it.isEnabled } + val isChecked: Boolean get() = itemsChecked > 0 + val checkedPercent: Float get() = if (processes.isEmpty()) 0f else itemsChecked.toFloat() / processes.size + + override fun compareTo(other: DenyAppState) = comparator.compare(this, other) + + companion object { + private val comparator = compareBy( + { it.itemsChecked == 0 }, + { it.info } + ) + } +} + class DenyListViewModel : AsyncLoadViewModel() { - var isShowSystem = false - set(value) { - field = value - doQuery(query) + private val _loading = MutableStateFlow(true) + val loading: StateFlow = _loading.asStateFlow() + + private val _allApps = MutableStateFlow>(emptyList()) + + private val _query = MutableStateFlow("") + val query: StateFlow = _query.asStateFlow() + + private val _showSystem = MutableStateFlow(false) + val showSystem: StateFlow = _showSystem.asStateFlow() + + private val _showOS = MutableStateFlow(false) + val showOS: StateFlow = _showOS.asStateFlow() + + private val _sortBy = MutableStateFlow(SortBy.NAME) + val sortBy: StateFlow = _sortBy.asStateFlow() + + private val _sortReverse = MutableStateFlow(false) + val sortReverse: StateFlow = _sortReverse.asStateFlow() + + val filteredApps: StateFlow> = combine( + _allApps, _query, _showSystem, _showOS, _sortBy, _sortReverse + ) { args -> + @Suppress("UNCHECKED_CAST") + val apps = args[0] as List + val q = args[1] as String + val showSys = args[2] as Boolean + val showOS = args[3] as Boolean + val sort = args[4] as SortBy + val reverse = args[5] as Boolean + + val filtered = apps.filter { app -> + val passFilter = app.isChecked || + ((showSys || !app.info.isSystemApp()) && + ((showSys && showOS) || app.info.isApp())) + val passQuery = q.isBlank() || + app.info.label.contains(q, true) || + app.info.packageName.contains(q, true) || + app.processes.any { it.process.name.contains(q, true) } + passFilter && passQuery } - var isShowOS = false - set(value) { - field = value - doQuery(query) + val secondary: Comparator = when (sort) { + SortBy.NAME -> compareBy(String.CASE_INSENSITIVE_ORDER) { it.info.label } + SortBy.PACKAGE_NAME -> compareBy(String.CASE_INSENSITIVE_ORDER) { it.info.packageName } + SortBy.INSTALL_TIME -> compareByDescending { it.info.firstInstallTime } + SortBy.UPDATE_TIME -> compareByDescending { it.info.lastUpdateTime } } + val comparator = compareBy { it.itemsChecked == 0 } + .then(if (reverse) secondary.reversed() else secondary) + filtered.sortedWith(comparator) + }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList()) - var query = "" - set(value) { - field = value - doQuery(value) + fun setQuery(q: String) { _query.value = q } + fun setShowSystem(v: Boolean) { + _showSystem.value = v + if (!v) _showOS.value = false + } + fun setShowOS(v: Boolean) { _showOS.value = v } + fun setSortBy(s: SortBy) { _sortBy.value = s } + fun toggleSortReverse() { _sortReverse.value = !_sortReverse.value } + + fun toggleExpanded(app: DenyAppState) { + _allApps.update { apps -> + apps.map { + if (it.info.packageName == app.info.packageName) it.copy(isExpanded = !it.isExpanded) else it + } } - - val items = filterList(viewModelScope) - val extraBindings = bindExtra { - it.put(BR.viewModel, this) } - @get:Bindable - var loading = true - private set(value) = set(value, field, { field = it }, BR.loading) + fun toggleAll(app: DenyAppState) { + val willCheck = !app.isChecked + if (!willCheck) { + Shell.cmd("magisk --denylist rm ${app.info.packageName}").submit() + } + _allApps.update { apps -> + apps.map { currentApp -> + if (currentApp.info.packageName == app.info.packageName) { + val newProcs = currentApp.processes.map { proc -> + if (willCheck) { + if (!proc.isEnabled) { + val (name, pkg) = proc.process + Shell.cmd("magisk --denylist add $pkg '$name'").submit() + } + proc.copy(isEnabled = true) + } else { + if (proc.process.isIsolated && proc.isEnabled) { + val (name, pkg) = proc.process + Shell.cmd("magisk --denylist rm $pkg '$name'").submit() + } + proc.copy(isEnabled = false) + } + } + currentApp.copy(processes = newProcs) + } else { + currentApp + } + } + } + } + + fun toggleProcess(app: DenyAppState, proc: DenyProcessState) { + val newEnabled = !proc.isEnabled + val arg = if (newEnabled) "add" else "rm" + val (name, pkg) = proc.process + Shell.cmd("magisk --denylist $arg $pkg '$name'").submit() + + _allApps.update { apps -> + apps.map { currentApp -> + if (currentApp.info.packageName == app.info.packageName) { + val newProcs = currentApp.processes.map { currentProc -> + if (currentProc.process.name == proc.process.name && currentProc.process.packageName == proc.process.packageName) { + currentProc.copy(isEnabled = newEnabled) + } else { + currentProc + } + } + currentApp.copy(processes = newProcs) + } else { + currentApp + } + } + } + } @SuppressLint("InlinedApi") override suspend fun doLoadWork() { - loading = true + _loading.value = true val apps = withContext(Dispatchers.Default) { val pm = AppContext.packageManager val denyList = Shell.cmd("magisk --denylist ls").exec().out @@ -59,31 +189,23 @@ class DenyListViewModel : AsyncLoadViewModel() { .filter { AppContext.packageName != it.packageName } .concurrentMap { AppProcessInfo(it, pm, denyList) } .filter { it.processes.isNotEmpty() } - .concurrentMap { DenyListRvItem(it) } - .toCollection(ArrayList(size)) + .concurrentMap { DenyAppState(it) } + .toCollection(ArrayList(size + 1)) } - apps.sort() + apps += DenyAppState( + AppProcessInfo.webViewZygote( + pm, + denyList, + "WebView Zygote", + ) + ) + apps.sortWith(compareBy( + { it.processes.count { p -> p.isEnabled } == 0 }, + { it.info } + )) apps } - items.set(apps) - doQuery(query) - } - - private fun doQuery(s: String) { - items.filter { - fun filterSystem() = isShowSystem || !it.info.isSystemApp() - - fun filterOS() = (isShowSystem && isShowOS) || it.info.isApp() - - fun filterQuery(): Boolean { - fun inName() = it.info.label.contains(s, true) - fun inPackage() = it.info.packageName.contains(s, true) - fun inProcesses() = it.processes.any { p -> p.process.name.contains(s, true) } - return inName() || inPackage() || inProcesses() - } - - (it.isChecked || (filterSystem() && filterOS())) && filterQuery() - } - loading = false + _allApps.value = apps + _loading.value = false } } diff --git a/app/apk-ng/src/main/java/com/topjohnwu/magisk/ui/flash/FlashScreen.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/flash/FlashScreen.kt similarity index 100% rename from app/apk-ng/src/main/java/com/topjohnwu/magisk/ui/flash/FlashScreen.kt rename to app/apk/src/main/java/com/topjohnwu/magisk/ui/flash/FlashScreen.kt diff --git a/app/apk-ng/src/main/java/com/topjohnwu/magisk/ui/flash/FlashUtils.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/flash/FlashUtils.kt similarity index 100% rename from app/apk-ng/src/main/java/com/topjohnwu/magisk/ui/flash/FlashUtils.kt rename to app/apk/src/main/java/com/topjohnwu/magisk/ui/flash/FlashUtils.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/flash/FlashViewModel.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/flash/FlashViewModel.kt index 53abaff82..33fa0983e 100644 --- a/app/apk/src/main/java/com/topjohnwu/magisk/ui/flash/FlashViewModel.kt +++ b/app/apk/src/main/java/com/topjohnwu/magisk/ui/flash/FlashViewModel.kt @@ -1,31 +1,39 @@ package com.topjohnwu.magisk.ui.flash -import android.os.Build -import android.view.MenuItem -import androidx.databinding.Bindable -import androidx.databinding.ObservableArrayList -import androidx.lifecycle.LiveData -import androidx.lifecycle.MutableLiveData -import androidx.lifecycle.map +import android.net.Uri +import androidx.compose.runtime.mutableStateListOf +import androidx.core.net.toFile import androidx.lifecycle.viewModelScope -import com.topjohnwu.magisk.BR -import com.topjohnwu.magisk.R import com.topjohnwu.magisk.arch.BaseViewModel +import com.topjohnwu.magisk.core.AppContext import com.topjohnwu.magisk.core.Const import com.topjohnwu.magisk.core.Info import com.topjohnwu.magisk.core.ktx.reboot import com.topjohnwu.magisk.core.ktx.synchronized import com.topjohnwu.magisk.core.ktx.timeFormatStandard import com.topjohnwu.magisk.core.ktx.toTime -import com.topjohnwu.magisk.core.tasks.FlashZip +import com.topjohnwu.magisk.core.ktx.writeTo import com.topjohnwu.magisk.core.tasks.MagiskInstaller import com.topjohnwu.magisk.core.utils.MediaStoreUtils +import com.topjohnwu.magisk.core.utils.MediaStoreUtils.displayName +import com.topjohnwu.magisk.core.utils.MediaStoreUtils.inputStream import com.topjohnwu.magisk.core.utils.MediaStoreUtils.outputStream -import com.topjohnwu.magisk.databinding.set -import com.topjohnwu.magisk.events.SnackbarEvent +import com.topjohnwu.magisk.terminal.TerminalEmulator +import com.topjohnwu.magisk.terminal.appendLineOnMain +import com.topjohnwu.magisk.terminal.runSuCommand import com.topjohnwu.superuser.CallbackList +import com.topjohnwu.superuser.Shell +import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import timber.log.Timber +import java.io.File +import java.io.FileNotFoundException +import java.io.IOException class FlashViewModel : BaseViewModel() { @@ -33,94 +41,168 @@ class FlashViewModel : BaseViewModel() { FLASHING, SUCCESS, FAILED } - private val _state = MutableLiveData(State.FLASHING) - val state: LiveData get() = _state - val flashing = state.map { it == State.FLASHING } + private val _flashState = MutableStateFlow(State.FLASHING) + val flashState: StateFlow = _flashState.asStateFlow() - @get:Bindable - var showReboot = Info.isRooted - set(value) = set(value, field, { field = it }, BR.showReboot) + private val _showReboot = MutableStateFlow(Info.isRooted) + val showReboot: StateFlow = _showReboot.asStateFlow() - val items = ObservableArrayList() - lateinit var args: FlashFragmentArgs + var flashAction: String = "" + var flashUri: Uri? = null + // --- TerminalScreen mode (FLASH_ZIP) --- + + private var emulator: TerminalEmulator? = null + private val emulatorReady = CompletableDeferred() + + fun onEmulatorCreated(emu: TerminalEmulator) { + emulator = emu + emulatorReady.complete(emu) + } + + // --- LazyColumn mode (MagiskInstaller) --- + + val consoleItems = mutableStateListOf() private val logItems = mutableListOf().synchronized() private val outItems = object : CallbackList() { override fun onAddElement(e: String?) { e ?: return - items.add(ConsoleItem(e)) + consoleItems.add(e) logItems.add(e) } } + // --- Shared --- + fun startFlashing() { - val (action, uri) = args + val action = flashAction + val uri = flashUri viewModelScope.launch { - val result = when (action) { + when (action) { Const.Value.FLASH_ZIP -> { uri ?: return@launch - FlashZip(uri, outItems, logItems).exec() + flashZip(uri) } Const.Value.UNINSTALL -> { - showReboot = false - MagiskInstaller.Uninstall(outItems, logItems).exec() + _showReboot.value = false + onResult(withContext(Dispatchers.IO) { + MagiskInstaller.Uninstall(outItems, logItems).exec() + }) } Const.Value.FLASH_MAGISK -> { - if (Info.isEmulator) - MagiskInstaller.Emulator(outItems, logItems).exec() - else - MagiskInstaller.Direct(outItems, logItems).exec() + onResult(withContext(Dispatchers.IO) { + if (Info.isEmulator) + MagiskInstaller.Emulator(outItems, logItems).exec() + else + MagiskInstaller.Direct(outItems, logItems).exec() + }) } Const.Value.FLASH_INACTIVE_SLOT -> { - showReboot = false - MagiskInstaller.SecondSlot(outItems, logItems).exec() + _showReboot.value = false + onResult(withContext(Dispatchers.IO) { + MagiskInstaller.SecondSlot(outItems, logItems).exec() + }) } Const.Value.PATCH_FILE -> { uri ?: return@launch - showReboot = false - MagiskInstaller.Patch(uri, outItems, logItems).exec() + _showReboot.value = false + onResult(withContext(Dispatchers.IO) { + MagiskInstaller.Patch(uri, outItems, logItems).exec() + }) } Const.Value.DOWNLOAD -> { uri ?: return@launch - showReboot = false - MagiskInstaller.Download(uri.toString(), outItems, logItems).exec() - } - else -> { - back() - return@launch + _showReboot.value = false + onResult(withContext(Dispatchers.IO) { + MagiskInstaller.Download(uri.toString(), outItems, logItems).exec() + }) } } - onResult(result) } } private fun onResult(success: Boolean) { - _state.value = if (success) State.SUCCESS else State.FAILED + _flashState.value = if (success) State.SUCCESS else State.FAILED } - fun onMenuItemClicked(item: MenuItem): Boolean { - when (item.itemId) { - R.id.action_save -> savePressed() + private suspend fun flashZip(uri: Uri) { + val emu = emulatorReady.await() + + val installDir = File(AppContext.cacheDir, "flash") + val result = withContext(Dispatchers.IO) { + try { + installDir.deleteRecursively() + installDir.mkdirs() + + val zipFile = if (uri.scheme == "file") { + uri.toFile() + } else { + File(installDir, "install.zip").also { + try { + uri.inputStream().writeTo(it) + } catch (e: IOException) { + val msg = if (e is FileNotFoundException) "Invalid Uri" else "Cannot copy to cache" + return@withContext msg to null + } + } + } + + val binary = File(installDir, "update-binary") + AppContext.assets.open("module_installer.sh").use { it.writeTo(binary) } + + val name = uri.displayName + null to Triple(installDir, zipFile, name) + } catch (e: IOException) { + Timber.e(e) + "Unable to extract files" to null + } } - return true + + val (error, prepResult) = result + if (prepResult == null) { + emu.appendLineOnMain("! ${error ?: "Installation failed"}") + _flashState.value = State.FAILED + return + } + + val (dir, zipFile, displayName) = prepResult + + val success = withContext(Dispatchers.IO) { + runSuCommand( + emu, + "echo '- Installing $displayName'; " + + "sh $dir/update-binary dummy 1 '${zipFile.absolutePath}'; " + + "EXIT=\$?; " + + "if [ \$EXIT -ne 0 ]; then echo '! Installation failed'; fi; " + + "exit \$EXIT" + ) + } + + Shell.cmd("cd /", "rm -rf $dir ${Const.TMPDIR}").submit() + _flashState.value = if (success) State.SUCCESS else State.FAILED } - private fun savePressed() = withExternalRW { + fun saveLog() { viewModelScope.launch(Dispatchers.IO) { val name = "magisk_install_log_%s.log".format( System.currentTimeMillis().toTime(timeFormatStandard) ) val file = MediaStoreUtils.getFile(name) file.uri.outputStream().bufferedWriter().use { writer -> - synchronized(logItems) { - logItems.forEach { - writer.write(it) - writer.newLine() + val transcript = emulator?.screen?.transcriptText + if (transcript != null) { + writer.write(transcript) + } else { + synchronized(logItems) { + logItems.forEach { + writer.write(it) + writer.newLine() + } } } } - SnackbarEvent(file.toString()).publish() + showSnackbar(file.toString()) } } diff --git a/app/apk-ng/src/main/java/com/topjohnwu/magisk/ui/home/HomeScreen.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/home/HomeScreen.kt similarity index 100% rename from app/apk-ng/src/main/java/com/topjohnwu/magisk/ui/home/HomeScreen.kt rename to app/apk/src/main/java/com/topjohnwu/magisk/ui/home/HomeScreen.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/home/HomeViewModel.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/home/HomeViewModel.kt index 4a0aa8275..37689fb7a 100644 --- a/app/apk/src/main/java/com/topjohnwu/magisk/ui/home/HomeViewModel.kt +++ b/app/apk/src/main/java/com/topjohnwu/magisk/ui/home/HomeViewModel.kt @@ -1,35 +1,25 @@ package com.topjohnwu.magisk.ui.home import android.content.ActivityNotFoundException -import android.content.Context import android.content.Intent import android.widget.Toast import androidx.core.net.toUri -import androidx.databinding.Bindable -import com.topjohnwu.magisk.BR -import com.topjohnwu.magisk.R -import com.topjohnwu.magisk.arch.ActivityExecutor +import androidx.lifecycle.viewModelScope import com.topjohnwu.magisk.arch.AsyncLoadViewModel -import com.topjohnwu.magisk.arch.ContextExecutor -import com.topjohnwu.magisk.arch.UIActivity -import com.topjohnwu.magisk.arch.ViewEvent +import com.topjohnwu.magisk.core.AppContext import com.topjohnwu.magisk.core.BuildConfig import com.topjohnwu.magisk.core.Config import com.topjohnwu.magisk.core.Info -import com.topjohnwu.magisk.core.download.Subject -import com.topjohnwu.magisk.core.download.Subject.App import com.topjohnwu.magisk.core.ktx.await import com.topjohnwu.magisk.core.ktx.toast import com.topjohnwu.magisk.core.repository.NetworkService -import com.topjohnwu.magisk.core.utils.asText -import com.topjohnwu.magisk.databinding.bindExtra -import com.topjohnwu.magisk.databinding.set -import com.topjohnwu.magisk.dialog.EnvFixDialog -import com.topjohnwu.magisk.dialog.ManagerInstallDialog -import com.topjohnwu.magisk.dialog.UninstallDialog -import com.topjohnwu.magisk.events.SnackbarEvent +import com.topjohnwu.magisk.utils.asFlow import com.topjohnwu.superuser.Shell -import kotlin.math.roundToInt +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 com.topjohnwu.magisk.core.R as CoreR class HomeViewModel( @@ -40,111 +30,125 @@ class HomeViewModel( LOADING, INVALID, OUTDATED, UP_TO_DATE } - val magiskTitleBarrierIds = - intArrayOf(R.id.home_magisk_icon, R.id.home_magisk_title, R.id.home_magisk_button) - val appTitleBarrierIds = - intArrayOf(R.id.home_manager_icon, R.id.home_manager_title, R.id.home_manager_button) + data class UiState( + val isNoticeVisible: Boolean = Config.safetyNotice, + val appState: State = State.LOADING, + val managerRemoteVersion: String = "", + val managerProgress: Int = 0, + val showUninstall: Boolean = false, + val showManagerInstall: Boolean = false, + val showHideRestore: Boolean = false, + val envFixCode: Int = 0, + val magiskState: State = computeMagiskState(), + val magiskInstalledVersion: String = computeMagiskInstalledVersion(), + val managerInstalledVersion: String = computeManagerInstalledVersion(), + ) - @get:Bindable - var isNoticeVisible = Config.safetyNotice - set(value) = set(value, field, { field = it }, BR.noticeVisible) + private val _uiState = MutableStateFlow(UiState()) + val uiState: StateFlow = _uiState.asStateFlow() - val magiskState - get() = when { + val magiskState get() = _uiState.value.magiskState + val magiskInstalledVersion get() = _uiState.value.magiskInstalledVersion + val managerInstalledVersion get() = _uiState.value.managerInstalledVersion + + companion object { + private var checkedEnv = false + + fun computeMagiskState() = when { Info.isRooted && Info.env.isUnsupported -> State.OUTDATED !Info.env.isActive -> State.INVALID Info.env.versionCode < BuildConfig.APP_VERSION_CODE -> State.OUTDATED else -> State.UP_TO_DATE } - @get:Bindable - var appState = State.LOADING - set(value) = set(value, field, { field = it }, BR.appState) - - val magiskInstalledVersion - get() = Info.env.run { + fun computeMagiskInstalledVersion() = Info.env.run { if (isActive) - ("$versionString ($versionCode)" + if (isDebug) " (D)" else "").asText() + "$versionString ($versionCode)" + if (isDebug) " (D)" else "" else - CoreR.string.not_available.asText() + "" } - @get:Bindable - var managerRemoteVersion = CoreR.string.loading.asText() - set(value) = set(value, field, { field = it }, BR.managerRemoteVersion) - - val managerInstalledVersion - get() = "${BuildConfig.APP_VERSION_NAME} (${BuildConfig.APP_VERSION_CODE})" + - if (BuildConfig.DEBUG) " (D)" else "" - - @get:Bindable - var stateManagerProgress = 0 - set(value) = set(value, field, { field = it }, BR.stateManagerProgress) - - val extraBindings = bindExtra { - it.put(BR.viewModel, this) + fun computeManagerInstalledVersion() = + "${BuildConfig.APP_VERSION_NAME} (${BuildConfig.APP_VERSION_CODE})" + + if (BuildConfig.DEBUG) " (D)" else "" } - companion object { - private var checkedEnv = false + init { + viewModelScope.launch { + Info.isConnected.asFlow().collect { + startLoading() + } + } } override suspend fun doLoadWork() { - appState = State.LOADING + _uiState.update { + it.copy( + appState = State.LOADING, + magiskState = computeMagiskState(), + magiskInstalledVersion = computeMagiskInstalledVersion(), + managerInstalledVersion = computeManagerInstalledVersion(), + ) + } Info.fetchUpdate(svc)?.apply { - appState = when { - BuildConfig.APP_VERSION_CODE < versionCode -> State.OUTDATED - else -> State.UP_TO_DATE - } - val isDebug = Config.updateChannel == Config.Value.DEBUG_CHANNEL - managerRemoteVersion = - ("$version (${versionCode})" + if (isDebug) " (D)" else "").asText() + _uiState.update { + it.copy( + appState = if (BuildConfig.APP_VERSION_CODE < versionCode) State.OUTDATED else State.UP_TO_DATE, + managerRemoteVersion = "$version ($versionCode)" + if (isDebug) " (D)" else "" + ) + } } ?: run { - appState = State.INVALID - managerRemoteVersion = CoreR.string.not_available.asText() + _uiState.update { it.copy(appState = State.INVALID, managerRemoteVersion = "") } } ensureEnv() } - override fun onNetworkChanged(network: Boolean) = startLoading() - - fun onProgressUpdate(progress: Float, subject: Subject) { - if (subject is App) - stateManagerProgress = progress.times(100f).roundToInt() - } - - fun onLinkPressed(link: String) = object : ViewEvent(), ContextExecutor { - override fun invoke(context: Context) { - val intent = Intent(Intent.ACTION_VIEW, link.toUri()) - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) - try { - context.startActivity(intent) - } catch (e: ActivityNotFoundException) { - context.toast(CoreR.string.open_link_failed_toast, Toast.LENGTH_SHORT) - } - } - }.publish() - - fun onDeletePressed() = UninstallDialog().show() - - fun onManagerPressed() = when (appState) { - State.LOADING -> SnackbarEvent(CoreR.string.loading).publish() - State.INVALID -> SnackbarEvent(CoreR.string.no_connection).publish() - else -> withExternalRW { - withInstallPermission { - ManagerInstallDialog().show() - } + fun onLinkPressed(link: String) { + val intent = Intent(Intent.ACTION_VIEW, link.toUri()) + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + try { + AppContext.startActivity(intent) + } catch (e: ActivityNotFoundException) { + AppContext.toast(CoreR.string.open_link_failed_toast, Toast.LENGTH_SHORT) } } - fun onMagiskPressed() = withExternalRW { - HomeFragmentDirections.actionHomeFragmentToInstallFragment().navigate() + fun onDeletePressed() { + _uiState.update { it.copy(showUninstall = true) } + } + + fun onUninstallConsumed() { + _uiState.update { it.copy(showUninstall = false) } + } + + fun onManagerPressed() { + when (_uiState.value.appState) { + State.LOADING -> showSnackbar(CoreR.string.loading) + State.INVALID -> showSnackbar(CoreR.string.no_connection) + else -> _uiState.update { it.copy(showManagerInstall = true) } + } + } + + fun onManagerInstallConsumed() { + _uiState.update { it.copy(showManagerInstall = false) } + } + + fun onHideRestorePressed() { + _uiState.update { it.copy(showHideRestore = true) } + } + + fun onHideRestoreConsumed() { + _uiState.update { it.copy(showHideRestore = false) } + } + + fun onEnvFixConsumed() { + _uiState.update { it.copy(envFixCode = 0) } } fun hideNotice() { Config.safetyNotice = false - isNoticeVisible = false + _uiState.update { it.copy(isNoticeVisible = false) } } private suspend fun ensureEnv() { @@ -152,15 +156,8 @@ class HomeViewModel( val cmd = "env_check ${Info.env.versionString} ${Info.env.versionCode}" val code = Shell.cmd(cmd).await().code if (code != 0) { - EnvFixDialog(this, code).show() + _uiState.update { it.copy(envFixCode = code) } } checkedEnv = true } - - val showTest = false - fun onTestPressed() = object : ViewEvent(), ActivityExecutor { - override fun invoke(activity: UIActivity<*>) { - /* Entry point to trigger test events within the app */ - } - }.publish() } diff --git a/app/apk-ng/src/main/java/com/topjohnwu/magisk/ui/install/InstallBottomSheet.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/install/InstallBottomSheet.kt similarity index 100% rename from app/apk-ng/src/main/java/com/topjohnwu/magisk/ui/install/InstallBottomSheet.kt rename to app/apk/src/main/java/com/topjohnwu/magisk/ui/install/InstallBottomSheet.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/install/InstallViewModel.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/install/InstallViewModel.kt index 40e323962..4c5189dbb 100644 --- a/app/apk/src/main/java/com/topjohnwu/magisk/ui/install/InstallViewModel.kt +++ b/app/apk/src/main/java/com/topjohnwu/magisk/ui/install/InstallViewModel.kt @@ -1,101 +1,49 @@ package com.topjohnwu.magisk.ui.install import android.net.Uri -import android.os.Bundle -import android.os.Parcelable -import android.text.Spanned -import android.text.SpannedString import android.widget.Toast -import androidx.databinding.Bindable -import androidx.lifecycle.LiveData -import androidx.lifecycle.MutableLiveData -import androidx.lifecycle.Observer import androidx.lifecycle.viewModelScope -import com.topjohnwu.magisk.BR -import com.topjohnwu.magisk.R import com.topjohnwu.magisk.arch.BaseViewModel import com.topjohnwu.magisk.core.AppContext import com.topjohnwu.magisk.core.BuildConfig.APP_VERSION_CODE -import com.topjohnwu.magisk.core.Config +import com.topjohnwu.magisk.core.Const import com.topjohnwu.magisk.core.Info -import com.topjohnwu.magisk.core.base.ContentResultCallback import com.topjohnwu.magisk.core.ktx.toast import com.topjohnwu.magisk.core.repository.NetworkService -import com.topjohnwu.magisk.databinding.set -import com.topjohnwu.magisk.dialog.DownloadDialog -import com.topjohnwu.magisk.dialog.SecondSlotWarningDialog -import com.topjohnwu.magisk.events.GetContentEvent -import com.topjohnwu.magisk.ui.flash.FlashFragment -import io.noties.markwon.Markwon +import com.topjohnwu.magisk.ui.navigation.Route import kotlinx.coroutines.Dispatchers +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.withContext -import kotlinx.parcelize.Parcelize import timber.log.Timber import java.io.File import java.io.IOException import com.topjohnwu.magisk.core.R as CoreR -class InstallViewModel(svc: NetworkService, markwon: Markwon) : BaseViewModel() { +class InstallViewModel(svc: NetworkService) : BaseViewModel() { + + enum class Method { NONE, PATCH, DIRECT, INACTIVE_SLOT, DOWNLOAD } + + data class UiState( + val step: Int = 0, + val method: Method = Method.NONE, + val notes: String = "", + val patchUri: Uri? = null, + val requestFilePicker: Boolean = false, + val showSecondSlotWarning: Boolean = false, + val showDownloadDialog: Boolean = false, + ) val isRooted get() = Info.isRooted val skipOptions = Info.isEmulator || (Info.isSAR && !Info.isFDE && Info.ramdisk) val noSecondSlot = !isRooted || !Info.isAB || Info.isEmulator - @get:Bindable - var step = if (skipOptions) 1 else 0 - set(value) = set(value, field, { field = it }, BR.step) - - private var methodId = -1 - private var spuriousMethodId = -1 - - @get:Bindable - var method - get() = methodId - set(value) = set(value, methodId, { methodId = it }, BR.method) { - if (it == spuriousMethodId) { - spuriousMethodId = -1 - return@set - } - when (it) { - R.id.method_patch -> { - GetContentEvent("*/*", UriCallback()).publish() - } - R.id.method_download -> { - DownloadDialog( - callback = { url -> _uri.value = url }, - onCancel = { resetMethod() }, - ).show() - } - R.id.method_inactive_slot -> { - SecondSlotWarningDialog().show() - } - } - } - - private fun resetMethod() { - spuriousMethodId = methodId - method = -1 - } - - private val _uri = MutableLiveData() - val data: LiveData get() = _uri - - private val sourceObserver = Observer { source -> - when (source) { - is PatchSource.File -> _uri.value = source.uri - PatchSource.Cancelled -> resetMethod() - null -> return@Observer - } - patchSource.value = null - } - - @get:Bindable - var notes: Spanned = SpannedString("") - set(value) = set(value, field, { field = it }, BR.notes) + private val _uiState = MutableStateFlow(UiState(step = if (skipOptions) 1 else 0)) + val uiState: StateFlow = _uiState.asStateFlow() init { - patchSource.observeForever(sourceObserver) viewModelScope.launch(Dispatchers.IO) { try { val noteFile = File(AppContext.cacheDir, "${APP_VERSION_CODE}.md") @@ -108,84 +56,77 @@ class InstallViewModel(svc: NetworkService, markwon: Markwon) : BaseViewModel() note } } - val spanned = markwon.toMarkdown(noteText) - withContext(Dispatchers.Main) { - notes = spanned - } + _uiState.update { it.copy(notes = noteText) } } catch (e: IOException) { Timber.e(e) } } } - fun install() { + fun nextStep() { + _uiState.update { it.copy(step = 1) } + } + + fun selectMethod(method: Method) { + _uiState.update { it.copy(method = method) } when (method) { - R.id.method_patch -> FlashFragment.patch(data.value!!).navigate(true) - R.id.method_download -> FlashFragment.download(data.value!!).navigate(true) - R.id.method_direct -> FlashFragment.flash(false).navigate(true) - R.id.method_inactive_slot -> FlashFragment.flash(true).navigate(true) - else -> error("Unknown value") + Method.PATCH -> { + AppContext.toast(CoreR.string.patch_file_msg, Toast.LENGTH_LONG) + _uiState.update { it.copy(requestFilePicker = true) } + } + Method.INACTIVE_SLOT -> { + _uiState.update { it.copy(showSecondSlotWarning = true) } + } + Method.DOWNLOAD -> { + _uiState.update { it.copy(showDownloadDialog = true) } + } + else -> {} } } - override fun onSaveState(state: Bundle) { - state.putParcelable( - INSTALL_STATE_KEY, InstallState( - methodId, - step, - Config.keepVerity, - Config.keepEnc, - Config.recovery - ) - ) + fun onFilePickerConsumed() { + _uiState.update { it.copy(requestFilePicker = false) } } - override fun onRestoreState(state: Bundle) { - state.getParcelable(INSTALL_STATE_KEY)?.let { - methodId = it.method - step = it.step - Config.keepVerity = it.keepVerity - Config.keepEnc = it.keepEnc - Config.recovery = it.recovery + fun onSecondSlotWarningConsumed() { + _uiState.update { it.copy(showSecondSlotWarning = false) } + } + + fun onDownloadDialogConsumed() { + _uiState.update { it.copy(showDownloadDialog = false) } + } + + fun onPatchFileSelected(uri: Uri) { + _uiState.update { it.copy(patchUri = uri) } + if (_uiState.value.method == Method.PATCH) { + install() } } - override fun onCleared() { - patchSource.removeObserver(sourceObserver) - super.onCleared() - } - - private sealed interface PatchSource { - data class File(val uri: Uri) : PatchSource - data object Cancelled : PatchSource - } - - @Parcelize - class UriCallback : ContentResultCallback { - override fun onActivityLaunch() { - AppContext.toast(CoreR.string.patch_file_msg, Toast.LENGTH_LONG) - } - - override fun onActivityResult(result: Uri) { - patchSource.value = PatchSource.File(result) - } - - override fun onActivityCancel() { - patchSource.value = PatchSource.Cancelled + fun onDownloadUrlSelected(uri: Uri) { + _uiState.update { it.copy(patchUri = uri) } + if (_uiState.value.method == Method.DOWNLOAD) { + install() } } - @Parcelize - class InstallState( - val method: Int, - val step: Int, - val keepVerity: Boolean, - val keepEnc: Boolean, - val recovery: Boolean, - ) : Parcelable - - companion object { - private const val INSTALL_STATE_KEY = "install_state" - private val patchSource = MutableLiveData() + fun install() { + when (_uiState.value.method) { + Method.PATCH -> navigateTo(Route.Flash( + action = Const.Value.PATCH_FILE, + additionalData = _uiState.value.patchUri!!.toString() + )) + Method.DOWNLOAD -> navigateTo(Route.Flash( + action = Const.Value.DOWNLOAD, + additionalData = _uiState.value.patchUri!!.toString() + )) + Method.DIRECT -> navigateTo(Route.Flash( + action = Const.Value.FLASH_MAGISK + )) + Method.INACTIVE_SLOT -> navigateTo(Route.Flash( + action = Const.Value.FLASH_INACTIVE_SLOT + )) + else -> error("Unknown method") + } } } diff --git a/app/apk-ng/src/main/java/com/topjohnwu/magisk/ui/log/LogScreen.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/log/LogScreen.kt similarity index 100% rename from app/apk-ng/src/main/java/com/topjohnwu/magisk/ui/log/LogScreen.kt rename to app/apk/src/main/java/com/topjohnwu/magisk/ui/log/LogScreen.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/log/LogViewModel.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/log/LogViewModel.kt index 928a6f823..96eaf3411 100644 --- a/app/apk/src/main/java/com/topjohnwu/magisk/ui/log/LogViewModel.kt +++ b/app/apk/src/main/java/com/topjohnwu/magisk/ui/log/LogViewModel.kt @@ -1,24 +1,24 @@ package com.topjohnwu.magisk.ui.log import android.system.Os -import androidx.databinding.Bindable import androidx.lifecycle.viewModelScope -import com.topjohnwu.magisk.BR import com.topjohnwu.magisk.arch.AsyncLoadViewModel import com.topjohnwu.magisk.core.BuildConfig import com.topjohnwu.magisk.core.Info import com.topjohnwu.magisk.core.R import com.topjohnwu.magisk.core.ktx.timeFormatStandard import com.topjohnwu.magisk.core.ktx.toTime +import com.topjohnwu.magisk.core.model.su.SuLog import com.topjohnwu.magisk.core.repository.LogRepository +import com.topjohnwu.magisk.core.su.SuEvents import com.topjohnwu.magisk.core.utils.MediaStoreUtils import com.topjohnwu.magisk.core.utils.MediaStoreUtils.outputStream -import com.topjohnwu.magisk.databinding.bindExtra -import com.topjohnwu.magisk.databinding.diffList -import com.topjohnwu.magisk.databinding.set -import com.topjohnwu.magisk.events.SnackbarEvent -import com.topjohnwu.magisk.view.TextItem import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.debounce +import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.io.FileInputStream @@ -26,46 +26,42 @@ import java.io.FileInputStream class LogViewModel( private val repo: LogRepository ) : AsyncLoadViewModel() { - @get:Bindable - var loading = true - private set(value) = set(value, field, { field = it }, BR.loading) - // --- empty view - - val itemEmpty = TextItem(R.string.log_data_none) - val itemMagiskEmpty = TextItem(R.string.log_data_magisk_none) - - // --- su log - - val items = diffList() - val extraBindings = bindExtra { - it.put(BR.viewModel, this) + init { + @OptIn(kotlinx.coroutines.FlowPreview::class) + viewModelScope.launch { + SuEvents.logUpdated.debounce(500).collect { reload() } + } } - // --- magisk log - val logs = diffList() - var magiskLogRaw = " " + data class UiState( + val loading: Boolean = true, + val magiskLog: String = "", + val magiskLogEntries: List = emptyList(), + val suLogs: List = emptyList(), + ) + + private val _uiState = MutableStateFlow(UiState()) + val uiState: StateFlow = _uiState.asStateFlow() + + private var magiskLogRaw = "" override suspend fun doLoadWork() { - loading = true - - val (suLogs, suDiff) = withContext(Dispatchers.Default) { + _uiState.update { it.copy(loading = true) } + withContext(Dispatchers.Default) { magiskLogRaw = repo.fetchMagiskLogs() - val newLogs = magiskLogRaw.split('\n').map { LogRvItem(it) } - logs.update(newLogs) - val suLogs = repo.fetchSuLogs().map { SuLogRvItem(it) } - suLogs to items.calculateDiff(suLogs) + val suLogs = repo.fetchSuLogs() + val entries = MagiskLogParser.parse(magiskLogRaw) + _uiState.update { it.copy( + loading = false, + magiskLog = magiskLogRaw, + magiskLogEntries = entries, + suLogs = suLogs, + ) } } - - items.firstOrNull()?.isTop = false - items.lastOrNull()?.isBottom = false - items.update(suLogs, suDiff) - items.firstOrNull()?.isTop = true - items.lastOrNull()?.isBottom = true - loading = false } - fun saveMagiskLog() = withExternalRW { + fun saveMagiskLog() { viewModelScope.launch(Dispatchers.IO) { val filename = "magisk_log_%s.log".format( System.currentTimeMillis().toTime(timeFormatStandard)) @@ -97,18 +93,18 @@ class LogViewModel( ProcessBuilder("logcat", "-d").start() .inputStream.reader().use { it.copyTo(file) } } - SnackbarEvent(logFile.toString()).publish() + showSnackbar(logFile.toString()) } } fun clearMagiskLog() = repo.clearMagiskLogs { - SnackbarEvent(R.string.logs_cleared).publish() + showSnackbar(R.string.logs_cleared) startLoading() } fun clearLog() = viewModelScope.launch { repo.clearLogs() - SnackbarEvent(R.string.logs_cleared).publish() + showSnackbar(R.string.logs_cleared) startLoading() } } diff --git a/app/apk-ng/src/main/java/com/topjohnwu/magisk/ui/log/MagiskLogParser.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/log/MagiskLogParser.kt similarity index 100% rename from app/apk-ng/src/main/java/com/topjohnwu/magisk/ui/log/MagiskLogParser.kt rename to app/apk/src/main/java/com/topjohnwu/magisk/ui/log/MagiskLogParser.kt diff --git a/app/apk-ng/src/main/java/com/topjohnwu/magisk/ui/module/ActionScreen.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/module/ActionScreen.kt similarity index 100% rename from app/apk-ng/src/main/java/com/topjohnwu/magisk/ui/module/ActionScreen.kt rename to app/apk/src/main/java/com/topjohnwu/magisk/ui/module/ActionScreen.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/module/ActionViewModel.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/module/ActionViewModel.kt index 2591aadd1..efd0bbf90 100644 --- a/app/apk/src/main/java/com/topjohnwu/magisk/ui/module/ActionViewModel.kt +++ b/app/apk/src/main/java/com/topjohnwu/magisk/ui/module/ActionViewModel.kt @@ -1,26 +1,20 @@ package com.topjohnwu.magisk.ui.module -import android.view.MenuItem -import androidx.databinding.ObservableArrayList -import androidx.lifecycle.LiveData -import androidx.lifecycle.MutableLiveData import androidx.lifecycle.viewModelScope -import com.topjohnwu.magisk.R import com.topjohnwu.magisk.arch.BaseViewModel -import com.topjohnwu.magisk.core.ktx.synchronized import com.topjohnwu.magisk.core.ktx.timeFormatStandard import com.topjohnwu.magisk.core.ktx.toTime import com.topjohnwu.magisk.core.utils.MediaStoreUtils import com.topjohnwu.magisk.core.utils.MediaStoreUtils.outputStream -import com.topjohnwu.magisk.events.SnackbarEvent -import com.topjohnwu.magisk.ui.flash.ConsoleItem -import com.topjohnwu.superuser.CallbackList -import com.topjohnwu.superuser.Shell +import com.topjohnwu.magisk.terminal.TerminalEmulator +import com.topjohnwu.magisk.terminal.runSuCommand +import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch import kotlinx.coroutines.withContext -import timber.log.Timber -import java.io.IOException class ActionViewModel : BaseViewModel() { @@ -28,61 +22,49 @@ class ActionViewModel : BaseViewModel() { RUNNING, SUCCESS, FAILED } - private val _state = MutableLiveData(State.RUNNING) - val state: LiveData get() = _state + private val _actionState = MutableStateFlow(State.RUNNING) + val actionState: StateFlow = _actionState.asStateFlow() - val items = ObservableArrayList() - lateinit var args: ActionFragmentArgs + var actionId: String = "" + var actionName: String = "" - private val logItems = mutableListOf().synchronized() - private val outItems = object : CallbackList() { - override fun onAddElement(e: String?) { - e ?: return - items.add(ConsoleItem(e)) - logItems.add(e) - } + private var emulator: TerminalEmulator? = null + private val emulatorReady = CompletableDeferred() + + fun onEmulatorCreated(emu: TerminalEmulator) { + emulator = emu + emulatorReady.complete(emu) } - fun startRunAction() = viewModelScope.launch { - onResult(withContext(Dispatchers.IO) { - try { - Shell.cmd("run_action \'${args.id}\'") - .to(outItems, logItems) - .exec().isSuccess - } catch (e: IOException) { - Timber.e(e) - false + fun startRunAction() { + viewModelScope.launch { + val emu = emulatorReady.await() + + val success = withContext(Dispatchers.IO) { + runSuCommand( + emu, + "cd /data/adb/modules/$actionId && sh ./action.sh" + ) } - }) - } - private fun onResult(success: Boolean) { - _state.value = if (success) State.SUCCESS else State.FAILED - } - - fun onMenuItemClicked(item: MenuItem): Boolean { - when (item.itemId) { - R.id.action_save -> savePressed() + _actionState.value = if (success) State.SUCCESS else State.FAILED } - return true } - private fun savePressed() = withExternalRW { + fun saveLog() { viewModelScope.launch(Dispatchers.IO) { val name = "%s_action_log_%s.log".format( - args.name, + actionName, System.currentTimeMillis().toTime(timeFormatStandard) ) val file = MediaStoreUtils.getFile(name) file.uri.outputStream().bufferedWriter().use { writer -> - synchronized(logItems) { - logItems.forEach { - writer.write(it) - writer.newLine() - } + val transcript = emulator?.screen?.transcriptText + if (transcript != null) { + writer.write(transcript) } } - SnackbarEvent(file.toString()).publish() + showSnackbar(file.toString()) } } } diff --git a/app/apk-ng/src/main/java/com/topjohnwu/magisk/ui/module/ModuleScreen.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/module/ModuleScreen.kt similarity index 100% rename from app/apk-ng/src/main/java/com/topjohnwu/magisk/ui/module/ModuleScreen.kt rename to app/apk/src/main/java/com/topjohnwu/magisk/ui/module/ModuleScreen.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/module/ModuleViewModel.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/module/ModuleViewModel.kt index 863206338..f0e9a6670 100644 --- a/app/apk/src/main/java/com/topjohnwu/magisk/ui/module/ModuleViewModel.kt +++ b/app/apk/src/main/java/com/topjohnwu/magisk/ui/module/ModuleViewModel.kt @@ -1,108 +1,147 @@ package com.topjohnwu.magisk.ui.module +import android.content.Context import android.net.Uri -import androidx.databinding.Bindable -import androidx.lifecycle.MutableLiveData -import com.topjohnwu.magisk.BR -import com.topjohnwu.magisk.MainDirections -import com.topjohnwu.magisk.R +import androidx.lifecycle.viewModelScope import com.topjohnwu.magisk.arch.AsyncLoadViewModel import com.topjohnwu.magisk.core.Const import com.topjohnwu.magisk.core.Info -import com.topjohnwu.magisk.core.base.ContentResultCallback +import com.topjohnwu.magisk.core.download.Subject import com.topjohnwu.magisk.core.model.module.LocalModule import com.topjohnwu.magisk.core.model.module.OnlineModule -import com.topjohnwu.magisk.databinding.MergeObservableList -import com.topjohnwu.magisk.databinding.RvItem -import com.topjohnwu.magisk.databinding.bindExtra -import com.topjohnwu.magisk.databinding.diffList -import com.topjohnwu.magisk.databinding.set -import com.topjohnwu.magisk.dialog.LocalModuleInstallDialog -import com.topjohnwu.magisk.dialog.OnlineModuleInstallDialog -import com.topjohnwu.magisk.events.GetContentEvent -import com.topjohnwu.magisk.events.SnackbarEvent +import com.topjohnwu.magisk.core.utils.TextHolder +import com.topjohnwu.magisk.core.utils.asText +import com.topjohnwu.magisk.ui.flash.FlashUtils +import com.topjohnwu.magisk.ui.navigation.Route +import com.topjohnwu.magisk.utils.asFlow +import com.topjohnwu.magisk.view.Notifications import kotlinx.coroutines.Dispatchers +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.withContext import kotlinx.parcelize.Parcelize import com.topjohnwu.magisk.core.R as CoreR +data class ModuleItem( + val module: LocalModule, + val isEnabled: Boolean = module.enable, + val isRemoved: Boolean = module.remove, + val showUpdate: Boolean = module.updateInfo != null, +) { + val showNotice: Boolean + val showAction: Boolean + val noticeText: TextHolder + val isUpdated = module.updated + val updateReady get() = module.outdated && !isRemoved && isEnabled + + init { + val isZygisk = module.isZygisk + val isRiru = module.isRiru + val zygiskUnloaded = isZygisk && module.zygiskUnloaded + + showNotice = zygiskUnloaded || + (Info.isZygiskEnabled && isRiru) || + (!Info.isZygiskEnabled && isZygisk) + showAction = module.hasAction && !showNotice + noticeText = + when { + zygiskUnloaded -> CoreR.string.zygisk_module_unloaded.asText() + isRiru -> CoreR.string.suspend_text_riru.asText(CoreR.string.zygisk.asText()) + else -> CoreR.string.suspend_text_zygisk.asText(CoreR.string.zygisk.asText()) + } + } +} + +@Parcelize +class OnlineModuleSubject( + override val module: OnlineModule, + override val autoLaunch: Boolean, + override val notifyId: Int = Notifications.nextId(), +) : Subject.Module() { + override fun pendingIntent(context: Context) = FlashUtils.installIntent(context, file) +} + class ModuleViewModel : AsyncLoadViewModel() { - val bottomBarBarrierIds = intArrayOf(R.id.module_update, R.id.module_remove) + data class UiState( + val loading: Boolean = true, + val modules: List = emptyList(), + ) - private val itemsInstalled = diffList() + private val _uiState = MutableStateFlow(UiState()) + val uiState: StateFlow = _uiState.asStateFlow() - val items = MergeObservableList() - val extraBindings = bindExtra { - it.put(BR.viewModel, this) - } - - val data get() = uri - - @get:Bindable - var loading = true - private set(value) = set(value, field, { field = it }, BR.loading) - - override suspend fun doLoadWork() { - loading = true - val moduleLoaded = Info.env.isActive && - withContext(Dispatchers.IO) { LocalModule.loaded() } - if (moduleLoaded) { - loadInstalled() - if (items.isEmpty()) { - items.insertItem(InstallModule) - .insertList(itemsInstalled) + init { + viewModelScope.launch { + Info.isConnected.asFlow().collect { + startLoading() } } - loading = false - loadUpdateInfo() } - override fun onNetworkChanged(network: Boolean) = startLoading() - - private suspend fun loadInstalled() { - withContext(Dispatchers.Default) { - val installed = LocalModule.installed().map { LocalModuleRvItem(it) } - itemsInstalled.update(installed) + override suspend fun doLoadWork() { + _uiState.update { it.copy(loading = true) } + val moduleLoaded = Info.env.isActive && + withContext(Dispatchers.IO) { LocalModule.loaded() } + if (moduleLoaded) { + val modules = withContext(Dispatchers.Default) { + LocalModule.installed().map { ModuleItem(it) } + } + _uiState.update { it.copy(loading = false, modules = modules) } + loadUpdateInfo() + } else { + _uiState.update { it.copy(loading = false) } } } private suspend fun loadUpdateInfo() { withContext(Dispatchers.IO) { - itemsInstalled.forEach { - if (it.item.fetch()) - it.fetchedUpdateInfo() + _uiState.update { state -> + state.copy( + modules = state.modules.map { item -> + if (item.module.fetch()) { + item.copy(showUpdate = item.module.updateInfo != null) + } else { + item + } + } + ) } } } - fun downloadPressed(item: OnlineModule?) = - if (item != null && Info.isConnected.value == true) { - withExternalRW { OnlineModuleInstallDialog(item).show() } - } else { - SnackbarEvent(CoreR.string.no_connection).publish() - } - - fun installPressed() = withExternalRW { - GetContentEvent("application/zip", UriCallback()).publish() - } - - fun requestInstallLocalModule(uri: Uri, displayName: String) { - LocalModuleInstallDialog(this, uri, displayName).show() - } - - @Parcelize - class UriCallback : ContentResultCallback { - override fun onActivityResult(result: Uri) { - uri.value = result - } + fun confirmLocalInstall(uri: Uri) { + navigateTo(Route.Flash(Const.Value.FLASH_ZIP, uri.toString())) } fun runAction(id: String, name: String) { - MainDirections.actionActionFragment(id, name).navigate() + navigateTo(Route.Action(id, name)) } - companion object { - private val uri = MutableLiveData() + fun toggleEnabled(item: ModuleItem) { + val newEnabled = !item.isEnabled + item.module.enable = newEnabled + _uiState.update { state -> + state.copy( + modules = state.modules.map { + if (it.module.id == item.module.id) it.copy(isEnabled = newEnabled) else it + } + ) + } + } + + fun toggleRemove(item: ModuleItem) { + val newRemoved = !item.isRemoved + item.module.remove = newRemoved + _uiState.update { state -> + state.copy( + modules = state.modules.map { + if (it.module.id == item.module.id) it.copy(isRemoved = newRemoved) else it + } + ) + } } } diff --git a/app/apk-ng/src/main/java/com/topjohnwu/magisk/ui/navigation/CollectNavEvents.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/navigation/CollectNavEvents.kt similarity index 100% rename from app/apk-ng/src/main/java/com/topjohnwu/magisk/ui/navigation/CollectNavEvents.kt rename to app/apk/src/main/java/com/topjohnwu/magisk/ui/navigation/CollectNavEvents.kt diff --git a/app/apk-ng/src/main/java/com/topjohnwu/magisk/ui/navigation/Navigator.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/navigation/Navigator.kt similarity index 100% rename from app/apk-ng/src/main/java/com/topjohnwu/magisk/ui/navigation/Navigator.kt rename to app/apk/src/main/java/com/topjohnwu/magisk/ui/navigation/Navigator.kt diff --git a/app/apk-ng/src/main/java/com/topjohnwu/magisk/ui/navigation/Routes.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/navigation/Routes.kt similarity index 100% rename from app/apk-ng/src/main/java/com/topjohnwu/magisk/ui/navigation/Routes.kt rename to app/apk/src/main/java/com/topjohnwu/magisk/ui/navigation/Routes.kt diff --git a/app/apk-ng/src/main/java/com/topjohnwu/magisk/ui/settings/SettingsScreen.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/settings/SettingsScreen.kt similarity index 100% rename from app/apk-ng/src/main/java/com/topjohnwu/magisk/ui/settings/SettingsScreen.kt rename to app/apk/src/main/java/com/topjohnwu/magisk/ui/settings/SettingsScreen.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/settings/SettingsViewModel.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/settings/SettingsViewModel.kt index e8dd010f9..1ee131317 100644 --- a/app/apk/src/main/java/com/topjohnwu/magisk/ui/settings/SettingsViewModel.kt +++ b/app/apk/src/main/java/com/topjohnwu/magisk/ui/settings/SettingsViewModel.kt @@ -1,132 +1,61 @@ package com.topjohnwu.magisk.ui.settings -import android.app.Activity -import android.content.Intent -import android.net.Uri -import android.os.Build -import android.provider.Settings -import android.view.View import android.widget.Toast -import androidx.core.content.pm.ShortcutManagerCompat import androidx.lifecycle.viewModelScope -import com.topjohnwu.magisk.BR import com.topjohnwu.magisk.arch.BaseViewModel import com.topjohnwu.magisk.core.AppContext -import com.topjohnwu.magisk.core.BuildConfig import com.topjohnwu.magisk.core.Config -import com.topjohnwu.magisk.core.Const import com.topjohnwu.magisk.core.Info import com.topjohnwu.magisk.core.R -import com.topjohnwu.magisk.core.isRunningAsStub -import com.topjohnwu.magisk.core.ktx.activity import com.topjohnwu.magisk.core.ktx.toast -import com.topjohnwu.magisk.core.tasks.AppMigration -import com.topjohnwu.magisk.core.utils.LocaleSetting import com.topjohnwu.magisk.core.utils.RootUtils -import com.topjohnwu.magisk.databinding.bindExtra -import com.topjohnwu.magisk.events.AddHomeIconEvent -import com.topjohnwu.magisk.events.AuthEvent -import com.topjohnwu.magisk.events.SnackbarEvent +import com.topjohnwu.magisk.ui.navigation.Route +import com.topjohnwu.magisk.view.Shortcuts +import com.topjohnwu.superuser.Shell +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch -class SettingsViewModel : BaseViewModel(), BaseSettingsItem.Handler { +class SettingsViewModel : BaseViewModel() { - val items = createItems() - val extraBindings = bindExtra { - it.put(BR.handler, this) + private val _denyListEnabled = MutableStateFlow(Config.denyList) + val denyListEnabled: StateFlow = _denyListEnabled.asStateFlow() + + val zygiskMismatch get() = Config.zygisk != Info.isZygiskEnabled + + var authenticate: (onSuccess: () -> Unit) -> Unit = { it() } + + fun navigateToDenyList() { + navigateTo(Route.DenyList) } - private fun createItems(): List { - val context = AppContext - val hidden = context.packageName != BuildConfig.APP_PACKAGE_NAME - - // Customization - val list = mutableListOf( - Customization, - Theme, if (LocaleSetting.useLocaleManager) LanguageSystem else Language - ) - if (isRunningAsStub && ShortcutManagerCompat.isRequestPinShortcutSupported(context)) - list.add(AddShortcut) - - // Manager - list.addAll(listOf( - AppSettings, - UpdateChannel, UpdateChannelUrl, DoHToggle, UpdateChecker, DownloadPath, RandNameToggle - )) - if (Info.env.isActive && Const.USER_ID == 0) { - if (hidden) list.add(Restore) else list.add(Hide) - } - - // Magisk - if (Info.env.isActive) { - list.addAll(listOf( - Magisk, - SystemlessHosts - )) - if (Const.Version.atLeast_24_0()) { - list.addAll(listOf(Zygisk, DenyList, DenyListConfig)) - } - } - - // Superuser - if (Info.showSuperUser) { - list.addAll(listOf( - Superuser, - Tapjack, Authentication, AccessMode, MultiuserMode, MountNamespaceMode, - AutomaticResponse, RequestTimeout, SUNotification - )) - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { - // Re-authenticate is not feasible on 8.0+ - list.add(Reauthenticate) - } - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { - // Can hide overlay windows on 12.0+ - list.remove(Tapjack) - } - if (Const.Version.atLeast_30_1()) { - list.add(Restrict) - } - } - - return list + fun requestAddShortcut() { + Shortcuts.addHomeIcon(AppContext) } - override fun onItemPressed(view: View, item: BaseSettingsItem, doAction: () -> Unit) { - when (item) { - DownloadPath -> withExternalRW(doAction) - UpdateChecker -> withPostNotificationPermission(doAction) - Authentication -> AuthEvent(doAction).publish() - AutomaticResponse -> if (Config.suAuth) AuthEvent(doAction).publish() else doAction() - else -> doAction() - } - } - - override fun onItemAction(view: View, item: BaseSettingsItem) { - when (item) { - Theme -> SettingsFragmentDirections.actionSettingsFragmentToThemeFragment().navigate() - LanguageSystem -> view.activity.startActivity(LocaleSetting.localeSettingsIntent) - AddShortcut -> AddHomeIconEvent().publish() - SystemlessHosts -> createHosts() - DenyListConfig -> SettingsFragmentDirections.actionSettingsFragmentToDenyFragment().navigate() - UpdateChannel -> openUrlIfNecessary(view) - is Hide -> viewModelScope.launch { AppMigration.hide(view.activity, item.value) } - Restore -> viewModelScope.launch { AppMigration.restore(view.activity) } - Zygisk -> if (Zygisk.mismatch) SnackbarEvent(R.string.reboot_apply_change).publish() - else -> Unit - } - } - - private fun openUrlIfNecessary(view: View) { - UpdateChannelUrl.refresh() - if (UpdateChannelUrl.isEnabled && UpdateChannelUrl.value.isBlank()) { - UpdateChannelUrl.onPressed(view, this) - } - } - - private fun createHosts() { + fun createHosts() { viewModelScope.launch { RootUtils.addSystemlessHosts() AppContext.toast(R.string.settings_hosts_toast, Toast.LENGTH_SHORT) } } + + fun toggleDenyList(enabled: Boolean) { + _denyListEnabled.value = enabled + val cmd = if (enabled) "enable" else "disable" + Shell.cmd("magisk --denylist $cmd").submit { result -> + if (result.isSuccess) { + Config.denyList = enabled + } else { + _denyListEnabled.value = !enabled + } + } + } + + fun withAuth(action: () -> Unit) = authenticate(action) + + fun notifyZygiskChange() { + if (zygiskMismatch) showSnackbar(R.string.reboot_apply_change) + } } diff --git a/app/apk-ng/src/main/java/com/topjohnwu/magisk/ui/superuser/SuperuserDetailScreen.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/superuser/SuperuserDetailScreen.kt similarity index 100% rename from app/apk-ng/src/main/java/com/topjohnwu/magisk/ui/superuser/SuperuserDetailScreen.kt rename to app/apk/src/main/java/com/topjohnwu/magisk/ui/superuser/SuperuserDetailScreen.kt diff --git a/app/apk-ng/src/main/java/com/topjohnwu/magisk/ui/superuser/SuperuserScreen.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/superuser/SuperuserScreen.kt similarity index 100% rename from app/apk-ng/src/main/java/com/topjohnwu/magisk/ui/superuser/SuperuserScreen.kt rename to app/apk/src/main/java/com/topjohnwu/magisk/ui/superuser/SuperuserScreen.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/superuser/SuperuserViewModel.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/superuser/SuperuserViewModel.kt index 3e0116b2b..e4534df12 100644 --- a/app/apk/src/main/java/com/topjohnwu/magisk/ui/superuser/SuperuserViewModel.kt +++ b/app/apk/src/main/java/com/topjohnwu/magisk/ui/superuser/SuperuserViewModel.kt @@ -3,11 +3,9 @@ package com.topjohnwu.magisk.ui.superuser import android.annotation.SuppressLint import android.content.pm.PackageManager import android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES +import android.graphics.drawable.Drawable import android.os.Process -import androidx.databinding.Bindable -import androidx.databinding.ObservableArrayList import androidx.lifecycle.viewModelScope -import com.topjohnwu.magisk.BR import com.topjohnwu.magisk.arch.AsyncLoadViewModel import com.topjohnwu.magisk.core.AppContext import com.topjohnwu.magisk.core.Config @@ -16,52 +14,66 @@ import com.topjohnwu.magisk.core.R import com.topjohnwu.magisk.core.data.magiskdb.PolicyDao import com.topjohnwu.magisk.core.ktx.getLabel import com.topjohnwu.magisk.core.model.su.SuPolicy -import com.topjohnwu.magisk.core.utils.asText -import com.topjohnwu.magisk.databinding.MergeObservableList -import com.topjohnwu.magisk.databinding.RvItem -import com.topjohnwu.magisk.databinding.bindExtra -import com.topjohnwu.magisk.databinding.diffList -import com.topjohnwu.magisk.databinding.set -import com.topjohnwu.magisk.dialog.SuperuserRevokeDialog -import com.topjohnwu.magisk.events.AuthEvent -import com.topjohnwu.magisk.events.SnackbarEvent -import com.topjohnwu.magisk.view.TextItem +import com.topjohnwu.magisk.core.su.SuEvents import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.FlowPreview +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.debounce +import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.util.Locale +data class PolicyItem( + val policy: SuPolicy, + val packageName: String, + val isSharedUid: Boolean, + val icon: Drawable, + val appName: String, + val policyValue: Int = policy.policy, + val notification: Boolean = policy.notification, + val logging: Boolean = policy.logging, +) { + val title get() = appName + val isEnabled get() = policyValue >= SuPolicy.ALLOW + val isRestricted get() = policyValue == SuPolicy.RESTRICT +} + class SuperuserViewModel( private val db: PolicyDao ) : AsyncLoadViewModel() { - private val itemNoData = TextItem(R.string.superuser_policy_none) + var authenticate: (onSuccess: () -> Unit) -> Unit = { it() } - private val itemsHelpers = ObservableArrayList() - private val itemsPolicies = diffList() - - val items = MergeObservableList() - .insertList(itemsHelpers) - .insertList(itemsPolicies) - val extraBindings = bindExtra { - it.put(BR.listener, this) + init { + @OptIn(FlowPreview::class) + viewModelScope.launch { + SuEvents.policyChanged.debounce(500).collect { reload() } + } } - @get:Bindable - var loading = true - private set(value) = set(value, field, { field = it }, BR.loading) + data class UiState( + val loading: Boolean = true, + val policies: List = emptyList(), + val suRestrict: Boolean = Config.suRestrict, + ) + + private val _uiState = MutableStateFlow(UiState()) + val uiState: StateFlow = _uiState.asStateFlow() @SuppressLint("InlinedApi") override suspend fun doLoadWork() { if (!Info.showSuperUser) { - loading = false + _uiState.update { it.copy(loading = false) } return } - loading = true + _uiState.update { it.copy(loading = true) } withContext(Dispatchers.IO) { db.deleteOutdated() db.delete(AppContext.applicationInfo.uid) - val policies = ArrayList() + val policies = ArrayList() val pm = AppContext.packageManager for (policy in db.fetchAll()) { val pkgs = @@ -74,14 +86,17 @@ class SuperuserViewModel( val map = pkgs.mapNotNull { pkg -> try { val info = pm.getPackageInfo(pkg, MATCH_UNINSTALLED_PACKAGES) - PolicyRvItem( - this@SuperuserViewModel, policy, - info.packageName, - info.sharedUserId != null, - info.applicationInfo?.loadIcon(pm) ?: pm.defaultActivityIcon, - info.applicationInfo?.getLabel(pm) ?: info.packageName + PolicyItem( + policy = policy, + packageName = info.packageName, + isSharedUid = info.sharedUserId != null, + icon = info.applicationInfo?.loadIcon(pm) ?: pm.defaultActivityIcon, + appName = info.applicationInfo?.getLabel(pm) ?: info.packageName, + policyValue = policy.policy, + notification = policy.notification, + logging = policy.logging, ) - } catch (e: PackageManager.NameNotFoundException) { + } catch (_: PackageManager.NameNotFoundException) { null } } @@ -95,86 +110,91 @@ class SuperuserViewModel( { it.appName.lowercase(Locale.ROOT) }, { it.packageName } )) - itemsPolicies.update(policies) - } - if (itemsPolicies.isNotEmpty()) - itemsHelpers.clear() - else if (itemsHelpers.isEmpty()) - itemsHelpers.add(itemNoData) - loading = false - } - - // --- - - fun deletePressed(item: PolicyRvItem) { - fun updateState() = viewModelScope.launch { - db.delete(item.item.uid) - val list = ArrayList(itemsPolicies) - list.removeAll { it.item.uid == item.item.uid } - itemsPolicies.update(list) - if (list.isEmpty() && itemsHelpers.isEmpty()) { - itemsHelpers.add(itemNoData) - } - } - - if (Config.suAuth) { - AuthEvent { updateState() }.publish() - } else { - SuperuserRevokeDialog(item.title) { updateState() }.show() + _uiState.update { it.copy(loading = false, policies = policies, suRestrict = Config.suRestrict) } } } - fun updateNotify(item: PolicyRvItem) { + fun refreshSuRestrict() { + _uiState.update { it.copy(suRestrict = Config.suRestrict) } + } + + val requiresAuth get() = Config.suAuth + + fun performDelete(item: PolicyItem, onDeleted: () -> Unit = {}) { viewModelScope.launch { - db.update(item.item) - val res = when { - item.item.notification -> R.string.su_snack_notif_on - else -> R.string.su_snack_notif_off + db.delete(item.policy.uid) + _uiState.update { state -> + state.copy(policies = state.policies.filter { it.policy.uid != item.policy.uid }) } - itemsPolicies.forEach { - if (it.item.uid == item.item.uid) { - it.notifyPropertyChanged(BR.shouldNotify) - } - } - SnackbarEvent(res.asText(item.appName)).publish() + onDeleted() } } - fun updateLogging(item: PolicyRvItem) { + fun updateNotify(item: PolicyItem) { + val newNotification = !item.notification + item.policy.notification = newNotification viewModelScope.launch { - db.update(item.item) - val res = when { - item.item.logging -> R.string.su_snack_log_on - else -> R.string.su_snack_log_off + db.update(item.policy) + _uiState.update { state -> + state.copy( + policies = state.policies.map { + if (it.policy.uid == item.policy.uid) it.copy(notification = newNotification) else it + } + ) } - itemsPolicies.forEach { - if (it.item.uid == item.item.uid) { - it.notifyPropertyChanged(BR.shouldLog) - } - } - SnackbarEvent(res.asText(item.appName)).publish() + val res = if (newNotification) R.string.su_snack_notif_on else R.string.su_snack_notif_off + showSnackbar(AppContext.getString(res, item.appName)) } } - fun updatePolicy(item: PolicyRvItem, policy: Int) { - val items = itemsPolicies.filter { it.item.uid == item.item.uid } + fun updateLogging(item: PolicyItem) { + val newLogging = !item.logging + item.policy.logging = newLogging + viewModelScope.launch { + db.update(item.policy) + _uiState.update { state -> + state.copy( + policies = state.policies.map { + if (it.policy.uid == item.policy.uid) it.copy(logging = newLogging) else it + } + ) + } + val res = if (newLogging) R.string.su_snack_log_on else R.string.su_snack_log_off + showSnackbar(AppContext.getString(res, item.appName)) + } + } + + fun updatePolicy(item: PolicyItem, newPolicy: Int) { fun updateState() { viewModelScope.launch { - val res = if (policy >= SuPolicy.ALLOW) R.string.su_snack_grant else R.string.su_snack_deny - item.item.policy = policy - db.update(item.item) - items.forEach { - it.notifyPropertyChanged(BR.enabled) - it.notifyPropertyChanged(BR.sliderValue) + item.policy.policy = newPolicy + db.update(item.policy) + _uiState.update { state -> + state.copy( + policies = state.policies.map { + if (it.policy.uid == item.policy.uid) it.copy(policyValue = newPolicy) else it + } + ) } - SnackbarEvent(res.asText(item.appName)).publish() + val res = if (newPolicy >= SuPolicy.ALLOW) R.string.su_snack_grant else R.string.su_snack_deny + showSnackbar(AppContext.getString(res, item.appName)) } } if (Config.suAuth) { - AuthEvent { updateState() }.publish() + authenticate { updateState() } } else { updateState() } } + + fun togglePolicy(item: PolicyItem) { + val newPolicy = if (item.isEnabled) SuPolicy.DENY else SuPolicy.ALLOW + updatePolicy(item, newPolicy) + } + + fun toggleRestrict(item: PolicyItem) { + val newPolicy = if (item.isRestricted) SuPolicy.ALLOW else SuPolicy.RESTRICT + updatePolicy(item, newPolicy) + } } diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/surequest/SuRequestActivity.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/surequest/SuRequestActivity.kt index 9e04c0f53..f164b2689 100644 --- a/app/apk/src/main/java/com/topjohnwu/magisk/ui/surequest/SuRequestActivity.kt +++ b/app/apk/src/main/java/com/topjohnwu/magisk/ui/surequest/SuRequestActivity.kt @@ -1,41 +1,66 @@ package com.topjohnwu.magisk.ui.surequest +import android.content.Context import android.content.Intent import android.content.pm.ActivityInfo -import android.content.res.Resources import android.os.Build import android.os.Bundle +import android.view.View +import android.view.ViewGroup import android.view.Window import android.view.WindowManager +import android.view.accessibility.AccessibilityEvent +import android.view.accessibility.AccessibilityNodeInfo +import android.view.accessibility.AccessibilityNodeProvider +import androidx.activity.ComponentActivity +import androidx.activity.addCallback +import androidx.activity.compose.setContent +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.ui.Modifier +import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.lifecycleScope import com.topjohnwu.magisk.R -import com.topjohnwu.magisk.arch.UIActivity -import com.topjohnwu.magisk.arch.viewModel +import com.topjohnwu.magisk.arch.VMFactory +import com.topjohnwu.magisk.core.base.ActivityExtension import com.topjohnwu.magisk.core.base.UntrackedActivity import com.topjohnwu.magisk.core.su.SuCallbackHandler import com.topjohnwu.magisk.core.su.SuCallbackHandler.REQUEST -import com.topjohnwu.magisk.databinding.ActivityRequestBinding -import com.topjohnwu.magisk.ui.theme.Theme +import com.topjohnwu.magisk.core.wrap +import com.topjohnwu.magisk.ui.MagiskTheme import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext -open class SuRequestActivity : UIActivity(), UntrackedActivity { +class SuRequestActivity : ComponentActivity(), UntrackedActivity { - override val layoutRes: Int = R.layout.activity_request - override val viewModel: SuRequestViewModel by viewModel() + private val extension = ActivityExtension(this) + private val viewModel: SuRequestViewModel by lazy { + ViewModelProvider(this, VMFactory)[SuRequestViewModel::class.java] + } + + override fun attachBaseContext(base: Context) { + super.attachBaseContext(base.wrap()) + } override fun onCreate(savedInstanceState: Bundle?) { - supportRequestWindowFeature(Window.FEATURE_NO_TITLE) + extension.onCreate(savedInstanceState) requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LOCKED + window.requestFeature(Window.FEATURE_NO_TITLE) window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) window.addFlags(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { window.setHideOverlayWindows(true) } - setTheme(Theme.selected.themeRes) + setTheme(R.style.Floating) super.onCreate(savedInstanceState) + onBackPressedDispatcher.addCallback(this) { viewModel.denyPressed() } + viewModel.finishActivity = { finish() } + viewModel.authenticate = { onSuccess -> + extension.withAuthentication { if (it) onSuccess() } + } + if (intent.action == Intent.ACTION_VIEW) { val action = intent.getStringExtra("action") if (action == REQUEST) { @@ -51,19 +76,39 @@ open class SuRequestActivity : UIActivity(), UntrackedAc } else { finish() } + + if (viewModel.useTapjackProtection) { + window.decorView.rootView.accessibilityDelegate = EmptyAccessibilityDelegate + } + + setContent { + MagiskTheme { + Box(modifier = Modifier.fillMaxSize()) { + SuRequestScreen(viewModel = viewModel) + } + } + } } - override fun getTheme(): Resources.Theme { - val theme = super.getTheme() - theme.applyStyle(R.style.Foundation_Floating, true) - return theme - } - - override fun onBackPressed() { - viewModel.denyPressed() + override fun onSaveInstanceState(outState: Bundle) { + super.onSaveInstanceState(outState) + extension.onSaveInstanceState(outState) } override fun finish() { super.finishAndRemoveTask() } + + private object EmptyAccessibilityDelegate : View.AccessibilityDelegate() { + override fun sendAccessibilityEvent(host: View, eventType: Int) {} + override fun performAccessibilityAction(host: View, action: Int, args: Bundle?) = true + override fun sendAccessibilityEventUnchecked(host: View, event: AccessibilityEvent) {} + override fun dispatchPopulateAccessibilityEvent(host: View, event: AccessibilityEvent) = true + override fun onPopulateAccessibilityEvent(host: View, event: AccessibilityEvent) {} + override fun onInitializeAccessibilityEvent(host: View, event: AccessibilityEvent) {} + override fun onInitializeAccessibilityNodeInfo(host: View, info: AccessibilityNodeInfo) {} + override fun addExtraDataToAccessibilityNodeInfo(host: View, info: AccessibilityNodeInfo, extraDataKey: String, arguments: Bundle?) {} + override fun onRequestSendAccessibilityEvent(host: ViewGroup, child: View, event: AccessibilityEvent): Boolean = false + override fun getAccessibilityNodeProvider(host: View): AccessibilityNodeProvider? = null + } } diff --git a/app/apk-ng/src/main/java/com/topjohnwu/magisk/ui/surequest/SuRequestScreen.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/surequest/SuRequestScreen.kt similarity index 100% rename from app/apk-ng/src/main/java/com/topjohnwu/magisk/ui/surequest/SuRequestScreen.kt rename to app/apk/src/main/java/com/topjohnwu/magisk/ui/surequest/SuRequestScreen.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/surequest/SuRequestViewModel.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/surequest/SuRequestViewModel.kt index ed7be09b4..09e721530 100644 --- a/app/apk/src/main/java/com/topjohnwu/magisk/ui/surequest/SuRequestViewModel.kt +++ b/app/apk/src/main/java/com/topjohnwu/magisk/ui/surequest/SuRequestViewModel.kt @@ -1,38 +1,24 @@ package com.topjohnwu.magisk.ui.surequest -import android.annotation.SuppressLint import android.content.Intent import android.content.SharedPreferences -import android.content.res.Resources import android.graphics.drawable.Drawable -import android.os.Bundle import android.os.CountDownTimer -import android.view.MotionEvent -import android.view.View -import android.view.ViewGroup -import android.view.accessibility.AccessibilityEvent -import android.view.accessibility.AccessibilityNodeInfo -import android.view.accessibility.AccessibilityNodeProvider -import android.widget.Toast -import androidx.databinding.Bindable +import androidx.core.content.edit import androidx.lifecycle.viewModelScope -import com.topjohnwu.magisk.BR import com.topjohnwu.magisk.arch.BaseViewModel import com.topjohnwu.magisk.core.AppContext import com.topjohnwu.magisk.core.Config -import com.topjohnwu.magisk.core.R import com.topjohnwu.magisk.core.data.magiskdb.PolicyDao import com.topjohnwu.magisk.core.ktx.getLabel -import com.topjohnwu.magisk.core.ktx.toast import com.topjohnwu.magisk.core.model.su.SuPolicy.Companion.ALLOW import com.topjohnwu.magisk.core.model.su.SuPolicy.Companion.DENY import com.topjohnwu.magisk.core.su.SuRequestHandler -import com.topjohnwu.magisk.core.utils.TextHolder -import com.topjohnwu.magisk.databinding.set -import com.topjohnwu.magisk.events.AuthEvent -import com.topjohnwu.magisk.events.DieEvent -import com.topjohnwu.magisk.events.ShowUIEvent import kotlinx.coroutines.Dispatchers +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 java.util.concurrent.TimeUnit.SECONDS @@ -41,43 +27,39 @@ class SuRequestViewModel( private val timeoutPrefs: SharedPreferences ) : BaseViewModel() { - lateinit var icon: Drawable - lateinit var title: String - lateinit var packageName: String + data class UiState( + val showUi: Boolean = false, + val icon: Drawable? = null, + val title: String = "", + val packageName: String = "", + val isSharedUid: Boolean = false, + val selectedItemPosition: Int = 0, + val grantEnabled: Boolean = false, + val denyCountdown: Int = 0, + val useTapjackProtection: Boolean = false, + ) - @get:Bindable - val denyText = DenyText() + private val _uiState = MutableStateFlow(UiState()) + val uiState: StateFlow = _uiState.asStateFlow() - @get:Bindable - var selectedItemPosition = 0 - set(value) = set(value, field, { field = it }, BR.selectedItemPosition) + var authenticate: (onSuccess: () -> Unit) -> Unit = { it() } + var finishActivity: () -> Unit = {} - @get:Bindable - var grantEnabled = false - set(value) = set(value, field, { field = it }, BR.grantEnabled) - - @SuppressLint("ClickableViewAccessibility") - val grantTouchListener = View.OnTouchListener { _: View, event: MotionEvent -> - // Filter obscured touches by consuming them. - if (event.flags and MotionEvent.FLAG_WINDOW_IS_OBSCURED != 0 - || event.flags and MotionEvent.FLAG_WINDOW_IS_PARTIALLY_OBSCURED != 0) { - if (event.action == MotionEvent.ACTION_UP) { - AppContext.toast(R.string.touch_filtered_warning, Toast.LENGTH_SHORT) - } - return@OnTouchListener Config.suTapjack - } - false - } + val useTapjackProtection get() = _uiState.value.useTapjackProtection private val handler = SuRequestHandler(AppContext.packageManager, policyDB) private val millis = SECONDS.toMillis(Config.suDefaultTimeout.toLong()) private var timer = SuTimer(millis, 1000) private var initialized = false + fun setSelectedItemPosition(position: Int) { + _uiState.update { it.copy(selectedItemPosition = position) } + } + fun grantPressed() { cancelTimer() if (Config.suAuth) { - AuthEvent { respond(ALLOW) }.publish() + authenticate { respond(ALLOW) } } else { respond(ALLOW) } @@ -87,9 +69,8 @@ class SuRequestViewModel( respond(DENY) } - fun spinnerTouched(): Boolean { + fun spinnerTouched() { cancelTimer() - return false } fun handleRequest(intent: Intent) { @@ -97,7 +78,7 @@ class SuRequestViewModel( if (handler.start(intent)) showDialog() else - DieEvent().publish() + finishActivity() } } @@ -106,50 +87,54 @@ class SuRequestViewModel( val info = handler.pkgInfo val app = info.applicationInfo + val isSharedUid = info.sharedUserId != null + val icon: Drawable? + val title: String + val packageName: String + if (app == null) { - // The request is not coming from an app process, and the UID is a - // shared UID. We have no way to know where this request comes from. icon = pm.defaultActivityIcon - title = "[SharedUID] ${info.sharedUserId}" + title = info.sharedUserId.toString() packageName = info.sharedUserId.toString() } else { - val prefix = if (info.sharedUserId == null) "" else "[SharedUID] " icon = app.loadIcon(pm) - title = "$prefix${app.getLabel(pm)}" + title = app.getLabel(pm) packageName = info.packageName } - selectedItemPosition = timeoutPrefs.getInt(packageName, 0) - - // Set timer + val selectedPos = timeoutPrefs.getInt(packageName, 0) + _uiState.update { + it.copy( + showUi = true, + icon = icon, + title = title, + packageName = packageName, + isSharedUid = isSharedUid, + selectedItemPosition = selectedPos, + useTapjackProtection = Config.suTapjack, + ) + } timer.start() - - // Actually show the UI - ShowUIEvent(if (Config.suTapjack) EmptyAccessibilityDelegate else null).publish() initialized = true } private fun respond(action: Int) { - if (!initialized) { - // ignore the response until showDialog done - return - } - + if (!initialized) return timer.cancel() - val pos = selectedItemPosition - timeoutPrefs.edit().putInt(packageName, pos).apply() + val pos = _uiState.value.selectedItemPosition + val pkg = _uiState.value.packageName + timeoutPrefs.edit { putInt(pkg, pos) } viewModelScope.launch { handler.respond(action, Config.Value.TIMEOUT_LIST[pos]) - // Kill activity after response - DieEvent().publish() + finishActivity() } } private fun cancelTimer() { timer.cancel() - denyText.seconds = 0 + _uiState.update { it.copy(denyCountdown = 0) } } private inner class SuTimer( @@ -158,42 +143,17 @@ class SuRequestViewModel( ) : CountDownTimer(millis, interval) { override fun onTick(remains: Long) { - if (!grantEnabled && remains <= millis - 1000) { - grantEnabled = true + _uiState.update { + it.copy( + grantEnabled = it.grantEnabled || remains <= millis - 1000, + denyCountdown = (remains / 1000).toInt() + 1 + ) } - denyText.seconds = (remains / 1000).toInt() + 1 } override fun onFinish() { - denyText.seconds = 0 + _uiState.update { it.copy(denyCountdown = 0) } respond(DENY) } - - } - - inner class DenyText : TextHolder() { - var seconds = 0 - set(value) = set(value, field, { field = it }, BR.denyText) - - override fun getText(resources: Resources): String { - return if (seconds != 0) - "${resources.getString(R.string.deny)} ($seconds)" - else - resources.getString(R.string.deny) - } - } - - // Invisible for accessibility services - object EmptyAccessibilityDelegate : View.AccessibilityDelegate() { - override fun sendAccessibilityEvent(host: View, eventType: Int) {} - override fun performAccessibilityAction(host: View, action: Int, args: Bundle?) = true - override fun sendAccessibilityEventUnchecked(host: View, event: AccessibilityEvent) {} - override fun dispatchPopulateAccessibilityEvent(host: View, event: AccessibilityEvent) = true - override fun onPopulateAccessibilityEvent(host: View, event: AccessibilityEvent) {} - override fun onInitializeAccessibilityEvent(host: View, event: AccessibilityEvent) {} - override fun onInitializeAccessibilityNodeInfo(host: View, info: AccessibilityNodeInfo) {} - override fun addExtraDataToAccessibilityNodeInfo(host: View, info: AccessibilityNodeInfo, extraDataKey: String, arguments: Bundle?) {} - override fun onRequestSendAccessibilityEvent(host: ViewGroup, child: View, event: AccessibilityEvent): Boolean = false - override fun getAccessibilityNodeProvider(host: View): AccessibilityNodeProvider? = null } } diff --git a/app/apk-ng/src/main/java/com/topjohnwu/magisk/ui/terminal/TerminalRenderer.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/terminal/TerminalRenderer.kt similarity index 100% rename from app/apk-ng/src/main/java/com/topjohnwu/magisk/ui/terminal/TerminalRenderer.kt rename to app/apk/src/main/java/com/topjohnwu/magisk/ui/terminal/TerminalRenderer.kt diff --git a/app/apk-ng/src/main/java/com/topjohnwu/magisk/ui/terminal/TerminalScreen.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/terminal/TerminalScreen.kt similarity index 100% rename from app/apk-ng/src/main/java/com/topjohnwu/magisk/ui/terminal/TerminalScreen.kt rename to app/apk/src/main/java/com/topjohnwu/magisk/ui/terminal/TerminalScreen.kt diff --git a/app/apk-ng/src/main/java/com/topjohnwu/magisk/utils/Compose.kt b/app/apk/src/main/java/com/topjohnwu/magisk/utils/Compose.kt similarity index 100% rename from app/apk-ng/src/main/java/com/topjohnwu/magisk/utils/Compose.kt rename to app/apk/src/main/java/com/topjohnwu/magisk/utils/Compose.kt diff --git a/app/apk-ng/src/main/java/com/topjohnwu/magisk/utils/FlowUtils.kt b/app/apk/src/main/java/com/topjohnwu/magisk/utils/FlowUtils.kt similarity index 100% rename from app/apk-ng/src/main/java/com/topjohnwu/magisk/utils/FlowUtils.kt rename to app/apk/src/main/java/com/topjohnwu/magisk/utils/FlowUtils.kt diff --git a/app/apk-ng/src/main/res/drawable/ic_bug.xml b/app/apk/src/main/res/drawable/ic_bug.xml similarity index 100% rename from app/apk-ng/src/main/res/drawable/ic_bug.xml rename to app/apk/src/main/res/drawable/ic_bug.xml diff --git a/app/apk-ng/src/main/res/drawable/ic_download.xml b/app/apk/src/main/res/drawable/ic_download.xml similarity index 100% rename from app/apk-ng/src/main/res/drawable/ic_download.xml rename to app/apk/src/main/res/drawable/ic_download.xml diff --git a/app/apk-ng/src/main/res/drawable/ic_home.xml b/app/apk/src/main/res/drawable/ic_home.xml similarity index 100% rename from app/apk-ng/src/main/res/drawable/ic_home.xml rename to app/apk/src/main/res/drawable/ic_home.xml diff --git a/app/apk/src/main/res/drawable/ic_manager.xml b/app/apk/src/main/res/drawable/ic_manager.xml index 001df45e3..3a918c5f1 100644 --- a/app/apk/src/main/res/drawable/ic_manager.xml +++ b/app/apk/src/main/res/drawable/ic_manager.xml @@ -4,6 +4,6 @@ android:viewportWidth="24" android:viewportHeight="24"> diff --git a/app/apk-ng/src/main/res/drawable/ic_module.xml b/app/apk/src/main/res/drawable/ic_module.xml similarity index 100% rename from app/apk-ng/src/main/res/drawable/ic_module.xml rename to app/apk/src/main/res/drawable/ic_module.xml diff --git a/app/apk/src/main/res/drawable/ic_restart.xml b/app/apk/src/main/res/drawable/ic_restart.xml index b4f8eaee9..3151a7b21 100644 --- a/app/apk/src/main/res/drawable/ic_restart.xml +++ b/app/apk/src/main/res/drawable/ic_restart.xml @@ -5,6 +5,6 @@ android:viewportWidth="24" android:viewportHeight="24"> diff --git a/app/apk-ng/src/main/res/drawable/ic_save.xml b/app/apk/src/main/res/drawable/ic_save.xml similarity index 100% rename from app/apk-ng/src/main/res/drawable/ic_save.xml rename to app/apk/src/main/res/drawable/ic_save.xml diff --git a/app/apk-ng/src/main/res/drawable/ic_settings.xml b/app/apk/src/main/res/drawable/ic_settings.xml similarity index 100% rename from app/apk-ng/src/main/res/drawable/ic_settings.xml rename to app/apk/src/main/res/drawable/ic_settings.xml diff --git a/app/apk/src/main/res/values/themes.xml b/app/apk/src/main/res/values/themes.xml index 09078e38e..3c3dbc0ff 100644 --- a/app/apk/src/main/res/values/themes.xml +++ b/app/apk/src/main/res/values/themes.xml @@ -1,32 +1,14 @@ - - - - -