From 4d7c9e5ef48046f97c6491b8327ea9ebd8032d38 Mon Sep 17 00:00:00 2001 From: Jakub Mendyka Date: Mon, 23 Nov 2026 15:47:13 +0100 Subject: [PATCH 01/12] Move app view models to a shared module Prepare for a second frontend (Wear OS) by moving the non-UI parts of the app out of :apk into a new :shared Android library: view models, the view model factory, navigation routes, the terminal emulator, flash helpers and the small UI state types they depend on. AppSortBy and ThemeState are split out of their Compose files so :shared does not need Material 3. FlashUtils now targets the component of the app's own launch intent instead of referencing MainActivity, which stays in :apk. Packages and class names are unchanged and there is no change in behavior. Assisted-by: Claude Opus 5.5 --- app/apk/build.gradle.kts | 1 + .../com/topjohnwu/magisk/ui/MagiskTheme.kt | 8 ------ .../magisk/ui/component/AppSortFilter.kt | 8 ------ app/gradle/libs.versions.toml | 4 +++ app/settings.gradle.kts | 2 +- app/shared/build.gradle.kts | 27 +++++++++++++++++++ .../magisk/arch/AsyncLoadViewModel.kt | 0 .../topjohnwu/magisk/arch/BaseViewModel.kt | 0 .../topjohnwu/magisk/arch/ViewModelFactory.kt | 0 .../magisk/terminal/TerminalBuffer.kt | 0 .../magisk/terminal/TerminalEmulator.kt | 0 .../magisk/terminal/TerminalProcess.kt | 0 .../topjohnwu/magisk/terminal/TerminalRow.kt | 0 .../magisk/terminal/TerminalStyle.kt | 0 .../com/topjohnwu/magisk/terminal/WcWidth.kt | 0 .../com/topjohnwu/magisk/ui/ThemeState.kt | 10 +++++++ .../magisk/ui/component/AppSortBy.kt | 11 ++++++++ .../magisk/ui/deny/AppProcessInfo.kt | 0 .../magisk/ui/deny/DenyListViewModel.kt | 0 .../topjohnwu/magisk/ui/flash/FlashUtils.kt | 7 +++-- .../magisk/ui/flash/FlashViewModel.kt | 0 .../topjohnwu/magisk/ui/home/HomeViewModel.kt | 0 .../magisk/ui/install/InstallViewModel.kt | 0 .../topjohnwu/magisk/ui/log/LogViewModel.kt | 0 .../magisk/ui/log/MagiskLogParser.kt | 0 .../magisk/ui/module/ActionViewModel.kt | 0 .../magisk/ui/module/ModuleViewModel.kt | 0 .../topjohnwu/magisk/ui/navigation/Routes.kt | 0 .../magisk/ui/settings/SettingsUiState.kt | 0 .../magisk/ui/settings/SettingsViewModel.kt | 0 .../ui/superuser/SuperuserGrantViewModel.kt | 0 .../magisk/ui/superuser/SuperuserViewModel.kt | 0 .../com/topjohnwu/magisk/utils/FlowUtils.kt | 0 33 files changed, 57 insertions(+), 21 deletions(-) create mode 100644 app/shared/build.gradle.kts rename app/{apk => shared}/src/main/java/com/topjohnwu/magisk/arch/AsyncLoadViewModel.kt (100%) rename app/{apk => shared}/src/main/java/com/topjohnwu/magisk/arch/BaseViewModel.kt (100%) rename app/{apk => shared}/src/main/java/com/topjohnwu/magisk/arch/ViewModelFactory.kt (100%) rename app/{apk => shared}/src/main/java/com/topjohnwu/magisk/terminal/TerminalBuffer.kt (100%) rename app/{apk => shared}/src/main/java/com/topjohnwu/magisk/terminal/TerminalEmulator.kt (100%) rename app/{apk => shared}/src/main/java/com/topjohnwu/magisk/terminal/TerminalProcess.kt (100%) rename app/{apk => shared}/src/main/java/com/topjohnwu/magisk/terminal/TerminalRow.kt (100%) rename app/{apk => shared}/src/main/java/com/topjohnwu/magisk/terminal/TerminalStyle.kt (100%) rename app/{apk => shared}/src/main/java/com/topjohnwu/magisk/terminal/WcWidth.kt (100%) create mode 100644 app/shared/src/main/java/com/topjohnwu/magisk/ui/ThemeState.kt create mode 100644 app/shared/src/main/java/com/topjohnwu/magisk/ui/component/AppSortBy.kt rename app/{apk => shared}/src/main/java/com/topjohnwu/magisk/ui/deny/AppProcessInfo.kt (100%) rename app/{apk => shared}/src/main/java/com/topjohnwu/magisk/ui/deny/DenyListViewModel.kt (100%) rename app/{apk => shared}/src/main/java/com/topjohnwu/magisk/ui/flash/FlashUtils.kt (88%) rename app/{apk => shared}/src/main/java/com/topjohnwu/magisk/ui/flash/FlashViewModel.kt (100%) rename app/{apk => shared}/src/main/java/com/topjohnwu/magisk/ui/home/HomeViewModel.kt (100%) rename app/{apk => shared}/src/main/java/com/topjohnwu/magisk/ui/install/InstallViewModel.kt (100%) rename app/{apk => shared}/src/main/java/com/topjohnwu/magisk/ui/log/LogViewModel.kt (100%) rename app/{apk => shared}/src/main/java/com/topjohnwu/magisk/ui/log/MagiskLogParser.kt (100%) rename app/{apk => shared}/src/main/java/com/topjohnwu/magisk/ui/module/ActionViewModel.kt (100%) rename app/{apk => shared}/src/main/java/com/topjohnwu/magisk/ui/module/ModuleViewModel.kt (100%) rename app/{apk => shared}/src/main/java/com/topjohnwu/magisk/ui/navigation/Routes.kt (100%) rename app/{apk => shared}/src/main/java/com/topjohnwu/magisk/ui/settings/SettingsUiState.kt (100%) rename app/{apk => shared}/src/main/java/com/topjohnwu/magisk/ui/settings/SettingsViewModel.kt (100%) rename app/{apk => shared}/src/main/java/com/topjohnwu/magisk/ui/superuser/SuperuserGrantViewModel.kt (100%) rename app/{apk => shared}/src/main/java/com/topjohnwu/magisk/ui/superuser/SuperuserViewModel.kt (100%) rename app/{apk => shared}/src/main/java/com/topjohnwu/magisk/utils/FlowUtils.kt (100%) diff --git a/app/apk/build.gradle.kts b/app/apk/build.gradle.kts index 109c26e356473..5916e33496689 100644 --- a/app/apk/build.gradle.kts +++ b/app/apk/build.gradle.kts @@ -35,6 +35,7 @@ android { dependencies { implementation(project(":core")) + implementation(project(":shared")) coreLibraryDesugaring(libs.jdk.libs) // Compose diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/MagiskTheme.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/MagiskTheme.kt index c1485cd75524b..0ecc63b47e16d 100644 --- a/app/apk/src/main/java/com/topjohnwu/magisk/ui/MagiskTheme.kt +++ b/app/apk/src/main/java/com/topjohnwu/magisk/ui/MagiskTheme.kt @@ -18,9 +18,6 @@ import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableIntStateOf -import androidx.compose.runtime.setValue import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext @@ -32,7 +29,6 @@ import com.google.android.material.color.utilities.DynamicColor import com.google.android.material.color.utilities.Hct import com.google.android.material.color.utilities.MaterialDynamicColors import com.google.android.material.color.utilities.SchemeTonalSpot -import com.topjohnwu.magisk.core.Config import com.topjohnwu.magisk.core.model.ColorMode @SuppressLint("RestrictedApi") @@ -99,10 +95,6 @@ fun dynamicColorScheme( val MagiskAccentColor = Color(0xFF00AF9C) -object ThemeState { - var colorMode by mutableIntStateOf(Config.colorMode) -} - // Same values as androidx.activity's internal DefaultLightScrim / DefaultDarkScrim private val LightScrim = android.graphics.Color.argb(0xe6, 0xFF, 0xFF, 0xFF) private val DarkScrim = android.graphics.Color.argb(0x80, 0x1b, 0x1b, 0x1b) diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/component/AppSortFilter.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/component/AppSortFilter.kt index 18a239c154d27..32bf671be208a 100644 --- a/app/apk/src/main/java/com/topjohnwu/magisk/ui/component/AppSortFilter.kt +++ b/app/apk/src/main/java/com/topjohnwu/magisk/ui/component/AppSortFilter.kt @@ -1,6 +1,5 @@ package com.topjohnwu.magisk.ui.component -import androidx.annotation.StringRes import androidx.compose.foundation.layout.Box import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.Sort @@ -22,13 +21,6 @@ import androidx.compose.ui.unit.DpOffset import androidx.compose.ui.unit.dp import com.topjohnwu.magisk.core.R as CoreR -enum class AppSortBy(@StringRes val labelRes: Int) { - NAME(CoreR.string.sort_by_name), - PACKAGE_NAME(CoreR.string.sort_by_package_name), - INSTALL_TIME(CoreR.string.sort_by_install_time), - UPDATE_TIME(CoreR.string.sort_by_update_time); -} - @Composable fun AppSortFilterActions( sortBy: AppSortBy, diff --git a/app/gradle/libs.versions.toml b/app/gradle/libs.versions.toml index 0c54f8e7d01b1..1269ce1124879 100644 --- a/app/gradle/libs.versions.toml +++ b/app/gradle/libs.versions.toml @@ -51,6 +51,7 @@ libsu-nio = { module = "com.github.topjohnwu.libsu:nio", version.ref = "libsu" } # Compose activity-compose = { module = "androidx.activity:activity-compose", version = "1.13.0" } accompanist-drawablepainter = { module = "com.google.accompanist:accompanist-drawablepainter", version = "0.37.3" } +compose-runtime = { module = "androidx.compose.runtime:runtime", version.ref = "compose-ui" } compose-ui = { module = "androidx.compose.ui:ui", version.ref = "compose-ui" } compose-animation = { module = "androidx.compose.animation:animation", version.ref = "compose-ui" } compose-foundation = { module = "androidx.compose.foundation:foundation", version.ref = "compose-ui" } @@ -60,6 +61,9 @@ compose-material3 = { module = "androidx.compose.material3:material3", version.r compose-material3-adaptive-navigation-suite = { module = "androidx.compose.material3:material3-adaptive-navigation-suite", version.ref = "compose-m3" } window-core = { module = "androidx.window:window-core", version = "1.5.0" } compose-material-icons-extended = { module = "androidx.compose.material:material-icons-extended", version = "1.7.8" } +lifecycle-livedata-core = { module = "androidx.lifecycle:lifecycle-livedata-core", version.ref = "lifecycle" } +lifecycle-viewmodel = { module = "androidx.lifecycle:lifecycle-viewmodel", version.ref = "lifecycle" } +lifecycle-viewmodel-savedstate = { module = "androidx.lifecycle:lifecycle-viewmodel-savedstate", version.ref = "lifecycle" } lifecycle-runtime-compose = { module = "androidx.lifecycle:lifecycle-runtime-compose", version.ref = "lifecycle" } lifecycle-viewmodel-compose = { module = "androidx.lifecycle:lifecycle-viewmodel-compose", version.ref = "lifecycle" } lifecycle-viewmodel-navigation3 = { module = "androidx.lifecycle:lifecycle-viewmodel-navigation3", version.ref = "lifecycle" } diff --git a/app/settings.gradle.kts b/app/settings.gradle.kts index d456d615b03d3..da8293977c791 100644 --- a/app/settings.gradle.kts +++ b/app/settings.gradle.kts @@ -31,4 +31,4 @@ pluginManagement { } rootProject.name = "Magisk" -include(":apk", ":core", ":test") +include(":apk", ":core", ":shared", ":test") diff --git a/app/shared/build.gradle.kts b/app/shared/build.gradle.kts new file mode 100644 index 0000000000000..6d8bf8c765080 --- /dev/null +++ b/app/shared/build.gradle.kts @@ -0,0 +1,27 @@ +plugins { + alias(libs.plugins.android.library) + kotlin("plugin.parcelize") + alias(libs.plugins.compose.compiler) +} + +setupCommon() + +android { + namespace = "com.topjohnwu.magisk.shared" + + compileOptions { + isCoreLibraryDesugaringEnabled = true + } +} + +dependencies { + api(project(":core")) + coreLibraryDesugaring(libs.jdk.libs) + + api(libs.lifecycle.viewmodel) + api(libs.lifecycle.viewmodel.savedstate) + api(libs.lifecycle.livedata.core) + api(libs.compose.runtime) + api(libs.navigation3.runtime) + implementation(libs.core.ktx) +} diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/arch/AsyncLoadViewModel.kt b/app/shared/src/main/java/com/topjohnwu/magisk/arch/AsyncLoadViewModel.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/arch/AsyncLoadViewModel.kt rename to app/shared/src/main/java/com/topjohnwu/magisk/arch/AsyncLoadViewModel.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/arch/BaseViewModel.kt b/app/shared/src/main/java/com/topjohnwu/magisk/arch/BaseViewModel.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/arch/BaseViewModel.kt rename to app/shared/src/main/java/com/topjohnwu/magisk/arch/BaseViewModel.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/arch/ViewModelFactory.kt b/app/shared/src/main/java/com/topjohnwu/magisk/arch/ViewModelFactory.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/arch/ViewModelFactory.kt rename to app/shared/src/main/java/com/topjohnwu/magisk/arch/ViewModelFactory.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/terminal/TerminalBuffer.kt b/app/shared/src/main/java/com/topjohnwu/magisk/terminal/TerminalBuffer.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/terminal/TerminalBuffer.kt rename to app/shared/src/main/java/com/topjohnwu/magisk/terminal/TerminalBuffer.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/terminal/TerminalEmulator.kt b/app/shared/src/main/java/com/topjohnwu/magisk/terminal/TerminalEmulator.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/terminal/TerminalEmulator.kt rename to app/shared/src/main/java/com/topjohnwu/magisk/terminal/TerminalEmulator.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/terminal/TerminalProcess.kt b/app/shared/src/main/java/com/topjohnwu/magisk/terminal/TerminalProcess.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/terminal/TerminalProcess.kt rename to app/shared/src/main/java/com/topjohnwu/magisk/terminal/TerminalProcess.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/terminal/TerminalRow.kt b/app/shared/src/main/java/com/topjohnwu/magisk/terminal/TerminalRow.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/terminal/TerminalRow.kt rename to app/shared/src/main/java/com/topjohnwu/magisk/terminal/TerminalRow.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/terminal/TerminalStyle.kt b/app/shared/src/main/java/com/topjohnwu/magisk/terminal/TerminalStyle.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/terminal/TerminalStyle.kt rename to app/shared/src/main/java/com/topjohnwu/magisk/terminal/TerminalStyle.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/terminal/WcWidth.kt b/app/shared/src/main/java/com/topjohnwu/magisk/terminal/WcWidth.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/terminal/WcWidth.kt rename to app/shared/src/main/java/com/topjohnwu/magisk/terminal/WcWidth.kt diff --git a/app/shared/src/main/java/com/topjohnwu/magisk/ui/ThemeState.kt b/app/shared/src/main/java/com/topjohnwu/magisk/ui/ThemeState.kt new file mode 100644 index 0000000000000..b1a1e1dbe2042 --- /dev/null +++ b/app/shared/src/main/java/com/topjohnwu/magisk/ui/ThemeState.kt @@ -0,0 +1,10 @@ +package com.topjohnwu.magisk.ui + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.setValue +import com.topjohnwu.magisk.core.Config + +object ThemeState { + var colorMode by mutableIntStateOf(Config.colorMode) +} diff --git a/app/shared/src/main/java/com/topjohnwu/magisk/ui/component/AppSortBy.kt b/app/shared/src/main/java/com/topjohnwu/magisk/ui/component/AppSortBy.kt new file mode 100644 index 0000000000000..7a95c709ac9d9 --- /dev/null +++ b/app/shared/src/main/java/com/topjohnwu/magisk/ui/component/AppSortBy.kt @@ -0,0 +1,11 @@ +package com.topjohnwu.magisk.ui.component + +import androidx.annotation.StringRes +import com.topjohnwu.magisk.core.R as CoreR + +enum class AppSortBy(@StringRes val labelRes: Int) { + NAME(CoreR.string.sort_by_name), + PACKAGE_NAME(CoreR.string.sort_by_package_name), + INSTALL_TIME(CoreR.string.sort_by_install_time), + UPDATE_TIME(CoreR.string.sort_by_update_time); +} diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/deny/AppProcessInfo.kt b/app/shared/src/main/java/com/topjohnwu/magisk/ui/deny/AppProcessInfo.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/ui/deny/AppProcessInfo.kt rename to app/shared/src/main/java/com/topjohnwu/magisk/ui/deny/AppProcessInfo.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/deny/DenyListViewModel.kt b/app/shared/src/main/java/com/topjohnwu/magisk/ui/deny/DenyListViewModel.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/ui/deny/DenyListViewModel.kt rename to app/shared/src/main/java/com/topjohnwu/magisk/ui/deny/DenyListViewModel.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/flash/FlashUtils.kt b/app/shared/src/main/java/com/topjohnwu/magisk/ui/flash/FlashUtils.kt similarity index 88% rename from app/apk/src/main/java/com/topjohnwu/magisk/ui/flash/FlashUtils.kt rename to app/shared/src/main/java/com/topjohnwu/magisk/ui/flash/FlashUtils.kt index 7bf5a45ad670f..269cdf3eb7c9a 100644 --- a/app/apk/src/main/java/com/topjohnwu/magisk/ui/flash/FlashUtils.kt +++ b/app/shared/src/main/java/com/topjohnwu/magisk/ui/flash/FlashUtils.kt @@ -5,8 +5,7 @@ import android.content.Context import android.content.Intent import android.net.Uri import com.topjohnwu.magisk.core.Const -import com.topjohnwu.magisk.core.cmp -import com.topjohnwu.magisk.ui.MainActivity +import com.topjohnwu.magisk.core.ktx.selfLaunchIntent import java.util.UUID object FlashUtils { @@ -28,8 +27,8 @@ object FlashUtils { * own one-shot PendingIntent. */ fun installIntent(context: Context, file: Uri, requestCode: Int): PendingIntent { - val intent = Intent(context, MainActivity::class.java).apply { - component = MainActivity::class.java.cmp(context.packageName) + val intent = Intent().apply { + component = context.selfLaunchIntent().component action = INTENT_FLASH putExtra(EXTRA_FLASH_ACTION, Const.Value.FLASH_ZIP) putExtra(EXTRA_FLASH_URI, file.toString()) diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/flash/FlashViewModel.kt b/app/shared/src/main/java/com/topjohnwu/magisk/ui/flash/FlashViewModel.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/ui/flash/FlashViewModel.kt rename to app/shared/src/main/java/com/topjohnwu/magisk/ui/flash/FlashViewModel.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/home/HomeViewModel.kt b/app/shared/src/main/java/com/topjohnwu/magisk/ui/home/HomeViewModel.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/ui/home/HomeViewModel.kt rename to app/shared/src/main/java/com/topjohnwu/magisk/ui/home/HomeViewModel.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/install/InstallViewModel.kt b/app/shared/src/main/java/com/topjohnwu/magisk/ui/install/InstallViewModel.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/ui/install/InstallViewModel.kt rename to app/shared/src/main/java/com/topjohnwu/magisk/ui/install/InstallViewModel.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/log/LogViewModel.kt b/app/shared/src/main/java/com/topjohnwu/magisk/ui/log/LogViewModel.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/ui/log/LogViewModel.kt rename to app/shared/src/main/java/com/topjohnwu/magisk/ui/log/LogViewModel.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/log/MagiskLogParser.kt b/app/shared/src/main/java/com/topjohnwu/magisk/ui/log/MagiskLogParser.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/ui/log/MagiskLogParser.kt rename to app/shared/src/main/java/com/topjohnwu/magisk/ui/log/MagiskLogParser.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/module/ActionViewModel.kt b/app/shared/src/main/java/com/topjohnwu/magisk/ui/module/ActionViewModel.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/ui/module/ActionViewModel.kt rename to app/shared/src/main/java/com/topjohnwu/magisk/ui/module/ActionViewModel.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/module/ModuleViewModel.kt b/app/shared/src/main/java/com/topjohnwu/magisk/ui/module/ModuleViewModel.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/ui/module/ModuleViewModel.kt rename to app/shared/src/main/java/com/topjohnwu/magisk/ui/module/ModuleViewModel.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/navigation/Routes.kt b/app/shared/src/main/java/com/topjohnwu/magisk/ui/navigation/Routes.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/ui/navigation/Routes.kt rename to app/shared/src/main/java/com/topjohnwu/magisk/ui/navigation/Routes.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/settings/SettingsUiState.kt b/app/shared/src/main/java/com/topjohnwu/magisk/ui/settings/SettingsUiState.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/ui/settings/SettingsUiState.kt rename to app/shared/src/main/java/com/topjohnwu/magisk/ui/settings/SettingsUiState.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/settings/SettingsViewModel.kt b/app/shared/src/main/java/com/topjohnwu/magisk/ui/settings/SettingsViewModel.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/ui/settings/SettingsViewModel.kt rename to app/shared/src/main/java/com/topjohnwu/magisk/ui/settings/SettingsViewModel.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/superuser/SuperuserGrantViewModel.kt b/app/shared/src/main/java/com/topjohnwu/magisk/ui/superuser/SuperuserGrantViewModel.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/ui/superuser/SuperuserGrantViewModel.kt rename to app/shared/src/main/java/com/topjohnwu/magisk/ui/superuser/SuperuserGrantViewModel.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/superuser/SuperuserViewModel.kt b/app/shared/src/main/java/com/topjohnwu/magisk/ui/superuser/SuperuserViewModel.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/ui/superuser/SuperuserViewModel.kt rename to app/shared/src/main/java/com/topjohnwu/magisk/ui/superuser/SuperuserViewModel.kt diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/utils/FlowUtils.kt b/app/shared/src/main/java/com/topjohnwu/magisk/utils/FlowUtils.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/utils/FlowUtils.kt rename to app/shared/src/main/java/com/topjohnwu/magisk/utils/FlowUtils.kt From 5694911f8af8339f0f4ee71b2a97fe7520c6594a Mon Sep 17 00:00:00 2001 From: Jakub Mendyka Date: Fri, 27 Nov 2026 04:06:37 +0100 Subject: [PATCH 02/12] Add a Wear OS UI module Add :wear, a Wear OS frontend for the Magisk app built on the Wear Compose Material 3 libraries. It is a library of :apk, so a single APK serves both phones and watches; it shares :core and :shared with the phone UI. The main activity stays the only activity. Where useWearUi() is true (a watch on API 25 or later, the minimum of Wear Compose), it hands its content to WearUi instead of setting up the phone UI, and keeps running the common splash and initialization sequence. The check matches the watch-v25 resource qualifier, which replaces the activity theme and the splash background on those devices. Since Wear Compose is never used below API 25, :apk overrides the minimum SDK of those libraries. For now the Wear UI only shows the time on a black screen; the screens follow in later changes. JUnit is added to the version catalog for the module's JVM unit tests. Assisted-by: Claude Opus 5.5 --- app/apk/build.gradle.kts | 1 + app/apk/src/main/AndroidManifest.xml | 4 ++ .../com/topjohnwu/magisk/ui/MainActivity.kt | 11 ++++- app/gradle/libs.versions.toml | 6 +++ app/settings.gradle.kts | 2 +- app/wear/build.gradle.kts | 39 +++++++++++++++ app/wear/src/main/AndroidManifest.xml | 2 + .../java/com/topjohnwu/magisk/wear/WearUi.kt | 47 +++++++++++++++++++ .../src/main/res/values-watch-v25/colors.xml | 6 +++ .../src/main/res/values-watch-v25/themes.xml | 9 ++++ 10 files changed, 125 insertions(+), 2 deletions(-) create mode 100644 app/wear/build.gradle.kts create mode 100644 app/wear/src/main/AndroidManifest.xml create mode 100644 app/wear/src/main/java/com/topjohnwu/magisk/wear/WearUi.kt create mode 100644 app/wear/src/main/res/values-watch-v25/colors.xml create mode 100644 app/wear/src/main/res/values-watch-v25/themes.xml diff --git a/app/apk/build.gradle.kts b/app/apk/build.gradle.kts index 5916e33496689..7310867d1e8a0 100644 --- a/app/apk/build.gradle.kts +++ b/app/apk/build.gradle.kts @@ -36,6 +36,7 @@ android { dependencies { implementation(project(":core")) implementation(project(":shared")) + implementation(project(":wear")) coreLibraryDesugaring(libs.jdk.libs) // Compose diff --git a/app/apk/src/main/AndroidManifest.xml b/app/apk/src/main/AndroidManifest.xml index a24eeb08da824..b81c1c939b8a5 100644 --- a/app/apk/src/main/AndroidManifest.xml +++ b/app/apk/src/main/AndroidManifest.xml @@ -2,6 +2,10 @@ + + + (null) internal val showUnsupported = MutableStateFlow>>(emptyList()) + // Set in onCreate where the Wear OS UI replaces this one + private var wearUi: WearUi? = null override fun attachBaseContext(base: Context) { super.attachBaseContext(base.wrap()) } override fun onCreate(savedInstanceState: Bundle?) { - applySystemBarStyle() + if (useWearUi()) wearUi = WearUi(this) else applySystemBarStyle() extension.onCreate(savedInstanceState) splashController.preOnCreate() super.onCreate(savedInstanceState) @@ -110,6 +114,11 @@ class MainActivity : ComponentActivity(), SplashScreenHost { @SuppressLint("InlinedApi") override fun onCreateUi(savedInstanceState: Bundle?) { + wearUi?.let { + it.onCreateUi(savedInstanceState) + return + } + showUnsupportedMessage() // Only ask on startup, not every time the activity is recreated diff --git a/app/gradle/libs.versions.toml b/app/gradle/libs.versions.toml index 1269ce1124879..6027f43ac3620 100644 --- a/app/gradle/libs.versions.toml +++ b/app/gradle/libs.versions.toml @@ -13,6 +13,7 @@ compose-m3 = "1.4.0" navigation3 = "1.1.7" navigationevent = "1.1.2" wire = "7.0.3" +wear-compose = "1.7.2" [libraries] commons-compress = { module = "org.apache.commons:commons-compress", version = "1.28.0" } @@ -42,6 +43,7 @@ test-runner = { module = "androidx.test:runner", version = "1.7.0" } test-rules = { module = "androidx.test:rules", version = "1.7.0" } test-junit = { module = "androidx.test.ext:junit", version = "1.3.0" } test-uiautomator = { module = "androidx.test.uiautomator:uiautomator", version = "2.4.0" } +junit = { module = "junit:junit", version = "4.13.2" } # topjohnwu libsu-core = { module = "com.github.topjohnwu.libsu:core", version.ref = "libsu" } @@ -71,6 +73,10 @@ navigation3-runtime = { module = "androidx.navigation3:navigation3-runtime", ver navigation3-ui = { module = "androidx.navigation3:navigation3-ui", version.ref = "navigation3" } navigationevent-compose = { module = "androidx.navigationevent:navigationevent-compose", version.ref = "navigationevent" } +# Wear OS +wear-compose-foundation = { module = "androidx.wear.compose:compose-foundation", version.ref = "wear-compose" } +wear-compose-material3 = { module = "androidx.wear.compose:compose-material3", version.ref = "wear-compose" } + # For build-logic android-gradle-plugin = { module = "com.android.tools.build:gradle", version.ref = "android" } android-build-sdk-common = { module = "com.android.tools:sdk-common", version.ref = "android-tools" } diff --git a/app/settings.gradle.kts b/app/settings.gradle.kts index da8293977c791..0d0a53f93381f 100644 --- a/app/settings.gradle.kts +++ b/app/settings.gradle.kts @@ -31,4 +31,4 @@ pluginManagement { } rootProject.name = "Magisk" -include(":apk", ":core", ":shared", ":test") +include(":apk", ":core", ":shared", ":test", ":wear") diff --git a/app/wear/build.gradle.kts b/app/wear/build.gradle.kts new file mode 100644 index 0000000000000..8e15dbb255b16 --- /dev/null +++ b/app/wear/build.gradle.kts @@ -0,0 +1,39 @@ +plugins { + alias(libs.plugins.android.library) + kotlin("plugin.parcelize") + alias(libs.plugins.compose.compiler) +} + +setupCommon() + +android { + namespace = "com.topjohnwu.magisk.wear" + + buildFeatures { + compose = true + } + + compileOptions { + isCoreLibraryDesugaringEnabled = true + } +} + +dependencies { + implementation(project(":core")) + implementation(project(":shared")) + coreLibraryDesugaring(libs.jdk.libs) + + // Compose + implementation(libs.compose.ui) + implementation(libs.compose.foundation) + implementation(libs.compose.material.icons.extended) + implementation(libs.activity.compose) + implementation(libs.lifecycle.runtime.compose) + implementation(libs.lifecycle.viewmodel.compose) + + // Wear OS + implementation(libs.wear.compose.foundation) + implementation(libs.wear.compose.material3) + + testImplementation(libs.junit) +} diff --git a/app/wear/src/main/AndroidManifest.xml b/app/wear/src/main/AndroidManifest.xml new file mode 100644 index 0000000000000..8072ee00dbf16 --- /dev/null +++ b/app/wear/src/main/AndroidManifest.xml @@ -0,0 +1,2 @@ + + diff --git a/app/wear/src/main/java/com/topjohnwu/magisk/wear/WearUi.kt b/app/wear/src/main/java/com/topjohnwu/magisk/wear/WearUi.kt new file mode 100644 index 0000000000000..7cb5fe298c525 --- /dev/null +++ b/app/wear/src/main/java/com/topjohnwu/magisk/wear/WearUi.kt @@ -0,0 +1,47 @@ +package com.topjohnwu.magisk.wear + +import android.content.Context +import android.content.res.Configuration +import android.os.Build +import android.os.Bundle +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.ui.Modifier +import androidx.wear.compose.material3.MaterialTheme +import androidx.wear.compose.material3.TimeText +import androidx.wear.compose.material3.timeTextCurvedText + +/** + * Whether this device gets the Wear OS UI: a watch on API 25 or later, which Wear Compose + * requires. The check matches the `watch-v25` resource qualifier, so the theme and splash + * colors in `values-watch-v25` apply exactly where this returns true. + */ +fun Context.useWearUi(): Boolean = + Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1 && + (resources.configuration.uiMode and Configuration.UI_MODE_TYPE_MASK) == + Configuration.UI_MODE_TYPE_WATCH + +/** + * The Wear OS UI of the app. On a device where [useWearUi] is true, the main activity hands + * its content to this class instead of showing the phone UI. The activity keeps doing the + * common splash and initialization sequence. + */ +class WearUi(private val activity: ComponentActivity) { + + fun onCreateUi(savedInstanceState: Bundle?) { + activity.setContent { + MaterialTheme { + Box( + modifier = Modifier + .fillMaxSize() + .background(MaterialTheme.colorScheme.background) + ) { + TimeText { time -> timeTextCurvedText(time) } + } + } + } + } +} diff --git a/app/wear/src/main/res/values-watch-v25/colors.xml b/app/wear/src/main/res/values-watch-v25/colors.xml new file mode 100644 index 0000000000000..93619cfcf1aab --- /dev/null +++ b/app/wear/src/main/res/values-watch-v25/colors.xml @@ -0,0 +1,6 @@ + + + + + @android:color/black + diff --git a/app/wear/src/main/res/values-watch-v25/themes.xml b/app/wear/src/main/res/values-watch-v25/themes.xml new file mode 100644 index 0000000000000..2d056ae212f2c --- /dev/null +++ b/app/wear/src/main/res/values-watch-v25/themes.xml @@ -0,0 +1,9 @@ + + + + + + + From 51721c4136ea9e94add30016ecc3b3f25005013e Mon Sep 17 00:00:00 2001 From: Jakub Mendyka Date: Mon, 23 Nov 2026 19:41:15 +0100 Subject: [PATCH 03/12] Share display name, startup checks and auth Move the sanitizer and the timed provider query for the display name of an external flash request, and the startup checks for an unsupported install, from the phone MainActivity to :shared, so the Wear UI runs the same security-relevant code instead of a copy. The phone UI keeps its dialogs and behaves as before. rememberBiometricAuth, which asks for the device credential before a Superuser change when the setting requires it, moves to :shared as well. It only depends on the activity result API, not on a UI kit. The sanitizer gets JVM unit tests for control, bidi and tag characters, the length cap and trimming. Assisted-by: Claude Opus 5.5 --- .../com/topjohnwu/magisk/ui/MainActivity.kt | 83 +------------------ app/shared/build.gradle.kts | 3 + .../magisk/ui/UnsupportedMessages.kt | 33 ++++++++ .../magisk/ui/component/Authentication.kt | 0 .../topjohnwu/magisk/ui/flash/DisplayName.kt | 62 ++++++++++++++ .../magisk/ui/flash/DisplayNameTest.kt | 41 +++++++++ 6 files changed, 142 insertions(+), 80 deletions(-) create mode 100644 app/shared/src/main/java/com/topjohnwu/magisk/ui/UnsupportedMessages.kt rename app/{apk => shared}/src/main/java/com/topjohnwu/magisk/ui/component/Authentication.kt (100%) create mode 100644 app/shared/src/main/java/com/topjohnwu/magisk/ui/flash/DisplayName.kt create mode 100644 app/shared/src/test/java/com/topjohnwu/magisk/ui/flash/DisplayNameTest.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 3543cd0666557..53bde2c58e432 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 @@ -4,13 +4,9 @@ import android.Manifest import android.annotation.SuppressLint import android.content.Context import android.content.Intent -import android.content.pm.ApplicationInfo import android.content.res.Resources -import android.net.Uri import android.os.Build import android.os.Bundle -import android.os.CancellationSignal -import android.provider.OpenableColumns import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.animation.AnimatedContentTransitionScope.SlideDirection @@ -38,7 +34,6 @@ import com.topjohnwu.magisk.R 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 @@ -50,6 +45,8 @@ 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.flash.queryDisplayName +import com.topjohnwu.magisk.ui.flash.sanitizeDisplayName import com.topjohnwu.magisk.ui.module.ActionScreen import com.topjohnwu.magisk.ui.module.ActionViewModel import com.topjohnwu.magisk.ui.navigation.LocalNavigator @@ -62,17 +59,9 @@ import com.topjohnwu.magisk.ui.superuser.SuperuserGrantViewModel import com.topjohnwu.magisk.ui.superuser.SuperuserViewModel import com.topjohnwu.magisk.wear.WearUi import com.topjohnwu.magisk.wear.useWearUi -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.async import kotlinx.coroutines.flow.MutableStateFlow -import java.io.File -import kotlinx.coroutines.withTimeoutOrNull import com.topjohnwu.magisk.core.R as CoreR -private const val MAX_DISPLAY_NAME_LENGTH = 100 -private const val DISPLAY_NAME_QUERY_TIMEOUT_MS = 3000L - class MainActivity : ComponentActivity(), SplashScreenHost { override val extension = ActivityExtension(this) @@ -293,55 +282,6 @@ class MainActivity : ComponentActivity(), SplashScreenHost { } } - /** - * Names from external apps are untrusted: drop control and formatting characters - * (e.g. bidi overrides that can reorder the text) and cap the length. - */ - private fun String.sanitizeDisplayName(): String { - val sb = StringBuilder() - var count = 0 - var i = 0 - // Work on code points, so supplementary characters (e.g. invisible tag characters) - // are recognized and never split - while (i < length && count < MAX_DISPLAY_NAME_LENGTH) { - val cp = codePointAt(i) - i += Character.charCount(cp) - val type = Character.getType(cp) - if (Character.isISOControl(cp) || type == Character.FORMAT.toInt() || - type == Character.SURROGATE.toInt()) continue - sb.appendCodePoint(cp) - count++ - } - return sb.toString().trim() - } - - /** - * Query the display name from the provider of an external URI. The provider is controlled - * by another app, so never block on it indefinitely: give up after a timeout and cancel it. - */ - private suspend fun queryDisplayName(context: Context, uri: Uri): String? { - val signal = CancellationSignal() - // Not a child of the caller, so giving up doesn't have to wait for the provider - val query = CoroutineScope(Dispatchers.IO).async { - runCatching { - context.contentResolver.query( - uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null, signal - )?.use { cursor -> - val idx = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME) - if (cursor.moveToFirst() && idx >= 0) cursor.getString(idx) else null - } - }.getOrNull() - } - return try { - withTimeoutOrNull(DISPLAY_NAME_QUERY_TIMEOUT_MS) { query.await() } - } finally { - if (!query.isCompleted) { - signal.cancel() - query.cancel() - } - } - } - private fun setHideOverlayWindows(hide: Boolean) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { window.setHideOverlayWindows(hide) @@ -372,24 +312,7 @@ class MainActivity : ComponentActivity(), SplashScreenHost { } private fun showUnsupportedMessage() { - 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) { - messages.add(CoreR.string.unsupport_general_title to CoreR.string.unsupport_other_su_msg) - } - if (applicationInfo.flags and ApplicationInfo.FLAG_SYSTEM != 0) { - 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) - } - + val messages = unsupportedMessages() if (messages.isNotEmpty()) { showUnsupported.value = messages } diff --git a/app/shared/build.gradle.kts b/app/shared/build.gradle.kts index 6d8bf8c765080..09c36546a54d8 100644 --- a/app/shared/build.gradle.kts +++ b/app/shared/build.gradle.kts @@ -23,5 +23,8 @@ dependencies { api(libs.lifecycle.livedata.core) api(libs.compose.runtime) api(libs.navigation3.runtime) + implementation(libs.activity.compose) implementation(libs.core.ktx) + + testImplementation(libs.junit) } diff --git a/app/shared/src/main/java/com/topjohnwu/magisk/ui/UnsupportedMessages.kt b/app/shared/src/main/java/com/topjohnwu/magisk/ui/UnsupportedMessages.kt new file mode 100644 index 0000000000000..ad2f24890485b --- /dev/null +++ b/app/shared/src/main/java/com/topjohnwu/magisk/ui/UnsupportedMessages.kt @@ -0,0 +1,33 @@ +package com.topjohnwu.magisk.ui + +import android.content.Context +import android.content.pm.ApplicationInfo +import com.topjohnwu.magisk.core.Info +import java.io.File +import com.topjohnwu.magisk.core.R as CoreR + +/** + * Problems with the Magisk installation or the app's own install that the user should be + * told about on startup, as pairs of title and message string resources. + */ +fun Context.unsupportedMessages(): List> { + 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) { + messages.add(CoreR.string.unsupport_general_title to CoreR.string.unsupport_other_su_msg) + } + if (applicationInfo.flags and ApplicationInfo.FLAG_SYSTEM != 0) { + 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) + } + + return messages +} diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/component/Authentication.kt b/app/shared/src/main/java/com/topjohnwu/magisk/ui/component/Authentication.kt similarity index 100% rename from app/apk/src/main/java/com/topjohnwu/magisk/ui/component/Authentication.kt rename to app/shared/src/main/java/com/topjohnwu/magisk/ui/component/Authentication.kt diff --git a/app/shared/src/main/java/com/topjohnwu/magisk/ui/flash/DisplayName.kt b/app/shared/src/main/java/com/topjohnwu/magisk/ui/flash/DisplayName.kt new file mode 100644 index 0000000000000..8151837776223 --- /dev/null +++ b/app/shared/src/main/java/com/topjohnwu/magisk/ui/flash/DisplayName.kt @@ -0,0 +1,62 @@ +package com.topjohnwu.magisk.ui.flash + +import android.content.Context +import android.net.Uri +import android.os.CancellationSignal +import android.provider.OpenableColumns +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.async +import kotlinx.coroutines.withTimeoutOrNull + +private const val MAX_DISPLAY_NAME_LENGTH = 100 +private const val DISPLAY_NAME_QUERY_TIMEOUT_MS = 3000L + +/** + * Names from external apps are untrusted: drop control and formatting characters + * (e.g. bidi overrides that can reorder the text) and cap the length. + */ +fun String.sanitizeDisplayName(): String { + val sb = StringBuilder() + var count = 0 + var i = 0 + // Work on code points, so supplementary characters (e.g. invisible tag characters) + // are recognized and never split + while (i < length && count < MAX_DISPLAY_NAME_LENGTH) { + val cp = codePointAt(i) + i += Character.charCount(cp) + val type = Character.getType(cp) + if (Character.isISOControl(cp) || type == Character.FORMAT.toInt() || + type == Character.SURROGATE.toInt()) continue + sb.appendCodePoint(cp) + count++ + } + return sb.toString().trim() +} + +/** + * Query the display name from the provider of an external URI. The provider is controlled + * by another app, so never block on it indefinitely: give up after a timeout and cancel it. + */ +suspend fun queryDisplayName(context: Context, uri: Uri): String? { + val signal = CancellationSignal() + // Not a child of the caller, so giving up doesn't have to wait for the provider + val query = CoroutineScope(Dispatchers.IO).async { + runCatching { + context.contentResolver.query( + uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null, signal + )?.use { cursor -> + val idx = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME) + if (cursor.moveToFirst() && idx >= 0) cursor.getString(idx) else null + } + }.getOrNull() + } + return try { + withTimeoutOrNull(DISPLAY_NAME_QUERY_TIMEOUT_MS) { query.await() } + } finally { + if (!query.isCompleted) { + signal.cancel() + query.cancel() + } + } +} diff --git a/app/shared/src/test/java/com/topjohnwu/magisk/ui/flash/DisplayNameTest.kt b/app/shared/src/test/java/com/topjohnwu/magisk/ui/flash/DisplayNameTest.kt new file mode 100644 index 0000000000000..f02dccdacd5f0 --- /dev/null +++ b/app/shared/src/test/java/com/topjohnwu/magisk/ui/flash/DisplayNameTest.kt @@ -0,0 +1,41 @@ +package com.topjohnwu.magisk.ui.flash + +import org.junit.Assert.assertEquals +import org.junit.Test + +class DisplayNameTest { + + @Test + fun dropsControlChars() { + assertEquals("ab.zip", "a\u0000b\n.zip\u007f".sanitizeDisplayName()) + } + + @Test + fun dropsBidiOverride() { + assertEquals("evilpiz.exe", "evil‮piz.exe".sanitizeDisplayName()) + } + + @Test + fun dropsSupplementaryFormatChars() { + val tag = String(Character.toChars(0xE0041)) + assertEquals("module.zip", "module${tag}.zip".sanitizeDisplayName()) + } + + @Test + fun keepsOtherSupplementaryChars() { + val emoji = String(Character.toChars(0x1F600)) + assertEquals("$emoji.zip", "$emoji.zip".sanitizeDisplayName()) + } + + @Test + fun capsLengthInCodePoints() { + val emoji = String(Character.toChars(0x1F600)) + assertEquals(emoji.repeat(100), emoji.repeat(150).sanitizeDisplayName()) + assertEquals("a".repeat(100), "a".repeat(150).sanitizeDisplayName()) + } + + @Test + fun trims() { + assertEquals("module.zip", " module.zip \t".sanitizeDisplayName()) + } +} From ba2dedcab1826526e2e5b3a73309e05a9aecfa20 Mon Sep 17 00:00:00 2001 From: Jakub Mendyka Date: Mon, 23 Nov 2026 16:08:34 +0100 Subject: [PATCH 04/12] Add Wear theme, navigation and file picker Give the Wear UI its color scheme and a Navigation3 back stack shown with the Wear swipe-to-dismiss scene strategy. WearRoute adds the screens that only exist on Wear next to the shared Route, and WearNavigator saves the stack like the phone UI does. Screens that are not written yet show a placeholder. WearUi follows the phone UI's startup and handles the flash intent. Our own module downloads go straight to flashing; requests from other apps are confirmed with a Wear AlertDialog like on the phone: the display name is queried with a timeout and sanitized, its source is shown, and overlays are hidden while it is up. Most watches have no app for ACTION_OPEN_DOCUMENT, so the file picker falls back to listing the download folder through the root shell. It is also used when only a non-system app handles the action: the picker is started without a chooser, and any installed app could otherwise register for it and supply the file to install. The app creates the copy in its cache and root only writes into it: a file created by the root shell would get its SELinux level without the app's categories, and the app could neither open nor delete it. Assisted-by: Claude Opus 5.5 --- app/apk/src/main/AndroidManifest.xml | 2 +- .../com/topjohnwu/magisk/ui/MainActivity.kt | 6 +- app/core/src/main/res/values-pl/strings.xml | 4 + app/core/src/main/res/values/strings.xml | 3 + app/gradle/libs.versions.toml | 1 + app/wear/build.gradle.kts | 6 + app/wear/src/main/AndroidManifest.xml | 7 +- .../java/com/topjohnwu/magisk/wear/WearUi.kt | 286 +++++++++++++++++- .../magisk/wear/files/DocumentPicker.kt | 45 +++ .../topjohnwu/magisk/wear/files/FilePicker.kt | 151 +++++++++ .../topjohnwu/magisk/wear/files/RootFiles.kt | 83 +++++ .../com/topjohnwu/magisk/wear/nav/WearNav.kt | 133 ++++++++ .../topjohnwu/magisk/wear/theme/WearTheme.kt | 22 ++ .../magisk/wear/files/DocumentPickerTest.kt | 52 ++++ .../magisk/wear/files/RootFilesTest.kt | 46 +++ 15 files changed, 831 insertions(+), 16 deletions(-) create mode 100644 app/wear/src/main/java/com/topjohnwu/magisk/wear/files/DocumentPicker.kt create mode 100644 app/wear/src/main/java/com/topjohnwu/magisk/wear/files/FilePicker.kt create mode 100644 app/wear/src/main/java/com/topjohnwu/magisk/wear/files/RootFiles.kt create mode 100644 app/wear/src/main/java/com/topjohnwu/magisk/wear/nav/WearNav.kt create mode 100644 app/wear/src/main/java/com/topjohnwu/magisk/wear/theme/WearTheme.kt create mode 100644 app/wear/src/test/java/com/topjohnwu/magisk/wear/files/DocumentPickerTest.kt create mode 100644 app/wear/src/test/java/com/topjohnwu/magisk/wear/files/RootFilesTest.kt diff --git a/app/apk/src/main/AndroidManifest.xml b/app/apk/src/main/AndroidManifest.xml index b81c1c939b8a5..58a19329b9fd5 100644 --- a/app/apk/src/main/AndroidManifest.xml +++ b/app/apk/src/main/AndroidManifest.xml @@ -4,7 +4,7 @@ - + Zainstaluj w nieaktywnym slocie (po OTA) Po ponownym uruchomieniu twoje urządzenie zostanie ZMUSZONE do rozruchu z aktualnie nieaktywnego slotu!\nUżywaj tej opcji tylko po ukończeniu aktualizacji OTA.\nKontynuować? Dodatkowa konfiguracja + Wybierz z pamięci Ponowne uruchomienie za 5 sekund… Instalacja @@ -209,4 +210,7 @@ Zezwól na \"Instaluj z nieznanych źródeł\", aby włączyć tę funkcję Nie znaleziono aplikacji do wykonania tej czynności Uruchom ponownie, aby zastosować zmiany + + + Brak pasujących plików w folderze Download diff --git a/app/core/src/main/res/values/strings.xml b/app/core/src/main/res/values/strings.xml index 3c0ed388a6698..b8665014adabd 100644 --- a/app/core/src/main/res/values/strings.xml +++ b/app/core/src/main/res/values/strings.xml @@ -240,4 +240,7 @@ Reboot to apply changes Execution in progress Are you sure you want to exit? The running operation may not complete. + + + No matching files in the Download folder diff --git a/app/gradle/libs.versions.toml b/app/gradle/libs.versions.toml index 6027f43ac3620..c9cd610b76baa 100644 --- a/app/gradle/libs.versions.toml +++ b/app/gradle/libs.versions.toml @@ -76,6 +76,7 @@ navigationevent-compose = { module = "androidx.navigationevent:navigationevent-c # Wear OS wear-compose-foundation = { module = "androidx.wear.compose:compose-foundation", version.ref = "wear-compose" } wear-compose-material3 = { module = "androidx.wear.compose:compose-material3", version.ref = "wear-compose" } +wear-compose-navigation3 = { module = "androidx.wear.compose:compose-navigation3", version.ref = "wear-compose" } # For build-logic android-gradle-plugin = { module = "com.android.tools.build:gradle", version.ref = "android" } diff --git a/app/wear/build.gradle.kts b/app/wear/build.gradle.kts index 8e15dbb255b16..78da65e3a19c3 100644 --- a/app/wear/build.gradle.kts +++ b/app/wear/build.gradle.kts @@ -34,6 +34,12 @@ dependencies { // Wear OS implementation(libs.wear.compose.foundation) implementation(libs.wear.compose.material3) + implementation(libs.wear.compose.navigation3) + + // Navigation3 + implementation(libs.navigation3.runtime) + implementation(libs.navigation3.ui) + implementation(libs.lifecycle.viewmodel.navigation3) testImplementation(libs.junit) } diff --git a/app/wear/src/main/AndroidManifest.xml b/app/wear/src/main/AndroidManifest.xml index 8072ee00dbf16..223f28cf62f15 100644 --- a/app/wear/src/main/AndroidManifest.xml +++ b/app/wear/src/main/AndroidManifest.xml @@ -1,2 +1,7 @@ - + + + + + + diff --git a/app/wear/src/main/java/com/topjohnwu/magisk/wear/WearUi.kt b/app/wear/src/main/java/com/topjohnwu/magisk/wear/WearUi.kt index 7cb5fe298c525..6cf5c3ba9c3c7 100644 --- a/app/wear/src/main/java/com/topjohnwu/magisk/wear/WearUi.kt +++ b/app/wear/src/main/java/com/topjohnwu/magisk/wear/WearUi.kt @@ -1,18 +1,67 @@ package com.topjohnwu.magisk.wear +import android.Manifest +import android.annotation.SuppressLint import android.content.Context import android.content.res.Configuration import android.os.Build import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent -import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +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.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier -import androidx.wear.compose.material3.MaterialTheme +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalResources +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.style.TextAlign +import androidx.core.net.toUri +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.lifecycle.viewmodel.navigation3.rememberViewModelStoreNavEntryDecorator +import androidx.navigation3.runtime.NavKey +import androidx.navigation3.runtime.entryProvider +import androidx.navigation3.runtime.rememberSaveableStateHolderNavEntryDecorator +import androidx.navigation3.ui.NavDisplay +import androidx.wear.compose.foundation.lazy.TransformingLazyColumn +import androidx.wear.compose.foundation.lazy.rememberTransformingLazyColumnState +import androidx.wear.compose.material3.AlertDialog +import androidx.wear.compose.material3.AlertDialogDefaults +import androidx.wear.compose.material3.AppScaffold +import androidx.wear.compose.material3.Button +import androidx.wear.compose.material3.ListHeader +import androidx.wear.compose.material3.ScreenScaffold +import androidx.wear.compose.material3.Text import androidx.wear.compose.material3.TimeText -import androidx.wear.compose.material3.timeTextCurvedText +import androidx.wear.compose.navigation3.rememberSwipeDismissableSceneStrategy +import com.topjohnwu.magisk.core.Config +import com.topjohnwu.magisk.core.Const +import com.topjohnwu.magisk.core.base.ActivityExtension +import com.topjohnwu.magisk.ui.flash.FlashUtils +import com.topjohnwu.magisk.ui.flash.queryDisplayName +import com.topjohnwu.magisk.ui.flash.sanitizeDisplayName +import com.topjohnwu.magisk.ui.navigation.Route +import com.topjohnwu.magisk.ui.unsupportedMessages +import com.topjohnwu.magisk.wear.files.PickScreen +import com.topjohnwu.magisk.wear.nav.LocalWearNavigator +import com.topjohnwu.magisk.wear.nav.WearNavigator +import com.topjohnwu.magisk.wear.nav.WearRoute +import com.topjohnwu.magisk.wear.nav.rememberWearNavigator +import com.topjohnwu.magisk.wear.theme.WearTheme +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.flow.MutableStateFlow +import com.topjohnwu.magisk.core.R as CoreR /** * Whether this device gets the Wear OS UI: a watch on API 25 or later, which Wear Compose @@ -26,22 +75,233 @@ fun Context.useWearUi(): Boolean = /** * The Wear OS UI of the app. On a device where [useWearUi] is true, the main activity hands - * its content to this class instead of showing the phone UI. The activity keeps doing the - * common splash and initialization sequence. + * its content and new intents to this class instead of showing the phone UI. The activity + * keeps doing the common splash and initialization sequence. */ -class WearUi(private val activity: ComponentActivity) { +class WearUi( + private val activity: ComponentActivity, + private val extension: ActivityExtension, +) { + private val intentState = MutableStateFlow(0) + + @SuppressLint("InlinedApi") fun onCreateUi(savedInstanceState: Bundle?) { + val unsupported = activity.unsupportedMessages() + + // Only ask on startup, not every time the activity is recreated + if (savedInstanceState == null && Config.checkUpdate) { + extension.withPermission(Manifest.permission.POST_NOTIFICATIONS) { + Config.checkUpdate = it + } + } + activity.setContent { - MaterialTheme { - Box( - modifier = Modifier - .fillMaxSize() - .background(MaterialTheme.colorScheme.background) - ) { - TimeText { time -> timeTextCurvedText(time) } + WearTheme { + AppScaffold(timeText = { TimeText() }) { + val navigator = rememberWearNavigator(Route.Main) + CompositionLocalProvider(LocalWearNavigator provides navigator) { + HandleFlashIntent(navigator) + + NavDisplay( + backStack = navigator.backStack, + onBack = { navigator.pop() }, + entryDecorators = listOf( + rememberSaveableStateHolderNavEntryDecorator(), + rememberViewModelStoreNavEntryDecorator() + ), + // Swipe-to-dismiss, and predictive back from API 36 + sceneStrategies = listOf(rememberSwipeDismissableSceneStrategy()), + entryProvider = entryProvider { + entry { MainPlaceholder(navigator) } + entry { + Placeholder(stringResource(CoreR.string.denylist)) + } + entry { + Placeholder(stringResource(CoreR.string.flash_screen_title)) + } + entry { + Placeholder(stringResource(CoreR.string.superuser)) + } + entry { + Placeholder(stringResource(CoreR.string.superuser_grant)) + } + entry { key -> Placeholder(key.name) } + entry { + Placeholder(stringResource(CoreR.string.superuser)) + } + entry { + Placeholder(stringResource(CoreR.string.logs)) + } + entry { + Placeholder(stringResource(CoreR.string.modules)) + } + entry { key -> Placeholder(key.dir) } + entry { + Placeholder(stringResource(CoreR.string.install)) + } + entry { + Placeholder(stringResource(CoreR.string.settings)) + } + entry { key -> PickScreen(key.kind, navigator) } + entry { + Placeholder(stringResource(CoreR.string.restore_img)) + } + } + ) + } + UnsupportedDialogs(unsupported) + } + } + } + } + + @Composable + private fun HandleFlashIntent(navigator: WearNavigator) { + val context = LocalContext.current + val resources = LocalResources.current + val intentVersion by intentState.collectAsStateWithLifecycle() + var confirmRequest by remember { mutableStateOf(null) } + // Not cleared, so the text stays while the dialog animates out after it is answered + var shownContent by remember { mutableStateOf("") } + + LaunchedEffect(intentVersion) { + val currentIntent = activity.intent ?: return@LaunchedEffect + if (currentIntent.action != FlashUtils.INTENT_FLASH) return@LaunchedEffect + val action = currentIntent.getStringExtra(FlashUtils.EXTRA_FLASH_ACTION) + val uriString = currentIntent.getStringExtra(FlashUtils.EXTRA_FLASH_URI) + + val route = when (action) { + Const.Value.FLASH_ZIP -> { + if (uriString.isNullOrEmpty()) { + null + } else if (FlashUtils.isTrusted(currentIntent)) { + // Sent by our own module download, which the user already chose to install + Route.Flash(action, uriString) + } else { + val uri = uriString.toUri() + val name = queryDisplayName(context, uri)?.sanitizeDisplayName()?.ifEmpty { null } + ?: uri.lastPathSegment?.sanitizeDisplayName()?.ifEmpty { null } + ?: "module.zip" + // The name is chosen by the app that sent the intent, so also show where it comes from + val authority = uri.authority?.sanitizeDisplayName()?.ifEmpty { null } + val displayName = authority?.let { "$name ($it)" } ?: name + + // This confirmation is the only safeguard, so don't let other apps draw over it + setHideOverlayWindows(true) + val confirmed = try { + val request = ConfirmRequest( + content = resources.getString(CoreR.string.confirm_install, displayName) + ) + shownContent = request.content + confirmRequest = request + request.result.await() + } finally { + confirmRequest = null + setHideOverlayWindows(false) + } + if (confirmed) Route.Flash(action, uriString) else null + } + } + // Only installing modules can be requested through this intent (our module + // downloads use it too); drop any other action, e.g. uninstalling Magisk + else -> null + } + + // Only consume the intent once the request is resolved. If a configuration change + // cancels this effect while the confirmation is showing, the new Activity replays it. + currentIntent.action = null + route?.let { navigator.navigate(it) } + } + + val request = confirmRequest + AlertDialog( + visible = request != null, + onDismissRequest = { request?.result?.complete(false) }, + title = { Text(stringResource(CoreR.string.confirm_install_title)) }, + text = { Text(shownContent) }, + confirmButton = { + AlertDialogDefaults.ConfirmButton(onClick = { request?.result?.complete(true) }) + }, + dismissButton = { + AlertDialogDefaults.DismissButton(onClick = { request?.result?.complete(false) }) + }, + ) + } + + /** A confirmation shown by [HandleFlashIntent], completed with the user's answer. */ + private class ConfirmRequest(val content: String) { + val result = CompletableDeferred() + } + + private fun setHideOverlayWindows(hide: Boolean) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + activity.window.setHideOverlayWindows(hide) + } + } + + /** Called by the activity after it got a new intent. */ + fun onNewIntent() { + intentState.value += 1 + } +} + +/** Stands in for a screen that is not implemented yet. */ +@Composable +private fun Placeholder(title: String) { + ScreenScaffold { contentPadding -> + Box( + modifier = Modifier + .fillMaxSize() + .padding(contentPadding), + contentAlignment = Alignment.Center, + ) { + Text(title, textAlign = TextAlign.Center) + } + } +} + +/** Stands in for the home screen: only reaches the other screens. */ +@Composable +private fun MainPlaceholder(navigator: WearNavigator) { + val destinations: List> = listOf( + CoreR.string.superuser to WearRoute.Superuser, + CoreR.string.modules to WearRoute.Modules, + CoreR.string.logs to WearRoute.Logs, + CoreR.string.settings to WearRoute.Settings, + CoreR.string.install to WearRoute.Install, + ) + val state = rememberTransformingLazyColumnState() + ScreenScaffold(state) { contentPadding -> + TransformingLazyColumn(state = state, contentPadding = contentPadding) { + item { + ListHeader { Text(stringResource(CoreR.string.section_home)) } + } + destinations.forEach { (title, key) -> + item { + Button( + onClick = { navigator.navigate(key) }, + modifier = Modifier.fillMaxWidth(), + ) { + Text(stringResource(title)) + } } } } } } + +/** Shows each problem found by [unsupportedMessages] in turn, like the phone app on startup. */ +@Composable +private fun UnsupportedDialogs(messages: List>) { + var index by rememberSaveable { mutableIntStateOf(0) } + // The last one stays as content while its dialog animates out + val shown = messages.getOrNull(index) ?: messages.lastOrNull() ?: return + AlertDialog( + visible = index < messages.size, + onDismissRequest = { index++ }, + title = { Text(stringResource(shown.first)) }, + text = { Text(stringResource(shown.second)) }, + edgeButton = { AlertDialogDefaults.EdgeButton(onClick = { index++ }) }, + ) +} diff --git a/app/wear/src/main/java/com/topjohnwu/magisk/wear/files/DocumentPicker.kt b/app/wear/src/main/java/com/topjohnwu/magisk/wear/files/DocumentPicker.kt new file mode 100644 index 0000000000000..672152be2a58e --- /dev/null +++ b/app/wear/src/main/java/com/topjohnwu/magisk/wear/files/DocumentPicker.kt @@ -0,0 +1,45 @@ +package com.topjohnwu.magisk.wear.files + +import android.content.Context +import android.content.Intent +import android.net.Uri +import androidx.activity.result.contract.ActivityResultContract +import androidx.activity.result.contract.ActivityResultContracts + +// Packages that register ACTION_OPEN_DOCUMENT on devices without a document picker, only to +// tell the user that no app can handle it. Wear OS ships the first one. +private val StubPackages = setOf( + "com.google.android.wearable.frameworkpackagestubs", + "com.android.frameworkpackagestubs", +) + +/** The package of an activity that handles ACTION_OPEN_DOCUMENT, and whether it is a system app. */ +class PickerHandler(val packageName: String, val isSystem: Boolean) + +/** + * The package to open documents with, chosen from the [handlers] of ACTION_OPEN_DOCUMENT in + * resolution order, or null if none of them is a real picker. + * + * Only a system app is used. The picker is sent to one package without a chooser, and on a + * watch without a real picker any installed app could otherwise register for the action and + * hand over the module zip or boot image to install. + */ +fun documentPickerPackage(handlers: List): String? = + handlers.firstOrNull { it.isSystem && it.packageName !in StubPackages }?.packageName + +/** A request to pick a document of one of [mimeTypes] with the picker in [packageName]. */ +class DocumentRequest(val packageName: String, val mimeTypes: Array) + +/** + * ACTION_OPEN_DOCUMENT sent to the package of the request, so a stub that also handles it can + * never be chosen instead. + */ +class OpenDocumentIn : ActivityResultContract() { + private val openDocument = ActivityResultContracts.OpenDocument() + + override fun createIntent(context: Context, input: DocumentRequest): Intent = + openDocument.createIntent(context, input.mimeTypes).setPackage(input.packageName) + + override fun parseResult(resultCode: Int, intent: Intent?): Uri? = + openDocument.parseResult(resultCode, intent) +} diff --git a/app/wear/src/main/java/com/topjohnwu/magisk/wear/files/FilePicker.kt b/app/wear/src/main/java/com/topjohnwu/magisk/wear/files/FilePicker.kt new file mode 100644 index 0000000000000..c0c6f64435b35 --- /dev/null +++ b/app/wear/src/main/java/com/topjohnwu/magisk/wear/files/FilePicker.kt @@ -0,0 +1,151 @@ +package com.topjohnwu.magisk.wear.files + +import android.content.ActivityNotFoundException +import android.content.pm.ApplicationInfo +import android.net.Uri +import android.widget.Toast +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.style.TextAlign +import androidx.wear.compose.foundation.lazy.TransformingLazyColumn +import androidx.wear.compose.foundation.lazy.items +import androidx.wear.compose.foundation.lazy.rememberTransformingLazyColumnState +import androidx.wear.compose.material3.Button +import androidx.wear.compose.material3.ListHeader +import androidx.wear.compose.material3.ScreenScaffold +import androidx.wear.compose.material3.Text +import com.topjohnwu.magisk.core.ktx.toast +import com.topjohnwu.magisk.wear.nav.LocalWearNavigator +import com.topjohnwu.magisk.wear.nav.WearNavigator +import com.topjohnwu.magisk.wear.nav.WearRoute +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.launch +import timber.log.Timber +import com.topjohnwu.magisk.core.R as CoreR + +enum class FileKind(val mimeTypes: Array, val extensions: Set) { + ZIP(arrayOf("application/zip"), setOf("zip")), + // Boot images, and Odin firmware packages that contain them + IMAGE(arrayOf("application/octet-stream", "application/x-tar"), setOf("img", "tar", "tar.md5")), +} + +/** + * Returns a function that lets the user pick a file of [kind] and passes it to [onPicked]. + * + * The system picker (ACTION_OPEN_DOCUMENT) is used when a system app handles it. Most watches + * have none, only a stub that says so (see [documentPickerPackage]), so otherwise the + * [WearRoute.Pick] screen lists the files in the download folder through the root shell. Its + * result comes back through [WearNavigator.setPickResult]. + */ +@Composable +fun rememberFilePicker(kind: FileKind, onPicked: (Uri) -> Unit): () -> Unit { + val context = LocalContext.current + val navigator = LocalWearNavigator.current + val currentOnPicked by rememberUpdatedState(onPicked) + + val launcher = rememberLauncherForActivityResult(OpenDocumentIn()) { uri -> + uri?.let { currentOnPicked(it) } + } + + val rootResult = navigator.pickResult(kind) + LaunchedEffect(rootResult) { + if (rootResult != null) { + navigator.consumePickResult(kind) + currentOnPicked(rootResult) + } + } + + return remember(kind, context, navigator, launcher) { + { + val intent = ActivityResultContracts.OpenDocument() + .createIntent(context, kind.mimeTypes) + val handlers = context.packageManager.queryIntentActivities(intent, 0).map { + val app = it.activityInfo.applicationInfo + PickerHandler(app.packageName, (app.flags and ApplicationInfo.FLAG_SYSTEM) != 0) + } + val picker = documentPickerPackage(handlers) + val launched = picker != null && try { + launcher.launch(DocumentRequest(picker, kind.mimeTypes)) + true + } catch (_: ActivityNotFoundException) { + // The handler can be disabled between the check and the launch + false + } + if (!launched) navigator.navigate(WearRoute.Pick(kind)) + } + } +} + +/** Files of [kind] in the download folder, listed with the root shell. */ +@Composable +fun PickScreen(kind: FileKind, navigator: WearNavigator) { + val context = LocalContext.current + val scope = rememberCoroutineScope() + // null while loading + var files by remember { mutableStateOf?>(null) } + var copying by remember { mutableStateOf(false) } + + LaunchedEffect(kind) { + files = RootFiles.list(ext = kind.extensions) + } + + val state = rememberTransformingLazyColumnState() + ScreenScaffold(state) { contentPadding -> + TransformingLazyColumn(state = state, contentPadding = contentPadding) { + item { + ListHeader { Text(stringResource(CoreR.string.select_from_storage)) } + } + val current = files + when { + current == null -> item { + Text(stringResource(CoreR.string.loading), textAlign = TextAlign.Center) + } + current.isEmpty() -> item { + Text(stringResource(CoreR.string.wear_pick_empty), textAlign = TextAlign.Center) + } + else -> items(current) { name -> + Button( + onClick = { + if (copying) return@Button + copying = true + scope.launch { + try { + val uri = RootFiles.copyToCache(context, name) + // Only deliver it if the user hasn't swiped away meanwhile + val pick = WearRoute.Pick(kind) + if (navigator.current() == pick) { + navigator.setPickResult(kind, uri) + navigator.pop() + } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + Timber.e(e) + context.toast(CoreR.string.failure, Toast.LENGTH_SHORT) + } finally { + copying = false + } + } + }, + enabled = !copying, + modifier = Modifier.fillMaxWidth(), + ) { + Text(name) + } + } + } + } + } +} diff --git a/app/wear/src/main/java/com/topjohnwu/magisk/wear/files/RootFiles.kt b/app/wear/src/main/java/com/topjohnwu/magisk/wear/files/RootFiles.kt new file mode 100644 index 0000000000000..c67bc99b1206e --- /dev/null +++ b/app/wear/src/main/java/com/topjohnwu/magisk/wear/files/RootFiles.kt @@ -0,0 +1,83 @@ +package com.topjohnwu.magisk.wear.files + +import android.content.Context +import android.net.Uri +import com.topjohnwu.magisk.core.ktx.await +import com.topjohnwu.magisk.terminal.shellQuoted +import com.topjohnwu.superuser.Shell +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import java.io.File +import java.io.IOException +import java.util.Locale + +/** + * Files read through the root shell, for devices where no app handles ACTION_OPEN_DOCUMENT + * (e.g. most Wear OS watches). Users put files there with `adb push`. + */ +object RootFiles { + + const val DOWNLOAD_DIR = "/sdcard/Download" + + // Copies of picked files, so the app can open them without storage permissions + private const val CACHE_DIR = "picked" + + /** + * Keep the names in [output] that end with an extension in [ext] (ignoring case), sorted + * by name ignoring case. Empty lines are dropped. + */ + fun parseListing(output: List, ext: Set): List { + val extensions = ext.mapTo(HashSet()) { it.lowercase(Locale.ROOT) } + return output + .filter { it.isNotEmpty() } + .filter { name -> + val lower = name.lowercase(Locale.ROOT) + extensions.any { lower.endsWith(".$it") } + } + .sortedWith(String.CASE_INSENSITIVE_ORDER) + } + + /** + * List the regular files in [dir] with an extension in [ext]. Returns an empty list if + * the directory can't be read, e.g. without root. + */ + suspend fun list(dir: String = DOWNLOAD_DIR, ext: Set): List { + // Only regular files: a directory named like "x.zip" can't be picked. printf instead + // of echo, so names starting with "-" are printed as they are. + val cmd = "cd ${dir.shellQuoted()} && " + + "for f in *; do [ -f \"\$f\" ] && printf '%s\\n' \"\$f\"; done" + // The loop's exit code is that of the last test, so only the output matters + return parseListing(Shell.cmd(cmd).await().out, ext) + } + + /** + * Copy [name] in [dir] to the app's cache with the root shell and return the copy's file + * URI. Copies of earlier picks are removed first, so large images don't pile up in the + * cache. + * + * The app creates the copy itself and root only writes into it. A file created by root + * would get the root shell's SELinux level, without the app's categories, so the app + * could neither open nor delete it. Writing through a redirect truncates the existing + * file, which keeps the app's owner and label. + */ + suspend fun copyToCache( + context: Context, + name: String, + dir: String = DOWNLOAD_DIR, + ): Uri = withContext(Dispatchers.IO) { + require('/' !in name && name != "." && name != "..") { "Not a file name: $name" } + val cache = File(context.cacheDir, CACHE_DIR) + // Every copy was created by the app, so the app can delete it + cache.deleteRecursively() + if (!cache.mkdirs()) throw IOException("Failed to create $cache") + val dest = File(cache, name) + if (!dest.createNewFile()) throw IOException("Failed to create $dest") + val src = File(dir, name).path + val result = Shell.cmd("cat ${src.shellQuoted()} > ${dest.path.shellQuoted()}").exec() + if (!result.isSuccess) { + dest.delete() + throw IOException("Failed to copy $src: ${result.err.joinToString("\n")}") + } + Uri.fromFile(dest) + } +} diff --git a/app/wear/src/main/java/com/topjohnwu/magisk/wear/nav/WearNav.kt b/app/wear/src/main/java/com/topjohnwu/magisk/wear/nav/WearNav.kt new file mode 100644 index 0000000000000..627638723d94e --- /dev/null +++ b/app/wear/src/main/java/com/topjohnwu/magisk/wear/nav/WearNav.kt @@ -0,0 +1,133 @@ +package com.topjohnwu.magisk.wear.nav + +import android.net.Uri +import android.os.Parcelable +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.mutableStateMapOf +import androidx.compose.runtime.saveable.Saver +import androidx.compose.runtime.saveable.listSaver +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.staticCompositionLocalOf +import androidx.navigation3.runtime.NavBackStack +import androidx.navigation3.runtime.NavKey +import com.topjohnwu.magisk.arch.BaseViewModel +import com.topjohnwu.magisk.ui.navigation.Route +import com.topjohnwu.magisk.wear.files.FileKind +import kotlinx.parcelize.Parcelize + +/** + * Screens that only exist on Wear. Screens shared with the phone app use [Route], so view + * models in :shared can navigate to them with [BaseViewModel.navigateTo]. + */ +sealed interface WearRoute : NavKey, Parcelable { + @Parcelize + data object Superuser : WearRoute + + @Parcelize + data object Logs : WearRoute + + @Parcelize + data object Modules : WearRoute + + @Parcelize + data class ModuleDetail( + // The module's directory name: unlike the id in module.prop, it is unique + val dir: String, + ) : WearRoute + + @Parcelize + data object Install : WearRoute + + @Parcelize + data object Settings : WearRoute + + /** The root shell file list, used when no app handles ACTION_OPEN_DOCUMENT. */ + @Parcelize + data class Pick(val kind: FileKind) : WearRoute + + @Parcelize + data object Restore : WearRoute +} + +class WearNavigator(val backStack: NavBackStack) { + constructor(vararg initialKeys: NavKey) : this(NavBackStack(*initialKeys)) + + // Files picked on a WearRoute.Pick screen, waiting for the picker that opened it. + // See setPickResult for how a result reaches its caller. + private val pickResults = mutableStateMapOf() + + fun navigate(key: NavKey) { + // Ignore pushing the screen that is already on top (e.g. a double tap, or the same + // request delivered twice). Both copies would get the same content key, so they would + // share one ViewModel and saved state, and need two swipes to leave. + if (backStack.lastOrNull() == key) return + // A result nobody consumed belongs to an earlier pick, never to this one + if (key is WearRoute.Pick) pickResults.remove(key.kind) + backStack.add(key) + } + + fun pop(): Boolean { + // Never remove the root: NavDisplay requires a non-empty back stack. Swiping the root + // away is left to the system, which closes the app. + if (backStack.size <= 1) return false + backStack.removeAt(backStack.lastIndex) + return true + } + + fun current(): NavKey? = backStack.lastOrNull() + + /** + * Hand a file picked on the [WearRoute.Pick] screen of [kind] to its caller. + * + * The Pick screen sets the result and pops itself. The caller is the screen right below + * it, so the rememberFilePicker of the same kind on that screen is composed again and + * takes the result with [consumePickResult]. A result is kept for one kind at a time, + * is dropped when a new Pick of that kind is opened, and is not saved across process + * death (it is consumed as soon as the caller is shown, so nothing is pending by then). + */ + fun setPickResult(kind: FileKind, uri: Uri) { + pickResults[kind] = uri + } + + /** The result waiting for [kind], read as snapshot state so callers recompose on it. */ + fun pickResult(kind: FileKind): Uri? = pickResults[kind] + + fun consumePickResult(kind: FileKind): Uri? = pickResults.remove(kind) + + companion object { + val Saver: Saver = listSaver( + save = { navigator -> navigator.backStack.toList() }, + restore = { savedList -> + val stack = NavBackStack() + if (savedList.isNotEmpty()) { + stack.addAll(savedList) + } else { + stack.add(Route.Main) + } + WearNavigator(stack) + } + ) + } +} + +@Composable +fun rememberWearNavigator(vararg startRoutes: NavKey = arrayOf(Route.Main)): WearNavigator { + return rememberSaveable(saver = WearNavigator.Saver) { + WearNavigator(*startRoutes) + } +} + +/** For composables that navigate without being a screen, e.g. the file picker. */ +val LocalWearNavigator = staticCompositionLocalOf { + error("LocalWearNavigator not provided") +} + +@Composable +fun CollectNavEvents(viewModel: BaseViewModel, navigator: WearNavigator) { + LaunchedEffect(viewModel) { + viewModel.navEvents.collect { route -> + navigator.navigate(route) + } + } +} diff --git a/app/wear/src/main/java/com/topjohnwu/magisk/wear/theme/WearTheme.kt b/app/wear/src/main/java/com/topjohnwu/magisk/wear/theme/WearTheme.kt new file mode 100644 index 0000000000000..959779d2bff28 --- /dev/null +++ b/app/wear/src/main/java/com/topjohnwu/magisk/wear/theme/WearTheme.kt @@ -0,0 +1,22 @@ +package com.topjohnwu.magisk.wear.theme + +import androidx.compose.runtime.Composable +import androidx.compose.ui.graphics.Color +import androidx.wear.compose.material3.ColorScheme +import androidx.wear.compose.material3.MaterialTheme + +private val WearColorScheme = ColorScheme( + // One accent: switches and tonal buttons use the container colors + primary = Color(0xFF4FD8C4), + primaryDim = Color(0xFF3CB4A3), + primaryContainer = Color(0xFF00504A), + onPrimary = Color(0xFF00382F), + onPrimaryContainer = Color(0xFF9FF2E3), + // A black background keeps OLED pixels off and blends with the bezel + background = Color.Black, +) + +@Composable +fun WearTheme(content: @Composable () -> Unit) { + MaterialTheme(colorScheme = WearColorScheme, content = content) +} diff --git a/app/wear/src/test/java/com/topjohnwu/magisk/wear/files/DocumentPickerTest.kt b/app/wear/src/test/java/com/topjohnwu/magisk/wear/files/DocumentPickerTest.kt new file mode 100644 index 0000000000000..1770ed8950f6b --- /dev/null +++ b/app/wear/src/test/java/com/topjohnwu/magisk/wear/files/DocumentPickerTest.kt @@ -0,0 +1,52 @@ +package com.topjohnwu.magisk.wear.files + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class DocumentPickerTest { + + private val wearStub = PickerHandler("com.google.android.wearable.frameworkpackagestubs", true) + private val aospStub = PickerHandler("com.android.frameworkpackagestubs", true) + private val documentsUi = PickerHandler("com.google.android.documentsui", true) + private val userApp = PickerHandler("com.example.files", false) + + @Test + fun noHandler() { + assertNull(documentPickerPackage(emptyList())) + } + + @Test + fun onlyStub() { + assertNull(documentPickerPackage(listOf(wearStub))) + assertNull(documentPickerPackage(listOf(aospStub))) + } + + @Test + fun realPicker() { + assertEquals(documentsUi.packageName, documentPickerPackage(listOf(documentsUi))) + } + + @Test + fun realPickerAfterStub() { + assertEquals(documentsUi.packageName, documentPickerPackage(listOf(wearStub, documentsUi))) + } + + @Test + fun keepsResolutionOrder() { + val otherSystem = PickerHandler("com.example.systemfiles", true) + assertEquals( + otherSystem.packageName, + documentPickerPackage(listOf(otherSystem, documentsUi)), + ) + } + + @Test + fun skipsUserApps() { + assertNull(documentPickerPackage(listOf(wearStub, userApp))) + assertEquals( + documentsUi.packageName, + documentPickerPackage(listOf(userApp, documentsUi)), + ) + } +} diff --git a/app/wear/src/test/java/com/topjohnwu/magisk/wear/files/RootFilesTest.kt b/app/wear/src/test/java/com/topjohnwu/magisk/wear/files/RootFilesTest.kt new file mode 100644 index 0000000000000..71eebb6c5239f --- /dev/null +++ b/app/wear/src/test/java/com/topjohnwu/magisk/wear/files/RootFilesTest.kt @@ -0,0 +1,46 @@ +package com.topjohnwu.magisk.wear.files + +import com.topjohnwu.magisk.terminal.shellQuoted +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Assume.assumeTrue +import org.junit.Test +import java.io.File + +class RootFilesTest { + + @Test + fun parsesZips() { + val files = RootFiles.parseListing( + listOf("a.zip", "b.img", "Zażółć gęślą.zip", "x.ZIP", ""), + setOf("zip") + ) + assertEquals(listOf("a.zip", "x.ZIP", "Zażółć gęślą.zip"), files) + } + + @Test + fun parsesMultiPartExtensions() { + val files = RootFiles.parseListing( + listOf("AP_R870.tar.md5", "boot.img", "notes.md5", "odin.TAR", "tar.md5"), + setOf("img", "tar", "tar.md5") + ) + assertEquals(listOf("AP_R870.tar.md5", "boot.img", "odin.TAR"), files) + } + + @Test + fun emptyDir() { + assertTrue(RootFiles.parseListing(emptyList(), setOf("zip")).isEmpty()) + } + + @Test + fun quotesNames() { + // Runs the quoted name through a real shell, which only exists on Unix hosts + assumeTrue(File("/bin/sh").canExecute()) + val process = ProcessBuilder("sh", "-c", "printf %s ${"it's a.zip".shellQuoted()}") + .redirectErrorStream(true) + .start() + val output = process.inputStream.bufferedReader().use { it.readText() } + assertEquals(0, process.waitFor()) + assertEquals("it's a.zip", output) + } +} From 5fe58629ab7f3571cac3e4432026a181f4ca69d6 Mon Sep 17 00:00:00 2001 From: Jakub Mendyka Date: Mon, 23 Nov 2026 16:21:09 +0100 Subject: [PATCH 05/12] Add Wear home screen Replace the home placeholder with a screen that shows the installed Magisk version and code, whether it is running, and the Zygisk and ramdisk status, followed by shortcuts to Superuser, Modules, Logs, Settings, Install and Uninstall. Without an active Magisk only Install is offered. It reuses HomeViewModel from :shared and reloads it each time the screen is shown, as the phone UI does for its home tab. The screen also shows the environment fix confirmation raised by HomeViewModel's check: it runs fixEnv, or opens Install when only a reinstall can fix it, and shows a progress indicator while it runs. HomeStatus.of applies the Info.Env rule (supported version code and root) to raw values, so it is unit tested without touching Info, whose initializer cannot run on the JVM. HomeStatus.from is the production entry and delegates to it. Assisted-by: Claude Opus 5.5 --- app/core/src/main/res/values-pl/strings.xml | 3 + app/core/src/main/res/values/resources.xml | 3 + app/core/src/main/res/values/strings.xml | 3 + .../java/com/topjohnwu/magisk/wear/WearUi.kt | 39 +-- .../magisk/wear/component/LoadingScreen.kt | 23 ++ .../topjohnwu/magisk/wear/home/HomeScreen.kt | 234 ++++++++++++++++++ .../topjohnwu/magisk/wear/home/HomeStatus.kt | 47 ++++ .../magisk/wear/home/HomeStatusTest.kt | 49 ++++ 8 files changed, 364 insertions(+), 37 deletions(-) create mode 100644 app/wear/src/main/java/com/topjohnwu/magisk/wear/component/LoadingScreen.kt create mode 100644 app/wear/src/main/java/com/topjohnwu/magisk/wear/home/HomeScreen.kt create mode 100644 app/wear/src/main/java/com/topjohnwu/magisk/wear/home/HomeStatus.kt create mode 100644 app/wear/src/test/java/com/topjohnwu/magisk/wear/home/HomeStatusTest.kt diff --git a/app/core/src/main/res/values-pl/strings.xml b/app/core/src/main/res/values-pl/strings.xml index 22188a7bdc4f3..0e2ff36c60e68 100644 --- a/app/core/src/main/res/values-pl/strings.xml +++ b/app/core/src/main/res/values-pl/strings.xml @@ -213,4 +213,7 @@ Brak pasujących plików w folderze Download + Działa + Zainstalowany · %1$d + Odinstaluj diff --git a/app/core/src/main/res/values/resources.xml b/app/core/src/main/res/values/resources.xml index 849fbe3de819d..d32d3c8c61d9a 100644 --- a/app/core/src/main/res/values/resources.xml +++ b/app/core/src/main/res/values/resources.xml @@ -8,6 +8,9 @@ SharedUID + + %1$s: %2$s + PayPal Patreon Twitter diff --git a/app/core/src/main/res/values/strings.xml b/app/core/src/main/res/values/strings.xml index b8665014adabd..b10e802fec9ed 100644 --- a/app/core/src/main/res/values/strings.xml +++ b/app/core/src/main/res/values/strings.xml @@ -243,4 +243,7 @@ No matching files in the Download folder + Running + Installed · %1$d + Uninstall diff --git a/app/wear/src/main/java/com/topjohnwu/magisk/wear/WearUi.kt b/app/wear/src/main/java/com/topjohnwu/magisk/wear/WearUi.kt index 6cf5c3ba9c3c7..aaa44cc5d39a9 100644 --- a/app/wear/src/main/java/com/topjohnwu/magisk/wear/WearUi.kt +++ b/app/wear/src/main/java/com/topjohnwu/magisk/wear/WearUi.kt @@ -10,7 +10,6 @@ import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider @@ -30,17 +29,12 @@ import androidx.compose.ui.text.style.TextAlign import androidx.core.net.toUri import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.viewmodel.navigation3.rememberViewModelStoreNavEntryDecorator -import androidx.navigation3.runtime.NavKey import androidx.navigation3.runtime.entryProvider import androidx.navigation3.runtime.rememberSaveableStateHolderNavEntryDecorator import androidx.navigation3.ui.NavDisplay -import androidx.wear.compose.foundation.lazy.TransformingLazyColumn -import androidx.wear.compose.foundation.lazy.rememberTransformingLazyColumnState import androidx.wear.compose.material3.AlertDialog import androidx.wear.compose.material3.AlertDialogDefaults import androidx.wear.compose.material3.AppScaffold -import androidx.wear.compose.material3.Button -import androidx.wear.compose.material3.ListHeader import androidx.wear.compose.material3.ScreenScaffold import androidx.wear.compose.material3.Text import androidx.wear.compose.material3.TimeText @@ -54,6 +48,7 @@ import com.topjohnwu.magisk.ui.flash.sanitizeDisplayName import com.topjohnwu.magisk.ui.navigation.Route import com.topjohnwu.magisk.ui.unsupportedMessages import com.topjohnwu.magisk.wear.files.PickScreen +import com.topjohnwu.magisk.wear.home.HomeScreen import com.topjohnwu.magisk.wear.nav.LocalWearNavigator import com.topjohnwu.magisk.wear.nav.WearNavigator import com.topjohnwu.magisk.wear.nav.WearRoute @@ -113,7 +108,7 @@ class WearUi( // Swipe-to-dismiss, and predictive back from API 36 sceneStrategies = listOf(rememberSwipeDismissableSceneStrategy()), entryProvider = entryProvider { - entry { MainPlaceholder(navigator) } + entry { HomeScreen(navigator) } entry { Placeholder(stringResource(CoreR.string.denylist)) } @@ -261,36 +256,6 @@ private fun Placeholder(title: String) { } } -/** Stands in for the home screen: only reaches the other screens. */ -@Composable -private fun MainPlaceholder(navigator: WearNavigator) { - val destinations: List> = listOf( - CoreR.string.superuser to WearRoute.Superuser, - CoreR.string.modules to WearRoute.Modules, - CoreR.string.logs to WearRoute.Logs, - CoreR.string.settings to WearRoute.Settings, - CoreR.string.install to WearRoute.Install, - ) - val state = rememberTransformingLazyColumnState() - ScreenScaffold(state) { contentPadding -> - TransformingLazyColumn(state = state, contentPadding = contentPadding) { - item { - ListHeader { Text(stringResource(CoreR.string.section_home)) } - } - destinations.forEach { (title, key) -> - item { - Button( - onClick = { navigator.navigate(key) }, - modifier = Modifier.fillMaxWidth(), - ) { - Text(stringResource(title)) - } - } - } - } - } -} - /** Shows each problem found by [unsupportedMessages] in turn, like the phone app on startup. */ @Composable private fun UnsupportedDialogs(messages: List>) { diff --git a/app/wear/src/main/java/com/topjohnwu/magisk/wear/component/LoadingScreen.kt b/app/wear/src/main/java/com/topjohnwu/magisk/wear/component/LoadingScreen.kt new file mode 100644 index 0000000000000..0cbb4607a5d28 --- /dev/null +++ b/app/wear/src/main/java/com/topjohnwu/magisk/wear/component/LoadingScreen.kt @@ -0,0 +1,23 @@ +package com.topjohnwu.magisk.wear.component + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.wear.compose.material3.CircularProgressIndicator +import androidx.wear.compose.material3.ScreenScaffold + +/** A screen with only a progress indicator, shown while its content is not ready. */ +@Composable +fun LoadingScreen(modifier: Modifier = Modifier) { + ScreenScaffold(modifier = modifier) { contentPadding -> + Box( + modifier = Modifier.fillMaxSize().padding(contentPadding), + contentAlignment = Alignment.Center, + ) { + CircularProgressIndicator() + } + } +} diff --git a/app/wear/src/main/java/com/topjohnwu/magisk/wear/home/HomeScreen.kt b/app/wear/src/main/java/com/topjohnwu/magisk/wear/home/HomeScreen.kt new file mode 100644 index 0000000000000..f37d9b0e0cd91 --- /dev/null +++ b/app/wear/src/main/java/com/topjohnwu/magisk/wear/home/HomeScreen.kt @@ -0,0 +1,234 @@ +package com.topjohnwu.magisk.wear.home + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.BugReport +import androidx.compose.material.icons.filled.Delete +import androidx.compose.material.icons.filled.Download +import androidx.compose.material.icons.filled.Extension +import androidx.compose.material.icons.filled.Security +import androidx.compose.material.icons.filled.Settings +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.lifecycle.viewmodel.compose.viewModel +import androidx.navigation3.runtime.NavKey +import androidx.wear.compose.foundation.lazy.TransformingLazyColumn +import androidx.wear.compose.foundation.lazy.rememberTransformingLazyColumnState +import androidx.wear.compose.material3.AlertDialog +import androidx.wear.compose.material3.AlertDialogDefaults +import androidx.wear.compose.material3.Button +import androidx.wear.compose.material3.FilledTonalButton +import androidx.wear.compose.material3.Icon +import androidx.wear.compose.material3.ListHeader +import androidx.wear.compose.material3.MaterialTheme +import androidx.wear.compose.material3.OutlinedButton +import androidx.wear.compose.material3.ScreenScaffold +import androidx.wear.compose.material3.Text +import com.topjohnwu.magisk.arch.VMFactory +import com.topjohnwu.magisk.core.BuildConfig +import com.topjohnwu.magisk.core.Info +import com.topjohnwu.magisk.ui.home.HomeViewModel +import com.topjohnwu.magisk.wear.component.LoadingScreen +import com.topjohnwu.magisk.wear.nav.CollectNavEvents +import com.topjohnwu.magisk.wear.nav.WearNavigator +import com.topjohnwu.magisk.wear.nav.WearRoute +import com.topjohnwu.magisk.core.R as CoreR + +private class Shortcut(val label: Int, val icon: ImageVector, val key: NavKey) + +private val shortcuts = listOf( + Shortcut(CoreR.string.superuser, Icons.Filled.Security, WearRoute.Superuser), + Shortcut(CoreR.string.modules, Icons.Filled.Extension, WearRoute.Modules), + Shortcut(CoreR.string.logs, Icons.Filled.BugReport, WearRoute.Logs), + Shortcut(CoreR.string.settings, Icons.Filled.Settings, WearRoute.Settings), +) + +@Composable +fun HomeScreen( + navigator: WearNavigator, + viewModel: HomeViewModel = viewModel(factory = VMFactory), +) { + val uiState by viewModel.uiState.collectAsStateWithLifecycle() + + // Reload whenever the screen is shown again, like the phone app does when its tab is selected + LaunchedEffect(viewModel) { + viewModel.startLoading() + } + CollectNavEvents(viewModel, navigator) + EnvFixDialog(uiState.envFixCode, viewModel, navigator) + + // Kept across the loading screen, so the list doesn't scroll back when it ends + val state = rememberTransformingLazyColumnState() + + if (uiState.showLoading) { + // Fixing the environment runs as root and then reboots, so block the screen meanwhile + LoadingScreen() + return + } + + // Recomposed whenever uiState changes, so this follows every reload + val status = HomeStatus.from(Info.env, Info.isZygiskEnabled, Info.ramdisk) + + ScreenScaffold(state) { contentPadding -> + TransformingLazyColumn(state = state, contentPadding = contentPadding) { + item { + ListHeader { Text(stringResource(CoreR.string.magisk)) } + } + item { + StatusCard(status, uiState.magiskState) + } + if (status.installed) { + shortcuts.forEach { shortcut -> + item { + FilledTonalButton( + onClick = { navigator.navigate(shortcut.key) }, + icon = { Icon(shortcut.icon, contentDescription = null) }, + label = { Text(stringResource(shortcut.label)) }, + modifier = Modifier.fillMaxWidth(), + ) + } + } + } + item { + Button( + onClick = { navigator.navigate(WearRoute.Install) }, + icon = { Icon(Icons.Filled.Download, contentDescription = null) }, + label = { Text(stringResource(CoreR.string.install)) }, + modifier = Modifier.fillMaxWidth(), + ) + } + if (status.installed) { + item { + OutlinedButton( + onClick = { navigator.navigate(WearRoute.Restore) }, + icon = { Icon(Icons.Filled.Delete, contentDescription = null) }, + label = { Text(stringResource(CoreR.string.wear_home_uninstall)) }, + modifier = Modifier.fillMaxWidth(), + ) + } + } + } + } +} + +/** Asks to fix the environment when the check run by [HomeViewModel] reports a problem. */ +@Composable +private fun EnvFixDialog(code: Int, viewModel: HomeViewModel, navigator: WearNavigator) { + // Survives recreation once the event is consumed, like the phone app's dialog state + var shownCode by rememberSaveable { mutableIntStateOf(0) } + var visible by rememberSaveable { mutableStateOf(false) } + + LaunchedEffect(code) { + if (code != 0) { + shownCode = code + visible = true + viewModel.onEnvFixConsumed() + } + } + + // Same rule as the phone app: a mismatched version can only be fixed by reinstalling + val needsFullFix = shownCode == 2 || + Info.env.versionCode != BuildConfig.APP_VERSION_CODE || + Info.env.versionString != BuildConfig.APP_VERSION_NAME + + AlertDialog( + visible = visible, + onDismissRequest = { visible = false }, + title = { Text(stringResource(CoreR.string.env_fix_title)) }, + text = { + Text( + stringResource( + if (needsFullFix) CoreR.string.env_full_fix_msg else CoreR.string.env_fix_msg + ) + ) + }, + confirmButton = { + AlertDialogDefaults.ConfirmButton(onClick = { + visible = false + if (needsFullFix) navigator.navigate(WearRoute.Install) else viewModel.fixEnv() + }) + }, + dismissButton = { + AlertDialogDefaults.DismissButton(onClick = { visible = false }) + }, + ) +} + +@Composable +private fun StatusCard(status: HomeStatus, magiskState: HomeViewModel.State) { + val colors = MaterialTheme.colorScheme + Column( + modifier = Modifier + .fillMaxWidth() + .background(colors.surfaceContainer, MaterialTheme.shapes.large) + .padding(horizontal = 16.dp, vertical = 12.dp), + horizontalAlignment = Alignment.CenterHorizontally, + ) { + if (status.installed) { + Row( + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + text = status.version ?: stringResource(CoreR.string.not_available), + style = MaterialTheme.typography.titleLarge, + ) + Text( + text = stringResource( + if (magiskState == HomeViewModel.State.OUTDATED) CoreR.string.update_available + else CoreR.string.wear_home_running + ), + style = MaterialTheme.typography.labelSmall, + color = colors.primary, + ) + } + status.versionCode?.let { + Text( + text = stringResource(CoreR.string.wear_home_installed_code, it), + style = MaterialTheme.typography.bodySmall, + color = colors.onSurfaceVariant, + ) + } + } else { + Text( + text = stringResource(CoreR.string.not_installed), + style = MaterialTheme.typography.titleMedium, + color = colors.error, + ) + } + Text( + text = stringResource( + CoreR.string.wear_home_status_item, + stringResource(CoreR.string.zygisk), + stringResource(if (status.zygisk) CoreR.string.enabled else CoreR.string.disabled), + ), + style = MaterialTheme.typography.bodySmall, + color = colors.onSurfaceVariant, + ) + Text( + text = stringResource( + CoreR.string.wear_home_status_item, + stringResource(CoreR.string.ramdisk), + stringResource(if (status.ramdisk) CoreR.string.yes else CoreR.string.no), + ), + style = MaterialTheme.typography.bodySmall, + color = colors.onSurfaceVariant, + ) + } +} diff --git a/app/wear/src/main/java/com/topjohnwu/magisk/wear/home/HomeStatus.kt b/app/wear/src/main/java/com/topjohnwu/magisk/wear/home/HomeStatus.kt new file mode 100644 index 0000000000000..74e70d3ef7a16 --- /dev/null +++ b/app/wear/src/main/java/com/topjohnwu/magisk/wear/home/HomeStatus.kt @@ -0,0 +1,47 @@ +package com.topjohnwu.magisk.wear.home + +import com.topjohnwu.magisk.core.Const +import com.topjohnwu.magisk.core.Info + +/** + * What the home screen shows about the installed Magisk. [version] and [versionCode] are only + * set when a supported Magisk is active, the same rule the phone app uses for its version text. + */ +data class HomeStatus( + val version: String?, + val versionCode: Int?, + val installed: Boolean, + val zygisk: Boolean, + val ramdisk: Boolean, +) { + companion object +} + +/** The status of [env], with [Info.isRooted] deciding whether its version can be trusted. */ +fun HomeStatus.Companion.from(env: Info.Env, zygisk: Boolean, ramdisk: Boolean): HomeStatus { + // Env keeps the raw version code private: its versionCode is already -1 when the daemon + // is unreachable, unsupported or the app has no root, which of() treats the same way + return of(env.versionString, env.versionCode, Info.isRooted, zygisk, ramdisk) +} + +/** + * Build the status from the raw values that [Info.Env] is created from, following the rule + * of [Info.Env.versionCode] and [Info.Env.isActive]: Magisk counts as installed only when + * [code] is at least [Const.Version.MIN_VERCODE] and the app is [rooted]. + */ +fun HomeStatus.Companion.of( + versionString: String, + code: Int, + rooted: Boolean, + zygisk: Boolean, + ramdisk: Boolean, +): HomeStatus { + val installed = code >= Const.Version.MIN_VERCODE && rooted + return HomeStatus( + version = versionString.takeIf { installed && it.isNotEmpty() }, + versionCode = code.takeIf { installed }, + installed = installed, + zygisk = zygisk, + ramdisk = ramdisk, + ) +} diff --git a/app/wear/src/test/java/com/topjohnwu/magisk/wear/home/HomeStatusTest.kt b/app/wear/src/test/java/com/topjohnwu/magisk/wear/home/HomeStatusTest.kt new file mode 100644 index 0000000000000..6bd94656c9f49 --- /dev/null +++ b/app/wear/src/test/java/com/topjohnwu/magisk/wear/home/HomeStatusTest.kt @@ -0,0 +1,49 @@ +package com.topjohnwu.magisk.wear.home + +import com.topjohnwu.magisk.core.Const +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +// Only of() is tested: touching Info would run its initializer, which needs a real Android +class HomeStatusTest { + + @Test + fun installed() { + val status = HomeStatus.of("31.1-wear", 31100, rooted = true, zygisk = true, ramdisk = false) + assertTrue(status.installed) + assertEquals("31.1-wear", status.version) + assertEquals(31100, status.versionCode) + assertTrue(status.zygisk) + assertFalse(status.ramdisk) + } + + @Test + fun daemonNotRunning() { + val status = HomeStatus.of("", -1, rooted = false, zygisk = false, ramdisk = true) + assertFalse(status.installed) + assertNull(status.version) + assertNull(status.versionCode) + assertTrue(status.ramdisk) + } + + @Test + fun unsupportedVersion() { + val status = HomeStatus.of( + "21.4", Const.Version.MIN_VERCODE - 1, rooted = true, zygisk = false, ramdisk = false + ) + assertFalse(status.installed) + assertNull(status.version) + assertNull(status.versionCode) + } + + @Test + fun notRooted() { + val status = HomeStatus.of("31.1-wear", 31100, rooted = false, zygisk = false, ramdisk = false) + assertFalse(status.installed) + assertNull(status.version) + assertNull(status.versionCode) + } +} From 1a46c63f7c435a96e924f386b7d08abb8c597fc9 Mon Sep 17 00:00:00 2001 From: Jakub Mendyka Date: Mon, 23 Nov 2026 16:31:47 +0100 Subject: [PATCH 06/12] Add Wear superuser screens Replace the Superuser placeholders with a list of apps that have a policy and a per-app detail screen. Each row shows the app icon, its name and the kind of root it gets, with a switch that flips the policy between Allow and Deny; tapping the row opens the details. The header links to the grant screen and the list ends with a link to the logs. The details toggle restricted root, notifications and logging, and revoke the policy after a confirmation, then return to the list. Like on the phone, changing a policy asks for authentication first when the Superuser setting requires it, which then replaces the confirmation of a revoke. Both screens use one activity-scoped SuperuserViewModel, as the phone UI does, so edits made in the details show up in the list immediately. App icons are drawn once at their small display size and cached. rootLabel picks the root kind label and is covered by unit tests. Assisted-by: Claude Opus 5.5 --- app/core/src/main/res/values-pl/strings.xml | 4 + app/core/src/main/res/values/strings.xml | 4 + .../java/com/topjohnwu/magisk/wear/WearUi.kt | 19 +- .../magisk/wear/component/AppIcon.kt | 79 +++++++ .../magisk/wear/superuser/RootLabel.kt | 14 ++ .../wear/superuser/SuperuserDetailScreen.kt | 194 ++++++++++++++++++ .../magisk/wear/superuser/SuperuserScreen.kt | 152 ++++++++++++++ .../topjohnwu/magisk/wear/theme/WearTheme.kt | 13 ++ .../magisk/wear/superuser/RootLabelTest.kt | 39 ++++ 9 files changed, 515 insertions(+), 3 deletions(-) create mode 100644 app/wear/src/main/java/com/topjohnwu/magisk/wear/component/AppIcon.kt create mode 100644 app/wear/src/main/java/com/topjohnwu/magisk/wear/superuser/RootLabel.kt create mode 100644 app/wear/src/main/java/com/topjohnwu/magisk/wear/superuser/SuperuserDetailScreen.kt create mode 100644 app/wear/src/main/java/com/topjohnwu/magisk/wear/superuser/SuperuserScreen.kt create mode 100644 app/wear/src/test/java/com/topjohnwu/magisk/wear/superuser/RootLabelTest.kt diff --git a/app/core/src/main/res/values-pl/strings.xml b/app/core/src/main/res/values-pl/strings.xml index 0e2ff36c60e68..ecf8229a96777 100644 --- a/app/core/src/main/res/values-pl/strings.xml +++ b/app/core/src/main/res/values-pl/strings.xml @@ -216,4 +216,8 @@ Działa Zainstalowany · %1$d Odinstaluj + Pełny root + Ograniczony root + Bez roota + Logi su diff --git a/app/core/src/main/res/values/strings.xml b/app/core/src/main/res/values/strings.xml index b10e802fec9ed..856713c7242f5 100644 --- a/app/core/src/main/res/values/strings.xml +++ b/app/core/src/main/res/values/strings.xml @@ -246,4 +246,8 @@ Running Installed · %1$d Uninstall + Full root + Restricted root + No root + Superuser logs diff --git a/app/wear/src/main/java/com/topjohnwu/magisk/wear/WearUi.kt b/app/wear/src/main/java/com/topjohnwu/magisk/wear/WearUi.kt index aaa44cc5d39a9..27bfd74517bac 100644 --- a/app/wear/src/main/java/com/topjohnwu/magisk/wear/WearUi.kt +++ b/app/wear/src/main/java/com/topjohnwu/magisk/wear/WearUi.kt @@ -28,6 +28,7 @@ import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.core.net.toUri import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.lifecycle.viewmodel.compose.viewModel import androidx.lifecycle.viewmodel.navigation3.rememberViewModelStoreNavEntryDecorator import androidx.navigation3.runtime.entryProvider import androidx.navigation3.runtime.rememberSaveableStateHolderNavEntryDecorator @@ -39,6 +40,7 @@ import androidx.wear.compose.material3.ScreenScaffold import androidx.wear.compose.material3.Text import androidx.wear.compose.material3.TimeText import androidx.wear.compose.navigation3.rememberSwipeDismissableSceneStrategy +import com.topjohnwu.magisk.arch.VMFactory import com.topjohnwu.magisk.core.Config import com.topjohnwu.magisk.core.Const import com.topjohnwu.magisk.core.base.ActivityExtension @@ -46,6 +48,7 @@ import com.topjohnwu.magisk.ui.flash.FlashUtils import com.topjohnwu.magisk.ui.flash.queryDisplayName import com.topjohnwu.magisk.ui.flash.sanitizeDisplayName import com.topjohnwu.magisk.ui.navigation.Route +import com.topjohnwu.magisk.ui.superuser.SuperuserViewModel import com.topjohnwu.magisk.ui.unsupportedMessages import com.topjohnwu.magisk.wear.files.PickScreen import com.topjohnwu.magisk.wear.home.HomeScreen @@ -53,6 +56,8 @@ import com.topjohnwu.magisk.wear.nav.LocalWearNavigator import com.topjohnwu.magisk.wear.nav.WearNavigator import com.topjohnwu.magisk.wear.nav.WearRoute import com.topjohnwu.magisk.wear.nav.rememberWearNavigator +import com.topjohnwu.magisk.wear.superuser.SuperuserDetailScreen +import com.topjohnwu.magisk.wear.superuser.SuperuserScreen import com.topjohnwu.magisk.wear.theme.WearTheme import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.flow.MutableStateFlow @@ -115,15 +120,23 @@ class WearUi( entry { Placeholder(stringResource(CoreR.string.flash_screen_title)) } - entry { - Placeholder(stringResource(CoreR.string.superuser)) + entry { key -> + // Owned by the activity, so the list and its details share one + // copy of the policies, like the phone app + val vm: SuperuserViewModel = viewModel( + viewModelStoreOwner = activity, factory = VMFactory + ) + SuperuserDetailScreen(key.uid, vm, navigator) } entry { Placeholder(stringResource(CoreR.string.superuser_grant)) } entry { key -> Placeholder(key.name) } entry { - Placeholder(stringResource(CoreR.string.superuser)) + val vm: SuperuserViewModel = viewModel( + viewModelStoreOwner = activity, factory = VMFactory + ) + SuperuserScreen(vm, navigator) } entry { Placeholder(stringResource(CoreR.string.logs)) diff --git a/app/wear/src/main/java/com/topjohnwu/magisk/wear/component/AppIcon.kt b/app/wear/src/main/java/com/topjohnwu/magisk/wear/component/AppIcon.kt new file mode 100644 index 0000000000000..7876b77112914 --- /dev/null +++ b/app/wear/src/main/java/com/topjohnwu/magisk/wear/component/AppIcon.kt @@ -0,0 +1,79 @@ +package com.topjohnwu.magisk.wear.component + +import android.content.Context +import android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES +import android.util.LruCache +import androidx.compose.foundation.Image +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.size +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.ImageBitmap +import androidx.compose.ui.graphics.asImageBitmap +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.unit.Dp +import androidx.core.graphics.drawable.toBitmap +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext + +private class CachedIcon(val lastUpdateTime: Long, val bitmap: ImageBitmap) + +// Keep recently shown icons so scrolling back through app lists doesn't reload them +private val iconCache = LruCache(64) + +private fun cacheKey(packageName: String, sizePx: Int) = "$packageName:$sizePx" + +/** + * Returns the icon of [packageName] drawn at [sizePx], reusing the cached one unless the + * package has been updated since it was loaded. Icons are drawn once at their display size, + * since the watch shows them small. + */ +private fun loadAppIcon(context: Context, packageName: String, sizePx: Int): ImageBitmap { + val pm = context.packageManager + // Lists include apps that are only installed for other users + val info = runCatching { pm.getPackageInfo(packageName, MATCH_UNINSTALLED_PACKAGES) }.getOrNull() + ?: return pm.defaultActivityIcon.toBitmap(sizePx, sizePx).asImageBitmap() + val key = cacheKey(packageName, sizePx) + iconCache[key]?.let { cached -> + if (cached.lastUpdateTime == info.lastUpdateTime) return cached.bitmap + } + val drawable = info.applicationInfo?.loadIcon(pm) ?: pm.defaultActivityIcon + val bitmap = drawable.toBitmap(sizePx, sizePx).asImageBitmap() + iconCache.put(key, CachedIcon(info.lastUpdateTime, bitmap)) + return bitmap +} + +@Composable +fun AppIcon( + packageName: String, + size: Dp, + modifier: Modifier = Modifier, + contentDescription: String? = null, +) { + val context = LocalContext.current + val sizePx = with(LocalDensity.current) { size.roundToPx() }.coerceAtLeast(1) + // Show the cached icon right away, then make sure it is still up to date + var bitmap by remember(packageName, sizePx) { + mutableStateOf(iconCache[cacheKey(packageName, sizePx)]?.bitmap) + } + LaunchedEffect(packageName, sizePx) { + bitmap = withContext(Dispatchers.IO) { loadAppIcon(context, packageName, sizePx) } + } + val icon = bitmap + if (icon == null) { + // Reserve the space while loading + Box(modifier = modifier.size(size)) + } else { + Image( + bitmap = icon, + contentDescription = contentDescription, + modifier = modifier.size(size), + ) + } +} diff --git a/app/wear/src/main/java/com/topjohnwu/magisk/wear/superuser/RootLabel.kt b/app/wear/src/main/java/com/topjohnwu/magisk/wear/superuser/RootLabel.kt new file mode 100644 index 0000000000000..b3578c5425bdc --- /dev/null +++ b/app/wear/src/main/java/com/topjohnwu/magisk/wear/superuser/RootLabel.kt @@ -0,0 +1,14 @@ +package com.topjohnwu.magisk.wear.superuser + +import androidx.annotation.StringRes +import com.topjohnwu.magisk.ui.superuser.PolicyItem +import com.topjohnwu.magisk.core.R as CoreR + +/** The kind of root access [item] currently gets, shown under the app name. */ +@StringRes +fun rootLabel(item: PolicyItem): Int = when { + // Checked first: a restricted policy also counts as enabled + item.isRestricted -> CoreR.string.wear_root_restricted + item.isEnabled -> CoreR.string.wear_root_full + else -> CoreR.string.wear_root_none +} diff --git a/app/wear/src/main/java/com/topjohnwu/magisk/wear/superuser/SuperuserDetailScreen.kt b/app/wear/src/main/java/com/topjohnwu/magisk/wear/superuser/SuperuserDetailScreen.kt new file mode 100644 index 0000000000000..9f1b878483af3 --- /dev/null +++ b/app/wear/src/main/java/com/topjohnwu/magisk/wear/superuser/SuperuserDetailScreen.kt @@ -0,0 +1,194 @@ +package com.topjohnwu.magisk.wear.superuser + +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Cancel +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.wear.compose.foundation.lazy.TransformingLazyColumn +import androidx.wear.compose.foundation.lazy.rememberTransformingLazyColumnState +import androidx.wear.compose.material3.AlertDialog +import androidx.wear.compose.material3.AlertDialogDefaults +import androidx.wear.compose.material3.Button +import androidx.wear.compose.material3.Icon +import androidx.wear.compose.material3.MaterialTheme +import androidx.wear.compose.material3.ScreenScaffold +import androidx.wear.compose.material3.SwitchButton +import androidx.wear.compose.material3.Text +import com.topjohnwu.magisk.core.Config +import com.topjohnwu.magisk.ui.component.rememberBiometricAuth +import com.topjohnwu.magisk.ui.navigation.Route +import com.topjohnwu.magisk.ui.superuser.PolicyItem +import com.topjohnwu.magisk.ui.superuser.SuperuserViewModel +import com.topjohnwu.magisk.wear.component.AppIcon +import com.topjohnwu.magisk.wear.component.LoadingScreen +import com.topjohnwu.magisk.wear.nav.WearNavigator +import com.topjohnwu.magisk.wear.theme.destructiveButtonColors +import com.topjohnwu.magisk.core.R as CoreR + +/** Settings of the policy of [uid]. [viewModel] is the one [SuperuserScreen] uses. */ +@Composable +fun SuperuserDetailScreen( + uid: Int, + viewModel: SuperuserViewModel, + navigator: WearNavigator, +) { + val uiState by viewModel.uiState.collectAsStateWithLifecycle() + // After a revoke, the policy is removed from the state while this screen is still + // animating out, so keep showing the last known content instead of a blank page. + val lastItems = remember(uid) { LastItems() } + val currentItems = uiState.policies.filter { it.uid == uid } + val policy = currentItems + .also { if (it.isNotEmpty()) lastItems.value = it } + .ifEmpty { lastItems.value } + .firstOrNull() + + // Only leave if this screen is still on top: a revoke confirmed twice, or the policy + // vanishing right after a revoke, must not pop the screen below it + val leave: () -> Unit = { + if (navigator.current() == Route.SuperuserDetail(uid)) navigator.pop() + } + + // If the policy disappears while this screen is still shown (e.g. the app was uninstalled), + // leave instead of showing stale content. After a revoke, we have already navigated away. + val isGone = !uiState.loading && currentItems.isEmpty() + LaunchedEffect(isGone) { + if (isGone) leave() + } + + LaunchedEffect(Unit) { + viewModel.refreshSuRestrict() + if (uiState.policies.isEmpty()) { + viewModel.startLoading() + } + } + + var showRevoke by rememberSaveable { mutableStateOf(false) } + // Asks for authentication first when the Superuser setting requires it + val requireAuth = rememberBiometricAuth() + val state = rememberTransformingLazyColumnState() + + if (uiState.loading) { + LoadingScreen() + return + } + + if (policy == null) return + + ScreenScaffold(state) { contentPadding -> + TransformingLazyColumn(state = state, contentPadding = contentPadding) { + item { + AppHeader(policy) + } + if (uiState.suRestrict || policy.isRestricted) { + item { + SwitchButton( + checked = policy.isRestricted, + onCheckedChange = { requireAuth { viewModel.toggleRestrict(policy) } }, + label = { Text(stringResource(CoreR.string.settings_su_restrict_title)) }, + modifier = Modifier.fillMaxWidth(), + ) + } + } + item { + SwitchButton( + checked = policy.notification, + onCheckedChange = { viewModel.updateNotify(policy) }, + label = { Text(stringResource(CoreR.string.superuser_toggle_notification)) }, + modifier = Modifier.fillMaxWidth(), + ) + } + item { + SwitchButton( + checked = policy.logging, + onCheckedChange = { viewModel.updateLogging(policy) }, + label = { Text(stringResource(CoreR.string.logs)) }, + modifier = Modifier.fillMaxWidth(), + ) + } + item { + Button( + onClick = { + // Authentication replaces the confirmation, like on the phone + if (Config.suAuth) { + requireAuth { viewModel.performDelete(policy) { leave() } } + } else { + showRevoke = true + } + }, + colors = destructiveButtonColors(), + icon = { Icon(Icons.Filled.Cancel, contentDescription = null) }, + label = { Text(stringResource(CoreR.string.superuser_toggle_revoke)) }, + modifier = Modifier.fillMaxWidth(), + ) + } + } + } + + AlertDialog( + visible = showRevoke, + onDismissRequest = { showRevoke = false }, + title = { Text(stringResource(CoreR.string.su_revoke_title)) }, + text = { Text(stringResource(CoreR.string.su_revoke_msg, policy.appName)) }, + confirmButton = { + AlertDialogDefaults.ConfirmButton(onClick = { + showRevoke = false + viewModel.performDelete(policy) { leave() } + }) + }, + dismissButton = { + AlertDialogDefaults.DismissButton(onClick = { showRevoke = false }) + }, + ) +} + +@Composable +private fun AppHeader(item: PolicyItem) { + Column( + modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp), + horizontalAlignment = Alignment.CenterHorizontally, + ) { + AppIcon( + packageName = item.packageName, + size = 40.dp, + contentDescription = item.appName, + ) + Text( + text = item.title, + style = MaterialTheme.typography.titleMedium, + textAlign = TextAlign.Center, + modifier = Modifier.padding(top = 4.dp), + ) + Text( + text = item.packageName, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + textAlign = TextAlign.Center, + ) + if (item.isSharedUid) { + Text( + text = stringResource(CoreR.string.shared_uid), + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.primary, + ) + } + } +} + +// Plain holder: updating it must not trigger recomposition +private class LastItems { + var value: List = emptyList() +} diff --git a/app/wear/src/main/java/com/topjohnwu/magisk/wear/superuser/SuperuserScreen.kt b/app/wear/src/main/java/com/topjohnwu/magisk/wear/superuser/SuperuserScreen.kt new file mode 100644 index 0000000000000..bb85dce332e5b --- /dev/null +++ b/app/wear/src/main/java/com/topjohnwu/magisk/wear/superuser/SuperuserScreen.kt @@ -0,0 +1,152 @@ +package com.topjohnwu.magisk.wear.superuser + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Add +import androidx.compose.material.icons.filled.BugReport +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.wear.compose.foundation.lazy.TransformingLazyColumn +import androidx.wear.compose.foundation.lazy.items +import androidx.wear.compose.foundation.lazy.rememberTransformingLazyColumnState +import androidx.wear.compose.material3.FilledTonalButton +import androidx.wear.compose.material3.Icon +import androidx.wear.compose.material3.IconButton +import androidx.wear.compose.material3.ListHeader +import androidx.wear.compose.material3.MaterialTheme +import androidx.wear.compose.material3.ScreenScaffold +import androidx.wear.compose.material3.SplitSwitchButton +import androidx.wear.compose.material3.Text +import com.topjohnwu.magisk.ui.component.rememberBiometricAuth +import com.topjohnwu.magisk.ui.navigation.Route +import com.topjohnwu.magisk.ui.superuser.PolicyItem +import com.topjohnwu.magisk.ui.superuser.SuperuserViewModel +import com.topjohnwu.magisk.wear.component.AppIcon +import com.topjohnwu.magisk.wear.component.LoadingScreen +import com.topjohnwu.magisk.wear.nav.CollectNavEvents +import com.topjohnwu.magisk.wear.nav.WearNavigator +import com.topjohnwu.magisk.wear.nav.WearRoute +import com.topjohnwu.magisk.core.R as CoreR + +/** + * The apps with a Superuser policy. [viewModel] is shared with [SuperuserDetailScreen], so + * changes made there show up here right away. + */ +@Composable +fun SuperuserScreen( + viewModel: SuperuserViewModel, + navigator: WearNavigator, +) { + val uiState by viewModel.uiState.collectAsStateWithLifecycle() + // Asks for authentication first when the Superuser setting requires it + val requireAuth = rememberBiometricAuth() + + // Reload whenever the screen is shown again, like the phone app does when its tab is selected + LaunchedEffect(viewModel) { + viewModel.startLoading() + } + CollectNavEvents(viewModel, navigator) + + // Kept across the loading screen, so the list doesn't scroll back when it ends + val state = rememberTransformingLazyColumnState() + + if (uiState.loading) { + LoadingScreen() + return + } + + ScreenScaffold(state) { contentPadding -> + TransformingLazyColumn(state = state, contentPadding = contentPadding) { + item { + ListHeader { + Row(verticalAlignment = Alignment.CenterVertically) { + Text(stringResource(CoreR.string.superuser)) + IconButton(onClick = { navigator.navigate(Route.SuperuserGrant) }) { + Icon( + Icons.Filled.Add, + contentDescription = stringResource(CoreR.string.superuser_grant), + ) + } + } + } + } + if (uiState.policies.isEmpty()) { + item { + Text( + text = stringResource(CoreR.string.superuser_policy_none), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + textAlign = TextAlign.Center, + modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp), + ) + } + } else { + items( + items = uiState.policies, + key = { "${it.uid}_${it.packageName}" }, + ) { item -> + PolicyRow( + item = item, + onToggle = { requireAuth { viewModel.togglePolicy(item) } }, + onDetail = { navigator.navigate(Route.SuperuserDetail(item.uid)) }, + ) + } + } + item { + FilledTonalButton( + onClick = { navigator.navigate(WearRoute.Logs) }, + icon = { Icon(Icons.Filled.BugReport, contentDescription = null) }, + label = { Text(stringResource(CoreR.string.wear_su_logs)) }, + modifier = Modifier.fillMaxWidth(), + ) + } + } + } +} + +@Composable +private fun PolicyRow( + item: PolicyItem, + onToggle: () -> Unit, + onDetail: () -> Unit, +) { + SplitSwitchButton( + checked = item.isEnabled, + // The view model flips the latest state, so quick repeated taps never get lost + onCheckedChange = { onToggle() }, + toggleContentDescription = item.appName, + onContainerClick = onDetail, + modifier = Modifier.fillMaxWidth(), + label = { + AppIcon(packageName = item.packageName, size = 28.dp) + Column( + modifier = Modifier.weight(1f).padding(start = 8.dp), + verticalArrangement = Arrangement.Center, + ) { + Text( + text = item.title, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + Text( + text = stringResource(rootLabel(item)), + style = MaterialTheme.typography.labelSmall, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + }, + ) +} diff --git a/app/wear/src/main/java/com/topjohnwu/magisk/wear/theme/WearTheme.kt b/app/wear/src/main/java/com/topjohnwu/magisk/wear/theme/WearTheme.kt index 959779d2bff28..105fbaee5cd57 100644 --- a/app/wear/src/main/java/com/topjohnwu/magisk/wear/theme/WearTheme.kt +++ b/app/wear/src/main/java/com/topjohnwu/magisk/wear/theme/WearTheme.kt @@ -2,6 +2,8 @@ package com.topjohnwu.magisk.wear.theme import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.Color +import androidx.wear.compose.material3.ButtonColors +import androidx.wear.compose.material3.ButtonDefaults import androidx.wear.compose.material3.ColorScheme import androidx.wear.compose.material3.MaterialTheme @@ -20,3 +22,14 @@ private val WearColorScheme = ColorScheme( fun WearTheme(content: @Composable () -> Unit) { MaterialTheme(colorScheme = WearColorScheme, content = content) } + +/** Colors of a button that removes or restores something and can't be undone. */ +@Composable +fun destructiveButtonColors(): ButtonColors { + val colors = MaterialTheme.colorScheme + return ButtonDefaults.buttonColors( + containerColor = colors.error, + contentColor = colors.onError, + iconColor = colors.onError, + ) +} diff --git a/app/wear/src/test/java/com/topjohnwu/magisk/wear/superuser/RootLabelTest.kt b/app/wear/src/test/java/com/topjohnwu/magisk/wear/superuser/RootLabelTest.kt new file mode 100644 index 0000000000000..b7a1872333e33 --- /dev/null +++ b/app/wear/src/test/java/com/topjohnwu/magisk/wear/superuser/RootLabelTest.kt @@ -0,0 +1,39 @@ +package com.topjohnwu.magisk.wear.superuser + +import com.topjohnwu.magisk.core.model.su.SuPolicy +import com.topjohnwu.magisk.ui.superuser.PolicyItem +import org.junit.Assert.assertEquals +import org.junit.Test +import com.topjohnwu.magisk.core.R as CoreR + +class RootLabelTest { + + // Built from a SuPolicy the same way SuperuserViewModel does + private fun item(policy: SuPolicy) = PolicyItem( + uid = policy.uid, + packageName = "com.example.app", + appName = "Example", + isSharedUid = false, + policyValue = policy.policy, + notification = policy.notification, + logging = policy.logging, + ) + + @Test + fun allowIsFullRoot() { + val label = rootLabel(item(SuPolicy(uid = 10123, policy = SuPolicy.ALLOW))) + assertEquals(CoreR.string.wear_root_full, label) + } + + @Test + fun restrictIsRestrictedRoot() { + val label = rootLabel(item(SuPolicy(uid = 10123, policy = SuPolicy.RESTRICT))) + assertEquals(CoreR.string.wear_root_restricted, label) + } + + @Test + fun denyIsNoRoot() { + val label = rootLabel(item(SuPolicy(uid = 10123, policy = SuPolicy.DENY))) + assertEquals(CoreR.string.wear_root_none, label) + } +} From 7f6d6087a5351524741aa905c18ac2292c0246d6 Mon Sep 17 00:00:00 2001 From: Jakub Mendyka Date: Mon, 23 Nov 2026 16:38:48 +0100 Subject: [PATCH 07/12] Add Wear root grant screen Replace the grant placeholder with a list of apps that had no policy when the screen opened. Tapping a row grants root and its "+" turns into a check mark with the kind of root it got; tapping again undoes the grant. The list ends with a switch that shows system apps. The mode chip at the top picks between full and restricted root for the next grant. It starts at the "restrict root capabilities" setting, which stays unchanged: toggleGrant now takes the mode, decided when the row is tapped, since the write happens later in the background and must not depend on what the setting is by then. A grant asks for authentication first when the Superuser setting requires it. New policies reach the Superuser list through the policy change event, as on the phone. Assisted-by: Claude Opus 5.5 --- app/core/src/main/res/values-pl/strings.xml | 1 + app/core/src/main/res/values/strings.xml | 1 + .../ui/superuser/SuperuserGrantViewModel.kt | 9 +- .../java/com/topjohnwu/magisk/wear/WearUi.kt | 8 +- .../magisk/wear/superuser/GrantScreen.kt | 188 ++++++++++++++++++ 5 files changed, 204 insertions(+), 3 deletions(-) create mode 100644 app/wear/src/main/java/com/topjohnwu/magisk/wear/superuser/GrantScreen.kt diff --git a/app/core/src/main/res/values-pl/strings.xml b/app/core/src/main/res/values-pl/strings.xml index ecf8229a96777..353833b9d2d30 100644 --- a/app/core/src/main/res/values-pl/strings.xml +++ b/app/core/src/main/res/values-pl/strings.xml @@ -220,4 +220,5 @@ Ograniczony root Bez roota Logi su + Przyznano · %1$s diff --git a/app/core/src/main/res/values/strings.xml b/app/core/src/main/res/values/strings.xml index 856713c7242f5..8a0b0fc658842 100644 --- a/app/core/src/main/res/values/strings.xml +++ b/app/core/src/main/res/values/strings.xml @@ -250,4 +250,5 @@ Restricted root No root Superuser logs + Granted · %1$s diff --git a/app/shared/src/main/java/com/topjohnwu/magisk/ui/superuser/SuperuserGrantViewModel.kt b/app/shared/src/main/java/com/topjohnwu/magisk/ui/superuser/SuperuserGrantViewModel.kt index a956b7c72329f..ccead32f2e7b5 100644 --- a/app/shared/src/main/java/com/topjohnwu/magisk/ui/superuser/SuperuserGrantViewModel.kt +++ b/app/shared/src/main/java/com/topjohnwu/magisk/ui/superuser/SuperuserGrantViewModel.kt @@ -136,7 +136,12 @@ class SuperuserGrantViewModel( fun setSortBy(s: AppSortBy) { _sortBy.value = s } fun toggleSortReverse() { _sortReverse.value = !_sortReverse.value } - fun toggleGrant(app: SuGrantAppState) { + /** + * Grants root to [app], or takes back a grant made here. A grant is [restricted] root, + * decided when this is called: the write happens later, and must not pick up a change of + * the setting made in between. + */ + fun toggleGrant(app: SuGrantAppState, restricted: Boolean = Config.suRestrict) { // Toggle the current state rather than the one the UI captured: two quick taps can // deliver the same item before it recomposes val uid = app.info.uid @@ -160,7 +165,7 @@ class SuperuserGrantViewModel( if (willGrant) { val existing = policyDB.fetch(uid) val suPolicy = existing ?: SuPolicy(uid) - suPolicy.policy = if (Config.suRestrict) SuPolicy.RESTRICT else SuPolicy.ALLOW + suPolicy.policy = if (restricted) SuPolicy.RESTRICT else SuPolicy.ALLOW policyDB.update(suPolicy) } else { policyDB.delete(uid) diff --git a/app/wear/src/main/java/com/topjohnwu/magisk/wear/WearUi.kt b/app/wear/src/main/java/com/topjohnwu/magisk/wear/WearUi.kt index 27bfd74517bac..146094677c65a 100644 --- a/app/wear/src/main/java/com/topjohnwu/magisk/wear/WearUi.kt +++ b/app/wear/src/main/java/com/topjohnwu/magisk/wear/WearUi.kt @@ -48,6 +48,7 @@ import com.topjohnwu.magisk.ui.flash.FlashUtils import com.topjohnwu.magisk.ui.flash.queryDisplayName import com.topjohnwu.magisk.ui.flash.sanitizeDisplayName import com.topjohnwu.magisk.ui.navigation.Route +import com.topjohnwu.magisk.ui.superuser.SuperuserGrantViewModel import com.topjohnwu.magisk.ui.superuser.SuperuserViewModel import com.topjohnwu.magisk.ui.unsupportedMessages import com.topjohnwu.magisk.wear.files.PickScreen @@ -56,6 +57,7 @@ import com.topjohnwu.magisk.wear.nav.LocalWearNavigator import com.topjohnwu.magisk.wear.nav.WearNavigator import com.topjohnwu.magisk.wear.nav.WearRoute import com.topjohnwu.magisk.wear.nav.rememberWearNavigator +import com.topjohnwu.magisk.wear.superuser.GrantScreen import com.topjohnwu.magisk.wear.superuser.SuperuserDetailScreen import com.topjohnwu.magisk.wear.superuser.SuperuserScreen import com.topjohnwu.magisk.wear.theme.WearTheme @@ -129,7 +131,11 @@ class WearUi( SuperuserDetailScreen(key.uid, vm, navigator) } entry { - Placeholder(stringResource(CoreR.string.superuser_grant)) + val vm: SuperuserGrantViewModel = viewModel(factory = VMFactory) + LaunchedEffect(Unit) { + vm.startLoading() + } + GrantScreen(vm) } entry { key -> Placeholder(key.name) } entry { diff --git a/app/wear/src/main/java/com/topjohnwu/magisk/wear/superuser/GrantScreen.kt b/app/wear/src/main/java/com/topjohnwu/magisk/wear/superuser/GrantScreen.kt new file mode 100644 index 0000000000000..c10a8361fa320 --- /dev/null +++ b/app/wear/src/main/java/com/topjohnwu/magisk/wear/superuser/GrantScreen.kt @@ -0,0 +1,188 @@ +package com.topjohnwu.magisk.wear.superuser + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Add +import androidx.compose.material.icons.filled.Check +import androidx.compose.material.icons.filled.Shield +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.semantics.toggleableState +import androidx.compose.ui.state.ToggleableState +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.wear.compose.foundation.lazy.TransformingLazyColumn +import androidx.wear.compose.foundation.lazy.items +import androidx.wear.compose.foundation.lazy.rememberTransformingLazyColumnState +import androidx.wear.compose.material3.ButtonDefaults +import androidx.wear.compose.material3.CompactButton +import androidx.wear.compose.material3.FilledTonalButton +import androidx.wear.compose.material3.Icon +import androidx.wear.compose.material3.ListHeader +import androidx.wear.compose.material3.MaterialTheme +import androidx.wear.compose.material3.ScreenScaffold +import androidx.wear.compose.material3.SwitchButton +import androidx.wear.compose.material3.Text +import com.topjohnwu.magisk.core.Config +import com.topjohnwu.magisk.ui.component.rememberBiometricAuth +import com.topjohnwu.magisk.ui.superuser.SuGrantAppState +import com.topjohnwu.magisk.ui.superuser.SuperuserGrantViewModel +import com.topjohnwu.magisk.wear.component.AppIcon +import com.topjohnwu.magisk.wear.component.LoadingScreen +import com.topjohnwu.magisk.core.R as CoreR + +/** + * Grants root to apps that have no policy yet. New entries reach the Superuser list through + * the policy change event the view model sends, like on the phone. + */ +@Composable +fun GrantScreen(viewModel: SuperuserGrantViewModel) { + val loading by viewModel.loading.collectAsStateWithLifecycle() + val apps by viewModel.filteredApps.collectAsStateWithLifecycle() + val showSystem by viewModel.showSystem.collectAsStateWithLifecycle() + + // The kind of root the next grant gives, switched with the mode chip. It starts at the + // "restrict root capabilities" setting, which stays unchanged. + var restrict by rememberSaveable { mutableStateOf(Config.suRestrict) } + val requireAuth = rememberBiometricAuth() + + // The mode each app was granted with here, by uid, to show it in its row + var grantedModes by rememberSaveable { mutableStateOf(HashMap()) } + + // Kept across the loading screen, so the list doesn't scroll back when it ends + val state = rememberTransformingLazyColumnState() + + if (loading) { + LoadingScreen() + return + } + + // Apps granted before this screen opened are already in the Superuser list. Apps granted + // here stay, so a mistaken grant can be undone right away. + val candidates = apps.filter { !it.initiallyGranted } + + ScreenScaffold(state) { contentPadding -> + TransformingLazyColumn(state = state, contentPadding = contentPadding) { + item { + ListHeader { + Text(stringResource(CoreR.string.superuser_grant)) + } + } + item { + CompactButton( + onClick = { restrict = !restrict }, + icon = { Icon(Icons.Filled.Shield, contentDescription = null) }, + label = { Text(stringResource(modeLabel(restrict))) }, + colors = ButtonDefaults.filledTonalButtonColors(), + ) + } + items( + items = candidates, + key = { it.info.packageName }, + ) { app -> + GrantRow( + app = app, + grantedRestricted = grantedModes[app.info.uid], + onToggle = { + // The mode of this tap, whatever the chip shows once authenticated + val restricted = restrict + requireAuth { + if (!app.isGranted) { + grantedModes = HashMap(grantedModes).apply { + put(app.info.uid, restricted) + } + } + // The view model flips the latest state, so quick repeated taps + // never get lost + viewModel.toggleGrant(app, restricted) + } + }, + ) + } + item { + SwitchButton( + checked = showSystem, + onCheckedChange = { viewModel.setShowSystem(it) }, + label = { Text(stringResource(CoreR.string.show_system_app)) }, + modifier = Modifier.fillMaxWidth(), + ) + } + } + } +} + +private fun modeLabel(restricted: Boolean) = + if (restricted) CoreR.string.wear_root_restricted else CoreR.string.wear_root_full + +@Composable +private fun GrantRow( + app: SuGrantAppState, + // The mode it was granted with on this screen, if known + grantedRestricted: Boolean?, + onToggle: () -> Unit, +) { + val colors = MaterialTheme.colorScheme + FilledTonalButton( + onClick = onToggle, + modifier = Modifier + .fillMaxWidth() + .semantics { toggleableState = ToggleableState(app.isGranted) }, + content = { + AppIcon(packageName = app.info.packageName, size = 28.dp) + Column( + modifier = Modifier.weight(1f).padding(horizontal = 8.dp), + verticalArrangement = Arrangement.Center, + ) { + Text( + text = app.info.label, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + Text( + text = if (app.isGranted && grantedRestricted != null) { + stringResource( + CoreR.string.wear_grant_granted, + stringResource(modeLabel(grantedRestricted)), + ) + } else { + app.info.packageName + }, + style = MaterialTheme.typography.labelSmall, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + Box( + modifier = Modifier + .size(32.dp) + .background( + color = if (app.isGranted) colors.primary else colors.primary.copy(alpha = 0.2f), + shape = CircleShape, + ), + contentAlignment = Alignment.Center, + ) { + Icon( + imageVector = if (app.isGranted) Icons.Filled.Check else Icons.Filled.Add, + contentDescription = null, + tint = if (app.isGranted) colors.onPrimary else colors.primary, + modifier = Modifier.size(20.dp), + ) + } + }, + ) +} From 8658718513984f3434441f750b8269fb70fb1e64 Mon Sep 17 00:00:00 2001 From: Jakub Mendyka Date: Mon, 23 Nov 2026 16:44:18 +0100 Subject: [PATCH 08/12] Add Wear log screen Show the Superuser log grouped by day, with a dot telling granted from denied requests, and the Magisk log as one monospace item per parsed entry, so long logs stay cheap to scroll. A switch at the top picks the log; without root only the Magisk log exists, like on the phone. Both logs list the newest entries first and can be cleared after a confirmation. Define the error colour in the Wear theme, so denied requests and destructive actions share one red. Assisted-by: Claude Opus 5.5 --- app/core/src/main/res/values-pl/strings.xml | 3 + app/core/src/main/res/values/resources.xml | 2 + app/core/src/main/res/values/strings.xml | 3 + .../java/com/topjohnwu/magisk/wear/WearUi.kt | 5 +- .../topjohnwu/magisk/wear/log/LogScreen.kt | 332 ++++++++++++++++++ .../topjohnwu/magisk/wear/theme/WearTheme.kt | 2 + 6 files changed, 346 insertions(+), 1 deletion(-) create mode 100644 app/wear/src/main/java/com/topjohnwu/magisk/wear/log/LogScreen.kt diff --git a/app/core/src/main/res/values-pl/strings.xml b/app/core/src/main/res/values-pl/strings.xml index 353833b9d2d30..e228ffd35bca9 100644 --- a/app/core/src/main/res/values-pl/strings.xml +++ b/app/core/src/main/res/values-pl/strings.xml @@ -221,4 +221,7 @@ Bez roota Logi su Przyznano · %1$s + Dziś + Wczoraj + Usunąć wszystkie wpisy z logu %1$s? diff --git a/app/core/src/main/res/values/resources.xml b/app/core/src/main/res/values/resources.xml index d32d3c8c61d9a..28417c1a6e96e 100644 --- a/app/core/src/main/res/values/resources.xml +++ b/app/core/src/main/res/values/resources.xml @@ -10,6 +10,8 @@ %1$s: %2$s + su + %1$s · %2$s PayPal Patreon diff --git a/app/core/src/main/res/values/strings.xml b/app/core/src/main/res/values/strings.xml index 8a0b0fc658842..a52905a711085 100644 --- a/app/core/src/main/res/values/strings.xml +++ b/app/core/src/main/res/values/strings.xml @@ -251,4 +251,7 @@ No root Superuser logs Granted · %1$s + Today + Yesterday + Delete all entries of the %1$s log? diff --git a/app/wear/src/main/java/com/topjohnwu/magisk/wear/WearUi.kt b/app/wear/src/main/java/com/topjohnwu/magisk/wear/WearUi.kt index 146094677c65a..f6508ba81ca48 100644 --- a/app/wear/src/main/java/com/topjohnwu/magisk/wear/WearUi.kt +++ b/app/wear/src/main/java/com/topjohnwu/magisk/wear/WearUi.kt @@ -47,12 +47,14 @@ import com.topjohnwu.magisk.core.base.ActivityExtension import com.topjohnwu.magisk.ui.flash.FlashUtils import com.topjohnwu.magisk.ui.flash.queryDisplayName import com.topjohnwu.magisk.ui.flash.sanitizeDisplayName +import com.topjohnwu.magisk.ui.log.LogViewModel import com.topjohnwu.magisk.ui.navigation.Route import com.topjohnwu.magisk.ui.superuser.SuperuserGrantViewModel import com.topjohnwu.magisk.ui.superuser.SuperuserViewModel import com.topjohnwu.magisk.ui.unsupportedMessages import com.topjohnwu.magisk.wear.files.PickScreen import com.topjohnwu.magisk.wear.home.HomeScreen +import com.topjohnwu.magisk.wear.log.LogScreen import com.topjohnwu.magisk.wear.nav.LocalWearNavigator import com.topjohnwu.magisk.wear.nav.WearNavigator import com.topjohnwu.magisk.wear.nav.WearRoute @@ -145,7 +147,8 @@ class WearUi( SuperuserScreen(vm, navigator) } entry { - Placeholder(stringResource(CoreR.string.logs)) + val vm: LogViewModel = viewModel(factory = VMFactory) + LogScreen(vm) } entry { Placeholder(stringResource(CoreR.string.modules)) diff --git a/app/wear/src/main/java/com/topjohnwu/magisk/wear/log/LogScreen.kt b/app/wear/src/main/java/com/topjohnwu/magisk/wear/log/LogScreen.kt new file mode 100644 index 0000000000000..0c7b5b8fc5d0c --- /dev/null +++ b/app/wear/src/main/java/com/topjohnwu/magisk/wear/log/LogScreen.kt @@ -0,0 +1,332 @@ +package com.topjohnwu.magisk.wear.log + +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Delete +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.selected +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.wear.compose.foundation.lazy.TransformingLazyColumn +import androidx.wear.compose.foundation.lazy.TransformingLazyColumnScope +import androidx.wear.compose.foundation.lazy.TransformingLazyColumnState +import androidx.wear.compose.foundation.lazy.items +import androidx.wear.compose.foundation.lazy.rememberTransformingLazyColumnState +import androidx.wear.compose.material3.AlertDialog +import androidx.wear.compose.material3.AlertDialogDefaults +import androidx.wear.compose.material3.ButtonDefaults +import androidx.wear.compose.material3.Card +import androidx.wear.compose.material3.CompactButton +import androidx.wear.compose.material3.FilledTonalButton +import androidx.wear.compose.material3.Icon +import androidx.wear.compose.material3.ListHeader +import androidx.wear.compose.material3.MaterialTheme +import androidx.wear.compose.material3.ScreenScaffold +import androidx.wear.compose.material3.Text +import com.topjohnwu.magisk.core.Info +import com.topjohnwu.magisk.core.ktx.dateFormat +import com.topjohnwu.magisk.core.ktx.toTime +import com.topjohnwu.magisk.core.model.su.SuLog +import com.topjohnwu.magisk.core.model.su.SuPolicy +import com.topjohnwu.magisk.ui.log.LogViewModel +import com.topjohnwu.magisk.ui.log.MagiskLogEntry +import com.topjohnwu.magisk.wear.component.LoadingScreen +import java.time.Instant +import java.time.LocalDate +import java.time.ZoneId +import java.time.format.DateTimeFormatter +import java.time.format.FormatStyle +import com.topjohnwu.magisk.core.R as CoreR + +private val shortTimeFormat: DateTimeFormatter by lazy { + DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT).withZone(ZoneId.systemDefault()) +} + +/** A row of the Superuser log: a day header, or one request. */ +private sealed interface SuLogRow { + data class Day(val date: LocalDate) : SuLogRow + data class Entry(val log: SuLog) : SuLogRow +} + +/** Puts a header before the first request of each day. [logs] are newest first. */ +private fun withDayHeaders(logs: List): List { + val zone = ZoneId.systemDefault() + val rows = ArrayList(logs.size + 8) + var lastDate: LocalDate? = null + for (log in logs) { + val date = Instant.ofEpochMilli(log.time).atZone(zone).toLocalDate() + if (date != lastDate) { + rows.add(SuLogRow.Day(date)) + lastDate = date + } + rows.add(SuLogRow.Entry(log)) + } + return rows +} + +/** + * The Superuser and Magisk logs. Without root there is no Superuser log, so only the Magisk + * log is shown, like the phone app does. + */ +@Composable +fun LogScreen(viewModel: LogViewModel) { + val uiState by viewModel.uiState.collectAsStateWithLifecycle() + val hasRoot = Info.env.isActive + var magiskTab by rememberSaveable { mutableStateOf(false) } + val showMagisk = !hasRoot || magiskTab + var showClear by rememberSaveable { mutableStateOf(false) } + + LaunchedEffect(viewModel) { + viewModel.startLoading() + } + + // One state per log, so switching between them keeps each one's position. Kept across the + // loading screen, so the list doesn't scroll back when it ends. + val suState = rememberTransformingLazyColumnState() + val magiskState = rememberTransformingLazyColumnState() + + if (uiState.loading) { + LoadingScreen() + return + } + + val suRows = remember(uiState.suLogs) { withDayHeaders(uiState.suLogs) } + // Newest first, like the Superuser log, so the latest lines are right below the switch + val magiskEntries = remember(uiState.magiskLogEntries) { uiState.magiskLogEntries.asReversed() } + val isEmpty = if (showMagisk) magiskEntries.isEmpty() else suRows.isEmpty() + val state: TransformingLazyColumnState = if (showMagisk) magiskState else suState + + ScreenScaffold(state) { contentPadding -> + TransformingLazyColumn(state = state, contentPadding = contentPadding) { + item { + if (hasRoot) { + LogSwitch(magiskTab = magiskTab, onSelect = { magiskTab = it }) + } else { + ListHeader { Text(stringResource(CoreR.string.logs)) } + } + } + if (isEmpty) { + item { + Text( + text = stringResource( + if (showMagisk) CoreR.string.log_data_magisk_none + else CoreR.string.log_data_none + ), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + textAlign = TextAlign.Center, + modifier = Modifier.fillMaxWidth().padding(8.dp), + ) + } + } else { + if (showMagisk) { + magiskLogItems(magiskEntries) + } else { + suLogItems(suRows) + } + item { + FilledTonalButton( + onClick = { showClear = true }, + icon = { Icon(Icons.Filled.Delete, contentDescription = null) }, + label = { Text(stringResource(CoreR.string.menuClearLog)) }, + modifier = Modifier.fillMaxWidth(), + ) + } + } + } + } + + AlertDialog( + visible = showClear, + onDismissRequest = { showClear = false }, + title = { Text(stringResource(CoreR.string.menuClearLog)) }, + text = { + Text( + stringResource( + CoreR.string.wear_log_clear_msg, + stringResource(if (showMagisk) CoreR.string.magisk else CoreR.string.superuser), + ) + ) + }, + confirmButton = { + AlertDialogDefaults.ConfirmButton(onClick = { + showClear = false + if (showMagisk) viewModel.clearMagiskLog() else viewModel.clearLog() + }) + }, + dismissButton = { + AlertDialogDefaults.DismissButton(onClick = { showClear = false }) + }, + ) +} + +/** Switches between the Superuser log and the Magisk log. */ +@Composable +private fun LogSwitch(magiskTab: Boolean, onSelect: (Boolean) -> Unit) { + Row( + modifier = Modifier + .background(MaterialTheme.colorScheme.surfaceContainer, CircleShape) + .padding(4.dp), + horizontalArrangement = Arrangement.spacedBy(4.dp), + ) { + SwitchSegment( + label = stringResource(CoreR.string.wear_log_su), + selected = !magiskTab, + onClick = { onSelect(false) }, + ) + SwitchSegment( + label = stringResource(CoreR.string.magisk), + selected = magiskTab, + onClick = { onSelect(true) }, + ) + } +} + +@Composable +private fun SwitchSegment(label: String, selected: Boolean, onClick: () -> Unit) { + CompactButton( + onClick = onClick, + label = { Text(label) }, + colors = if (selected) ButtonDefaults.buttonColors() else ButtonDefaults.childButtonColors(), + modifier = Modifier.semantics { this.selected = selected }, + ) +} + +private fun TransformingLazyColumnScope.suLogItems(rows: List) { + items( + items = rows, + key = { + when (it) { + is SuLogRow.Day -> "day_${it.date}" + is SuLogRow.Entry -> "log_${it.log.id}" + } + }, + ) { row -> + when (row) { + is SuLogRow.Day -> ListHeader { Text(dayLabel(row.date)) } + is SuLogRow.Entry -> SuLogCard(row.log) + } + } +} + +@Composable +private fun dayLabel(date: LocalDate): String { + val today = LocalDate.now(ZoneId.systemDefault()) + return when (date) { + today -> stringResource(CoreR.string.wear_log_today) + today.minusDays(1) -> stringResource(CoreR.string.wear_log_yesterday) + else -> dateFormat.format(date) + } +} + +@Composable +private fun SuLogCard(log: SuLog) { + val colors = MaterialTheme.colorScheme + val allowed = log.action >= SuPolicy.ALLOW + // The command can be long, so show all of it only when asked + var expanded by rememberSaveable(log.id) { mutableStateOf(false) } + val result = stringResource(if (allowed) CoreR.string.granted else CoreR.string.denied) + + Card( + onClick = { expanded = !expanded }, + modifier = Modifier.fillMaxWidth(), + ) { + Row(verticalAlignment = Alignment.CenterVertically) { + Box( + modifier = Modifier + .size(10.dp) + .background(if (allowed) colors.primary else colors.error, CircleShape), + ) + Spacer(Modifier.width(10.dp)) + Column(modifier = Modifier.weight(1f)) { + Text( + text = log.appName, + style = MaterialTheme.typography.titleSmall, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + Text( + text = if (log.command.isEmpty()) result + else stringResource(CoreR.string.wear_log_su_result, result, log.command), + style = MaterialTheme.typography.labelSmall, + color = colors.onSurfaceVariant, + maxLines = if (expanded) Int.MAX_VALUE else 1, + overflow = TextOverflow.Ellipsis, + ) + } + Spacer(Modifier.width(8.dp)) + Text( + text = log.time.toTime(shortTimeFormat), + style = MaterialTheme.typography.labelSmall, + color = colors.onSurfaceVariant, + ) + } + } +} + +private fun TransformingLazyColumnScope.magiskLogItems(entries: List) { + // One item per entry, so a long log is only laid out as far as it is scrolled. The entries + // are newest first, so key them by their position in the log, which a reload keeps. + items(count = entries.size, key = { entries.size - 1 - it }) { index -> + MagiskLogLine(entries[index]) + } +} + +@Composable +private fun MagiskLogLine(entry: MagiskLogEntry) { + val colors = MaterialTheme.colorScheme + val mono = MaterialTheme.typography.bodySmall.copy(fontFamily = FontFamily.Monospace) + // Long messages are cut to a few lines, like on the phone; a tap shows all of it + var expanded by remember { mutableStateOf(false) } + + Column( + modifier = Modifier + .fillMaxWidth() + .clickable { expanded = !expanded } + .padding(horizontal = 8.dp, vertical = 4.dp), + ) { + if (entry.isParsed) { + Text( + text = "${entry.level} ${entry.timestamp}", + style = MaterialTheme.typography.labelSmall.copy(fontFamily = FontFamily.Monospace), + color = when (entry.level) { + 'E', 'F' -> colors.error + 'W' -> colors.tertiary + else -> colors.onSurfaceVariant + }, + maxLines = 1, + ) + } + Text( + text = entry.message, + style = mono, + color = colors.onSurface, + maxLines = if (expanded) Int.MAX_VALUE else 3, + overflow = TextOverflow.Ellipsis, + ) + } +} diff --git a/app/wear/src/main/java/com/topjohnwu/magisk/wear/theme/WearTheme.kt b/app/wear/src/main/java/com/topjohnwu/magisk/wear/theme/WearTheme.kt index 105fbaee5cd57..12fc4c257947b 100644 --- a/app/wear/src/main/java/com/topjohnwu/magisk/wear/theme/WearTheme.kt +++ b/app/wear/src/main/java/com/topjohnwu/magisk/wear/theme/WearTheme.kt @@ -14,6 +14,8 @@ private val WearColorScheme = ColorScheme( primaryContainer = Color(0xFF00504A), onPrimary = Color(0xFF00382F), onPrimaryContainer = Color(0xFF9FF2E3), + // Denied requests and destructive actions + error = Color(0xFFFFB4AB), // A black background keeps OLED pixels off and blends with the bezel background = Color.Black, ) From 84a41791c76a6b7bfe3fdc014db5cafd55fed769 Mon Sep 17 00:00:00 2001 From: Jakub Mendyka Date: Mon, 23 Nov 2026 16:56:22 +0100 Subject: [PATCH 09/12] Add Wear module screens List the installed modules with a switch each, open their details to remove or restore them and run their action, and install a module zip picked from storage after a confirmation, like the phone UI. The confirmation shows the provider of a picked file next to its name, as for a request from another app. A reboot button shows up once a module differs from its state when first loaded, since changes only apply after a reboot. The action output is shown as plain monospace text read from the terminal emulator. A horizontal swipe dismisses the screen on Wear, so there is no horizontal scrolling: the emulator is sized to the width that fits and wraps long lines itself. TerminalText is reused by the flash screen. While the action runs, BlockDismiss turns swipe-to-dismiss off and registers the screen's back callback with the navigator. NavDisplay's onBack hands back to the latest blocker instead of popping, so the exit confirmation does not depend on the order of back handlers and a hung script can always be left. From API 36 the swipe is predictive back, and turning it off in the scene strategy would swallow back entirely, so it stays on there and reaches the same callback. Assisted-by: Claude Opus 5.5 --- app/core/src/main/res/values-pl/strings.xml | 8 + app/core/src/main/res/values/resources.xml | 1 + app/core/src/main/res/values/strings.xml | 8 + .../java/com/topjohnwu/magisk/wear/WearUi.kt | 62 ++++- .../magisk/wear/component/ScreenTitle.kt | 36 +++ .../magisk/wear/module/ActionScreen.kt | 102 +++++++ .../magisk/wear/module/ModuleDetailScreen.kt | 178 ++++++++++++ .../magisk/wear/module/ModulesScreen.kt | 260 ++++++++++++++++++ .../magisk/wear/module/TerminalText.kt | 127 +++++++++ .../com/topjohnwu/magisk/wear/nav/WearNav.kt | 53 ++++ 10 files changed, 830 insertions(+), 5 deletions(-) create mode 100644 app/wear/src/main/java/com/topjohnwu/magisk/wear/component/ScreenTitle.kt create mode 100644 app/wear/src/main/java/com/topjohnwu/magisk/wear/module/ActionScreen.kt create mode 100644 app/wear/src/main/java/com/topjohnwu/magisk/wear/module/ModuleDetailScreen.kt create mode 100644 app/wear/src/main/java/com/topjohnwu/magisk/wear/module/ModulesScreen.kt create mode 100644 app/wear/src/main/java/com/topjohnwu/magisk/wear/module/TerminalText.kt diff --git a/app/core/src/main/res/values-pl/strings.xml b/app/core/src/main/res/values-pl/strings.xml index e228ffd35bca9..864f54a218800 100644 --- a/app/core/src/main/res/values-pl/strings.xml +++ b/app/core/src/main/res/values-pl/strings.xml @@ -224,4 +224,12 @@ Dziś Wczoraj Usunąć wszystkie wpisy z logu %1$s? + Aktywny + Wyłączony + Usunięty po restarcie + Włączony + Uruchom ponownie + Uruchom akcję + Usuń moduł + Trwa… diff --git a/app/core/src/main/res/values/resources.xml b/app/core/src/main/res/values/resources.xml index 28417c1a6e96e..af40c3fbb4cb7 100644 --- a/app/core/src/main/res/values/resources.xml +++ b/app/core/src/main/res/values/resources.xml @@ -12,6 +12,7 @@ %1$s: %2$s su %1$s · %2$s + %1$s · %2$s PayPal Patreon diff --git a/app/core/src/main/res/values/strings.xml b/app/core/src/main/res/values/strings.xml index a52905a711085..9aaeba4c9ad8c 100644 --- a/app/core/src/main/res/values/strings.xml +++ b/app/core/src/main/res/values/strings.xml @@ -254,4 +254,12 @@ Today Yesterday Delete all entries of the %1$s log? + Active + Disabled + Removed after reboot + Enabled + Reboot + Run action + Remove module + Running… diff --git a/app/wear/src/main/java/com/topjohnwu/magisk/wear/WearUi.kt b/app/wear/src/main/java/com/topjohnwu/magisk/wear/WearUi.kt index f6508ba81ca48..1ea13d4c1fc38 100644 --- a/app/wear/src/main/java/com/topjohnwu/magisk/wear/WearUi.kt +++ b/app/wear/src/main/java/com/topjohnwu/magisk/wear/WearUi.kt @@ -30,6 +30,7 @@ import androidx.core.net.toUri import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.viewmodel.compose.viewModel import androidx.lifecycle.viewmodel.navigation3.rememberViewModelStoreNavEntryDecorator +import androidx.navigation3.runtime.NavKey import androidx.navigation3.runtime.entryProvider import androidx.navigation3.runtime.rememberSaveableStateHolderNavEntryDecorator import androidx.navigation3.ui.NavDisplay @@ -48,6 +49,8 @@ import com.topjohnwu.magisk.ui.flash.FlashUtils import com.topjohnwu.magisk.ui.flash.queryDisplayName import com.topjohnwu.magisk.ui.flash.sanitizeDisplayName import com.topjohnwu.magisk.ui.log.LogViewModel +import com.topjohnwu.magisk.ui.module.ActionViewModel +import com.topjohnwu.magisk.ui.module.ModuleViewModel import com.topjohnwu.magisk.ui.navigation.Route import com.topjohnwu.magisk.ui.superuser.SuperuserGrantViewModel import com.topjohnwu.magisk.ui.superuser.SuperuserViewModel @@ -55,6 +58,9 @@ import com.topjohnwu.magisk.ui.unsupportedMessages import com.topjohnwu.magisk.wear.files.PickScreen import com.topjohnwu.magisk.wear.home.HomeScreen import com.topjohnwu.magisk.wear.log.LogScreen +import com.topjohnwu.magisk.wear.module.ActionScreen +import com.topjohnwu.magisk.wear.module.ModuleDetailScreen +import com.topjohnwu.magisk.wear.module.ModulesScreen import com.topjohnwu.magisk.wear.nav.LocalWearNavigator import com.topjohnwu.magisk.wear.nav.WearNavigator import com.topjohnwu.magisk.wear.nav.WearRoute @@ -104,18 +110,29 @@ class WearUi( WearTheme { AppScaffold(timeText = { TimeText() }) { val navigator = rememberWearNavigator(Route.Main) + // See ModulesScreen; kept with the activity-scoped ModuleViewModel + val moduleLoadedStates = rememberSaveable { HashMap() } CompositionLocalProvider(LocalWearNavigator provides navigator) { HandleFlashIntent(navigator) NavDisplay( backStack = navigator.backStack, - onBack = { navigator.pop() }, + // A screen that blocks dismissal gets back instead, see BlockDismiss + onBack = { navigator.back() }, entryDecorators = listOf( rememberSaveableStateHolderNavEntryDecorator(), rememberViewModelStoreNavEntryDecorator() ), // Swipe-to-dismiss, and predictive back from API 36 - sceneStrategies = listOf(rememberSwipeDismissableSceneStrategy()), + sceneStrategies = listOf( + rememberSwipeDismissableSceneStrategy( + // From API 36 the swipe is predictive back, and turning it off + // swallows back entirely; leave it on there, so a blocked + // swipe reaches onBack, which hands it to the blocking screen + isUserSwipeEnabled = navigator.isDismissEnabled || + Build.VERSION.SDK_INT > Build.VERSION_CODES.VANILLA_ICE_CREAM + ) + ), entryProvider = entryProvider { entry { HomeScreen(navigator) } entry { @@ -139,7 +156,24 @@ class WearUi( } GrantScreen(vm) } - entry { key -> Placeholder(key.name) } + entry { key -> + val vm: ActionViewModel = viewModel(factory = VMFactory) + if (vm.isInterrupted) { + // Restored after process death: nothing is left to show + LeaveInterruptedScreen(navigator, key) + return@entry + } + LaunchedEffect(key) { + if (vm.actionDir.isEmpty()) { + vm.actionDir = key.dir + vm.actionName = key.name + vm.startRunAction() + } + } + ActionScreen(vm, actionName = key.name, onLeave = { + if (navigator.current() == key) navigator.pop() + }) + } entry { val vm: SuperuserViewModel = viewModel( viewModelStoreOwner = activity, factory = VMFactory @@ -151,9 +185,19 @@ class WearUi( LogScreen(vm) } entry { - Placeholder(stringResource(CoreR.string.modules)) + // Owned by the activity, so the list and its details share one + // copy of the modules, like the phone app + val vm: ModuleViewModel = viewModel( + viewModelStoreOwner = activity, factory = VMFactory + ) + ModulesScreen(vm, navigator, moduleLoadedStates) + } + entry { key -> + val vm: ModuleViewModel = viewModel( + viewModelStoreOwner = activity, factory = VMFactory + ) + ModuleDetailScreen(key.dir, vm, navigator) } - entry { key -> Placeholder(key.dir) } entry { Placeholder(stringResource(CoreR.string.install)) } @@ -263,6 +307,14 @@ class WearUi( } } +/** Leaves the screen of [key], if it is still on top. */ +@Composable +private fun LeaveInterruptedScreen(navigator: WearNavigator, key: NavKey) { + LaunchedEffect(key) { + if (navigator.current() == key) navigator.pop() + } +} + /** Stands in for a screen that is not implemented yet. */ @Composable private fun Placeholder(title: String) { diff --git a/app/wear/src/main/java/com/topjohnwu/magisk/wear/component/ScreenTitle.kt b/app/wear/src/main/java/com/topjohnwu/magisk/wear/component/ScreenTitle.kt new file mode 100644 index 0000000000000..edd1398ac3cb3 --- /dev/null +++ b/app/wear/src/main/java/com/topjohnwu/magisk/wear/component/ScreenTitle.kt @@ -0,0 +1,36 @@ +package com.topjohnwu.magisk.wear.component + +import androidx.compose.foundation.layout.padding +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalConfiguration +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextDecoration +import androidx.compose.ui.unit.dp +import androidx.wear.compose.material3.MaterialTheme +import androidx.wear.compose.material3.Text + +// Extra inset, as a fraction of the screen width, on top of the column's own horizontal padding. +// A round screen is narrowest at the top of a list, where this title sits. +private const val TopItemPaddingFraction = 0.14f + +/** + * The title of a detail screen, shown as the first item of its list. It wraps to more lines + * instead of running into the edges of a round screen. + */ +@Composable +fun ScreenTitle( + text: String, + modifier: Modifier = Modifier, + textDecoration: TextDecoration? = null, +) { + Text( + text = text, + style = MaterialTheme.typography.titleMedium, + textAlign = TextAlign.Center, + textDecoration = textDecoration, + modifier = modifier.padding( + horizontal = (LocalConfiguration.current.screenWidthDp * TopItemPaddingFraction).dp + ), + ) +} diff --git a/app/wear/src/main/java/com/topjohnwu/magisk/wear/module/ActionScreen.kt b/app/wear/src/main/java/com/topjohnwu/magisk/wear/module/ActionScreen.kt new file mode 100644 index 0000000000000..ce405cdb68ebe --- /dev/null +++ b/app/wear/src/main/java/com/topjohnwu/magisk/wear/module/ActionScreen.kt @@ -0,0 +1,102 @@ +package com.topjohnwu.magisk.wear.module + +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.wear.compose.material3.AlertDialog +import androidx.wear.compose.material3.AlertDialogDefaults +import androidx.wear.compose.material3.MaterialTheme +import androidx.wear.compose.material3.ScreenScaffold +import androidx.wear.compose.material3.Text +import com.topjohnwu.magisk.ui.module.ActionViewModel +import com.topjohnwu.magisk.wear.nav.BlockDismiss +import com.topjohnwu.magisk.core.R as CoreR + +/** + * The output of a module's action.sh. While it runs, the screen can't be swiped away; back + * (and from API 36 the swipe, which is predictive back) asks before leaving, like the phone + * app, so a script that hangs can still be left. + */ +@Composable +fun ActionScreen( + viewModel: ActionViewModel, + actionName: String, + onLeave: () -> Unit, +) { + val actionState by viewModel.actionState.collectAsStateWithLifecycle() + val running = actionState == ActionViewModel.State.RUNNING + var showExit by rememberSaveable { mutableStateOf(false) } + + BlockDismiss(blocked = running, onBlockedBack = { showExit = true }) + + ScreenScaffold { contentPadding -> + Column( + modifier = Modifier + .fillMaxSize() + .padding(contentPadding), + horizontalAlignment = Alignment.CenterHorizontally, + ) { + Text( + text = actionName, + style = MaterialTheme.typography.titleSmall, + textAlign = TextAlign.Center, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + val colors = MaterialTheme.colorScheme + Text( + text = stringResource( + when (actionState) { + ActionViewModel.State.RUNNING -> CoreR.string.wear_action_running + ActionViewModel.State.SUCCESS -> CoreR.string.done + ActionViewModel.State.FAILED -> CoreR.string.failure + } + ), + style = MaterialTheme.typography.labelSmall, + color = when (actionState) { + ActionViewModel.State.RUNNING -> colors.onSurfaceVariant + ActionViewModel.State.SUCCESS -> colors.primary + ActionViewModel.State.FAILED -> colors.error + }, + ) + TerminalText( + emu = viewModel.emulator, + modifier = Modifier + .weight(1f) + .fillMaxWidth() + .padding(horizontal = 8.dp, vertical = 4.dp), + onResized = viewModel::onTerminalResized, + ) + } + } + + AlertDialog( + // Not shown any more once the action has finished meanwhile: back just leaves then + visible = showExit && running, + onDismissRequest = { showExit = false }, + title = { Text(stringResource(CoreR.string.running_exit_title)) }, + text = { Text(stringResource(CoreR.string.running_exit_msg)) }, + confirmButton = { + AlertDialogDefaults.ConfirmButton(onClick = { + showExit = false + onLeave() + }) + }, + dismissButton = { + AlertDialogDefaults.DismissButton(onClick = { showExit = false }) + }, + ) +} diff --git a/app/wear/src/main/java/com/topjohnwu/magisk/wear/module/ModuleDetailScreen.kt b/app/wear/src/main/java/com/topjohnwu/magisk/wear/module/ModuleDetailScreen.kt new file mode 100644 index 0000000000000..a85556ce63437 --- /dev/null +++ b/app/wear/src/main/java/com/topjohnwu/magisk/wear/module/ModuleDetailScreen.kt @@ -0,0 +1,178 @@ +package com.topjohnwu.magisk.wear.module + +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.Undo +import androidx.compose.material.icons.filled.Delete +import androidx.compose.material.icons.filled.PlayArrow +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalResources +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextDecoration +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.wear.compose.foundation.lazy.TransformingLazyColumn +import androidx.wear.compose.foundation.lazy.rememberTransformingLazyColumnState +import androidx.wear.compose.material3.Button +import androidx.wear.compose.material3.ButtonDefaults +import androidx.wear.compose.material3.FilledTonalButton +import androidx.wear.compose.material3.Icon +import androidx.wear.compose.material3.MaterialTheme +import androidx.wear.compose.material3.ScreenScaffold +import androidx.wear.compose.material3.SwitchButton +import androidx.wear.compose.material3.Text +import com.topjohnwu.magisk.ui.module.ModuleItem +import com.topjohnwu.magisk.ui.module.ModuleViewModel +import com.topjohnwu.magisk.wear.component.LoadingScreen +import com.topjohnwu.magisk.wear.component.ScreenTitle +import com.topjohnwu.magisk.wear.nav.CollectNavEvents +import com.topjohnwu.magisk.wear.nav.WearNavigator +import com.topjohnwu.magisk.wear.nav.WearRoute +import com.topjohnwu.magisk.wear.theme.destructiveButtonColors +import com.topjohnwu.magisk.core.R as CoreR + +/** The module in directory [dir]. [viewModel] is the one [ModulesScreen] uses. */ +@Composable +fun ModuleDetailScreen( + dir: String, + viewModel: ModuleViewModel, + navigator: WearNavigator, +) { + val uiState by viewModel.uiState.collectAsStateWithLifecycle() + val moduleItem = uiState.modules.firstOrNull { it.module.base.name == dir } + + CollectNavEvents(viewModel, navigator) + + LaunchedEffect(Unit) { + // E.g. restored after process death straight into this screen + if (uiState.modules.isEmpty()) viewModel.startLoading() + } + + // If the module disappears while this screen is shown (e.g. removed by a reload after it was + // uninstalled elsewhere), leave instead of showing nothing. Only leave if this screen is + // still on top, so the screen below is never popped. + val isGone = !uiState.loading && moduleItem == null + LaunchedEffect(isGone) { + if (isGone && navigator.current() == WearRoute.ModuleDetail(dir)) navigator.pop() + } + + val state = rememberTransformingLazyColumnState() + + if (uiState.loading) { + LoadingScreen() + return + } + + if (moduleItem == null) return + + ScreenScaffold(state) { contentPadding -> + TransformingLazyColumn(state = state, contentPadding = contentPadding) { + item(key = "header") { + ModuleHeader(moduleItem) + } + item(key = "enabled") { + SwitchButton( + checked = moduleItem.isEnabled, + onCheckedChange = { viewModel.toggleEnabled(moduleItem) }, + label = { Text(stringResource(CoreR.string.wear_module_enabled)) }, + modifier = Modifier.fillMaxWidth(), + ) + } + // Shown when the phone app shows it: the action of a disabled or removed module + // can't run as intended + if (moduleItem.showAction && moduleItem.isEnabled && !moduleItem.isRemoved) { + item(key = "action") { + FilledTonalButton( + onClick = { viewModel.runAction(dir, moduleItem.module.name) }, + icon = { Icon(Icons.Filled.PlayArrow, contentDescription = null) }, + label = { Text(stringResource(CoreR.string.wear_module_run_action)) }, + modifier = Modifier.fillMaxWidth(), + ) + } + } + item(key = "remove") { + Button( + onClick = { viewModel.toggleRemove(moduleItem) }, + // An update waiting for the reboot replaces the module anyway + enabled = !moduleItem.isUpdated, + colors = if (moduleItem.isRemoved) { + ButtonDefaults.filledTonalButtonColors() + } else { + destructiveButtonColors() + }, + icon = { + Icon( + if (moduleItem.isRemoved) Icons.AutoMirrored.Filled.Undo else Icons.Filled.Delete, + contentDescription = null, + ) + }, + label = { + Text( + stringResource( + if (moduleItem.isRemoved) CoreR.string.module_state_restore + else CoreR.string.wear_module_remove + ) + ) + }, + modifier = Modifier.fillMaxWidth(), + ) + } + } + } +} + +@Composable +private fun ModuleHeader(item: ModuleItem) { + val module = item.module + val colors = MaterialTheme.colorScheme + val strikeThrough = if (item.isRemoved) TextDecoration.LineThrough else TextDecoration.None + + Column( + modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp), + horizontalAlignment = Alignment.CenterHorizontally, + ) { + ScreenTitle(text = module.name, textDecoration = strikeThrough) + Text( + text = stringResource(CoreR.string.module_version_author, module.version, module.author), + style = MaterialTheme.typography.bodySmall, + color = colors.onSurfaceVariant, + textAlign = TextAlign.Center, + ) + Text( + text = stringResource( + when { + item.isRemoved -> CoreR.string.wear_module_removed + item.isEnabled -> CoreR.string.wear_module_active + else -> CoreR.string.wear_module_disabled + } + ), + style = MaterialTheme.typography.labelSmall, + color = if (item.isEnabled && !item.isRemoved) colors.primary else colors.onSurfaceVariant, + modifier = Modifier.padding(top = 2.dp), + ) + if (item.showNotice) { + Text( + text = item.noticeText.getText(LocalResources.current), + style = MaterialTheme.typography.labelSmall, + color = colors.primary, + textAlign = TextAlign.Center, + modifier = Modifier.padding(top = 4.dp), + ) + } + if (module.description.isNotBlank()) { + Text( + text = module.description, + style = MaterialTheme.typography.bodySmall, + textAlign = TextAlign.Center, + modifier = Modifier.padding(top = 6.dp), + ) + } + } +} diff --git a/app/wear/src/main/java/com/topjohnwu/magisk/wear/module/ModulesScreen.kt b/app/wear/src/main/java/com/topjohnwu/magisk/wear/module/ModulesScreen.kt new file mode 100644 index 0000000000000..4c8ef520838db --- /dev/null +++ b/app/wear/src/main/java/com/topjohnwu/magisk/wear/module/ModulesScreen.kt @@ -0,0 +1,260 @@ +package com.topjohnwu.magisk.wear.module + +import android.content.Context +import android.net.Uri +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Add +import androidx.compose.material.icons.filled.RestartAlt +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalResources +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextDecoration +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.wear.compose.foundation.lazy.TransformingLazyColumn +import androidx.wear.compose.foundation.lazy.items +import androidx.wear.compose.foundation.lazy.rememberTransformingLazyColumnState +import androidx.wear.compose.material3.AlertDialog +import androidx.wear.compose.material3.AlertDialogDefaults +import androidx.wear.compose.material3.FilledTonalButton +import androidx.wear.compose.material3.Icon +import androidx.wear.compose.material3.IconButton +import androidx.wear.compose.material3.ListHeader +import androidx.wear.compose.material3.MaterialTheme +import androidx.wear.compose.material3.ScreenScaffold +import androidx.wear.compose.material3.SplitSwitchButton +import androidx.wear.compose.material3.Text +import com.topjohnwu.magisk.core.ktx.reboot +import com.topjohnwu.magisk.ui.flash.queryDisplayName +import com.topjohnwu.magisk.ui.flash.sanitizeDisplayName +import com.topjohnwu.magisk.ui.module.ModuleItem +import com.topjohnwu.magisk.ui.module.ModuleViewModel +import com.topjohnwu.magisk.wear.component.LoadingScreen +import com.topjohnwu.magisk.wear.files.FileKind +import com.topjohnwu.magisk.wear.files.rememberFilePicker +import com.topjohnwu.magisk.wear.nav.CollectNavEvents +import com.topjohnwu.magisk.wear.nav.WearNavigator +import com.topjohnwu.magisk.wear.nav.WearRoute +import kotlinx.coroutines.launch +import com.topjohnwu.magisk.core.R as CoreR + +// Bits of the state of a module that only take effect after a reboot +private const val STATE_ENABLED = 1 +private const val STATE_REMOVED = 2 + +private val ModuleItem.pendingState: Int + get() = (if (isEnabled) STATE_ENABLED else 0) or (if (isRemoved) STATE_REMOVED else 0) + +/** + * The installed modules. [viewModel] is shared with [ModuleDetailScreen], so changes made there + * show up here right away. + * + * [loadedStates] keeps the state of each module (by directory) when it was first loaded. Changes + * are written to disk right away, so a reload can't tell them apart; this is what stays active + * until the next reboot. It is filled in place, and kept as long as [viewModel], so leaving this + * screen doesn't hide pending changes. + */ +@Composable +fun ModulesScreen( + viewModel: ModuleViewModel, + navigator: WearNavigator, + loadedStates: MutableMap, +) { + val uiState by viewModel.uiState.collectAsStateWithLifecycle() + val context = LocalContext.current + val resources = LocalResources.current + val scope = rememberCoroutineScope() + + // Reload whenever the screen is shown again, like the phone app does when its tab is selected + LaunchedEffect(viewModel) { + viewModel.startLoading() + } + CollectNavEvents(viewModel, navigator) + + // Record every module seen for the first time before comparing, so none is skipped + uiState.modules.forEach { loadedStates.getOrPut(it.module.base.name) { it.pendingState } } + val needsReboot = uiState.modules.any { loadedStates[it.module.base.name] != it.pendingState } + var showReboot by rememberSaveable { mutableStateOf(false) } + + var pendingInstall by remember { mutableStateOf(null) } + // Not cleared, so the text stays while the dialog animates out after it is answered + var installMessage by remember { mutableStateOf("") } + val pickZip = rememberFilePicker(FileKind.ZIP) { uri -> + scope.launch { + val name = displayName(context, uri) + installMessage = resources.getString(CoreR.string.confirm_install, name) + pendingInstall = uri + } + } + + // Kept across the loading screen, so the list doesn't scroll back when it ends + val state = rememberTransformingLazyColumnState() + + if (uiState.loading) { + LoadingScreen() + return + } + + ScreenScaffold(state) { contentPadding -> + TransformingLazyColumn(state = state, contentPadding = contentPadding) { + item(key = "header") { + ListHeader { + Row(verticalAlignment = Alignment.CenterVertically) { + Text(stringResource(CoreR.string.modules)) + IconButton(onClick = pickZip) { + Icon( + Icons.Filled.Add, + contentDescription = stringResource( + CoreR.string.module_action_install_external + ), + ) + } + } + } + } + if (needsReboot) { + item(key = "reboot") { + FilledTonalButton( + onClick = { showReboot = true }, + icon = { Icon(Icons.Filled.RestartAlt, contentDescription = null) }, + label = { Text(stringResource(CoreR.string.wear_module_reboot)) }, + modifier = Modifier.fillMaxWidth(), + ) + } + } + if (uiState.modules.isEmpty()) { + item(key = "empty") { + Text( + text = stringResource(CoreR.string.module_empty), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + textAlign = TextAlign.Center, + modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp), + ) + } + } else { + items( + items = uiState.modules, + // Module ids come from module.prop and can be duplicated, directory names can't + key = { it.module.base.name }, + ) { item -> + ModuleRow( + item = item, + onToggle = { viewModel.toggleEnabled(item) }, + onDetail = { + navigator.navigate(WearRoute.ModuleDetail(item.module.base.name)) + }, + ) + } + } + } + } + + AlertDialog( + visible = showReboot, + onDismissRequest = { showReboot = false }, + title = { Text(stringResource(CoreR.string.reboot_apply_change)) }, + confirmButton = { + AlertDialogDefaults.ConfirmButton(onClick = { + showReboot = false + reboot() + }) + }, + dismissButton = { + AlertDialogDefaults.DismissButton(onClick = { showReboot = false }) + }, + ) + + AlertDialog( + visible = pendingInstall != null, + onDismissRequest = { pendingInstall = null }, + title = { Text(stringResource(CoreR.string.confirm_install_title)) }, + text = { Text(installMessage) }, + confirmButton = { + AlertDialogDefaults.ConfirmButton(onClick = { + pendingInstall?.let { viewModel.confirmLocalInstall(it) } + pendingInstall = null + }) + }, + dismissButton = { + AlertDialogDefaults.DismissButton(onClick = { pendingInstall = null }) + }, + ) +} + +@Composable +private fun ModuleRow( + item: ModuleItem, + onToggle: () -> Unit, + onDetail: () -> Unit, +) { + val module = item.module + val status = when { + item.isRemoved -> stringResource(CoreR.string.wear_module_removed) + !item.isEnabled -> stringResource(CoreR.string.wear_module_disabled) + item.showNotice -> item.noticeText.getText(LocalResources.current) + else -> module.description + } + val strikeThrough = if (item.isRemoved) TextDecoration.LineThrough else TextDecoration.None + + SplitSwitchButton( + checked = item.isEnabled, + onCheckedChange = { onToggle() }, + toggleContentDescription = module.name, + onContainerClick = onDetail, + modifier = Modifier.fillMaxWidth(), + label = { + Column( + modifier = Modifier.weight(1f), + verticalArrangement = Arrangement.Center, + ) { + Text( + text = module.name, + textDecoration = strikeThrough, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + Text( + text = if (status.isBlank()) { + module.version + } else { + stringResource(CoreR.string.wear_module_subtitle, module.version, status) + }, + style = MaterialTheme.typography.labelSmall, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + }, + ) +} + +/** + * The name to show for a picked file, for the install confirmation. The name is chosen by the + * app that provides the file, so it comes with where the file comes from, like for a request + * sent by another app. Files copied by the root file list have no authority. + */ +private suspend fun displayName(context: Context, uri: Uri): String { + val name = queryDisplayName(context, uri)?.sanitizeDisplayName()?.ifEmpty { null } + ?: uri.lastPathSegment?.substringAfterLast('/')?.sanitizeDisplayName()?.ifEmpty { null } + ?: "module.zip" + val authority = uri.authority?.sanitizeDisplayName()?.ifEmpty { null } + return authority?.let { "$name ($it)" } ?: name +} diff --git a/app/wear/src/main/java/com/topjohnwu/magisk/wear/module/TerminalText.kt b/app/wear/src/main/java/com/topjohnwu/magisk/wear/module/TerminalText.kt new file mode 100644 index 0000000000000..a4171c2949329 --- /dev/null +++ b/app/wear/src/main/java/com/topjohnwu/magisk/wear/module/TerminalText.kt @@ -0,0 +1,127 @@ +package com.topjohnwu.magisk.wear.module + +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.setValue +import androidx.compose.runtime.snapshotFlow +import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.rememberTextMeasurer +import androidx.wear.compose.foundation.rotary.RotaryScrollableDefaults +import androidx.wear.compose.foundation.rotary.rotaryScrollable +import androidx.wear.compose.material3.MaterialTheme +import androidx.wear.compose.material3.Text +import com.topjohnwu.magisk.terminal.TerminalEmulator +import kotlinx.coroutines.launch +import kotlin.math.max + +// The emulator needs at least 2 of each; fewer than this is unreadable anyway +private const val MIN_COLUMNS = 16 +private const val MIN_ROWS = 4 + +/** + * The output of [emu] as plain monospace text, scrolled by touch and the rotary input, and + * following new output while it is scrolled to the end. + * + * Unlike the phone terminal, there is no horizontal scrolling: a horizontal swipe dismisses the + * screen. So the emulator is sized to the width that fits, and long lines wrap in the emulator. + * [onResized] is called once the emulator has that size, so the command can be started with it. + */ +@Composable +fun TerminalText( + emu: TerminalEmulator, + modifier: Modifier = Modifier, + onResized: () -> Unit = {}, +) { + val currentOnResized by rememberUpdatedState(onResized) + val style = MaterialTheme.typography.bodySmall.copy(fontFamily = FontFamily.Monospace) + val measurer = rememberTextMeasurer() + val cell = remember(style) { measurer.measure("M", style).size } + + var text by remember { mutableStateOf("") } + + // Re-read the buffer after new output or a resize. Only called on the main thread, where + // the emulator is written. + fun refresh() { + val screen = emu.screen + // Rows wrapped by the emulator stay separate lines: they already fit the width + text = screen.getSelectedText( + 0, -screen.activeTranscriptRows, screen.columns, screen.screenRows, joinBackLines = false + ).trimEnd() + } + + DisposableEffect(emu) { + refresh() + emu.onScreenUpdate = { refresh() } + onDispose { + emu.onScreenUpdate = null + } + } + + BoxWithConstraints(modifier = modifier) { + // Inside an unbounded parent (e.g. a scrolling list), fall back to the minimum + val columns = if (constraints.hasBoundedWidth) { + max(MIN_COLUMNS, constraints.maxWidth / max(1, cell.width)) + } else MIN_COLUMNS + val rows = if (constraints.hasBoundedHeight) { + max(MIN_ROWS, constraints.maxHeight / max(1, cell.height)) + } else MIN_ROWS + + LaunchedEffect(columns, rows) { + emu.resize(columns, rows, cell.width, cell.height) + // The emulator outlives this screen (e.g. across rotation), and the text was read + // before this resize, so read it again with the new geometry + refresh() + currentOnResized() + } + + val scrollState = rememberScrollState() + // Follow new output, unless the user has scrolled away from the end + LaunchedEffect(scrollState) { + var following = true + var lastMax = scrollState.maxValue + snapshotFlow { scrollState.value to scrollState.maxValue }.collect { (value, maxValue) -> + if (maxValue != lastMax) { + lastMax = maxValue + // A child job: when a user scroll interrupts it, only it is cancelled + if (following) launch { scrollState.scrollTo(maxValue) } + } else if (maxValue != Int.MAX_VALUE) { + // Int.MAX_VALUE until the first layout, which says nothing about the user + following = value >= maxValue + } + } + } + + val focusRequester = remember { FocusRequester() } + LaunchedEffect(Unit) { + focusRequester.requestFocus() + } + + Column( + modifier = Modifier + .fillMaxWidth() + .rotaryScrollable( + behavior = RotaryScrollableDefaults.behavior(scrollState), + focusRequester = focusRequester, + ) + .verticalScroll(scrollState) + ) { + Text( + text = text, + style = style, + color = MaterialTheme.colorScheme.onSurface, + ) + } + } +} diff --git a/app/wear/src/main/java/com/topjohnwu/magisk/wear/nav/WearNav.kt b/app/wear/src/main/java/com/topjohnwu/magisk/wear/nav/WearNav.kt index 627638723d94e..c7975ef89ce76 100644 --- a/app/wear/src/main/java/com/topjohnwu/magisk/wear/nav/WearNav.kt +++ b/app/wear/src/main/java/com/topjohnwu/magisk/wear/nav/WearNav.kt @@ -3,8 +3,12 @@ package com.topjohnwu.magisk.wear.nav import android.net.Uri import android.os.Parcelable import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateMapOf +import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.saveable.Saver import androidx.compose.runtime.saveable.listSaver import androidx.compose.runtime.saveable.rememberSaveable @@ -57,6 +61,13 @@ class WearNavigator(val backStack: NavBackStack) { // See setPickResult for how a result reaches its caller. private val pickResults = mutableStateMapOf() + // Back handlers of the screens that currently refuse to be dismissed, latest last, see + // BlockDismiss. Not saved: the screens block again when they are composed after a restore. + private val dismissBlockers = mutableStateListOf() + + /** Whether the current screen may be swiped away or left with back. */ + val isDismissEnabled: Boolean get() = dismissBlockers.isEmpty() + fun navigate(key: NavKey) { // Ignore pushing the screen that is already on top (e.g. a double tap, or the same // request delivered twice). Both copies would get the same content key, so they would @@ -95,6 +106,26 @@ class WearNavigator(val backStack: NavBackStack) { fun consumePickResult(kind: FileKind): Uri? = pickResults.remove(kind) + /** + * Handle back from NavDisplay: pop, or while dismissal is blocked, let the latest + * [BlockDismiss] handle it instead. Screens leave themselves with [pop]. + */ + fun back() { + val blocker = dismissBlockers.lastOrNull() + if (blocker != null) blocker.onBack() else pop() + } + + internal fun addDismissBlocker(blocker: DismissBlocker) { + dismissBlockers.add(blocker) + } + + internal fun removeDismissBlocker(blocker: DismissBlocker) { + dismissBlockers.remove(blocker) + } + + // Compared by identity, so each BlockDismiss removes exactly its own entry + internal class DismissBlocker(val onBack: () -> Unit) + companion object { val Saver: Saver = listSaver( save = { navigator -> navigator.backStack.toList() }, @@ -123,6 +154,28 @@ val LocalWearNavigator = staticCompositionLocalOf { error("LocalWearNavigator not provided") } +/** + * While [blocked], the screen can't be swiped away, and back calls [onBlockedBack] instead of + * leaving it, e.g. to ask for confirmation; the screen then leaves with [WearNavigator.pop]. + * Back reaches it through the NavDisplay's onBack ([WearNavigator.back]), so it doesn't depend + * on the order of back handlers. If several screens block at once, the latest one gets back. + * The block ends when [blocked] turns false or this leaves the composition. + */ +@Composable +fun BlockDismiss( + blocked: Boolean, + onBlockedBack: () -> Unit, + navigator: WearNavigator = LocalWearNavigator.current, +) { + val currentOnBlockedBack by rememberUpdatedState(onBlockedBack) + if (!blocked) return + DisposableEffect(navigator) { + val blocker = WearNavigator.DismissBlocker { currentOnBlockedBack() } + navigator.addDismissBlocker(blocker) + onDispose { navigator.removeDismissBlocker(blocker) } + } +} + @Composable fun CollectNavEvents(viewModel: BaseViewModel, navigator: WearNavigator) { LaunchedEffect(viewModel) { From d4c0956f53efbf586773b44784dffc81149818b0 Mon Sep 17 00:00:00 2001 From: Jakub Mendyka Date: Mon, 23 Nov 2026 17:10:35 +0100 Subject: [PATCH 10/12] Add Wear install and flash screens Install offers patching an image picked from storage, direct install and, with root on A/B devices, the inactive slot with the phone UI's warning, plus the patching options that apply to the device. Direct install asks for confirmation first. The flash screen shows the installer output with a progress ring on the screen edge. While a boot image is flashed or patched it cannot be left; a module zip can be left after confirming, like on the phone. Restoring the images warns first and shows the SHA1 of the stock boot backup read from Magisk's config. It only starts on a long press, and only when the backup exists. The home view model is now owned by the activity, so the restore screen shares it and its loading state with the home screen. Flashing and restoring keep the screen on, so the app stays in the foreground and is not killed for memory halfway through. Assisted-by: Claude Opus 5.5 --- app/core/src/main/res/values-pl/strings.xml | 7 + app/core/src/main/res/values/strings.xml | 7 + .../java/com/topjohnwu/magisk/wear/WearUi.kt | 45 ++++- .../magisk/wear/install/BackupInfo.kt | 52 ++++++ .../magisk/wear/install/FlashScreen.kt | 145 ++++++++++++++++ .../magisk/wear/install/InstallScreen.kt | 156 ++++++++++++++++++ .../magisk/wear/install/RestoreScreen.kt | 144 ++++++++++++++++ .../magisk/wear/install/BackupInfoTest.kt | 50 ++++++ 8 files changed, 600 insertions(+), 6 deletions(-) create mode 100644 app/wear/src/main/java/com/topjohnwu/magisk/wear/install/BackupInfo.kt create mode 100644 app/wear/src/main/java/com/topjohnwu/magisk/wear/install/FlashScreen.kt create mode 100644 app/wear/src/main/java/com/topjohnwu/magisk/wear/install/InstallScreen.kt create mode 100644 app/wear/src/main/java/com/topjohnwu/magisk/wear/install/RestoreScreen.kt create mode 100644 app/wear/src/test/java/com/topjohnwu/magisk/wear/install/BackupInfoTest.kt diff --git a/app/core/src/main/res/values-pl/strings.xml b/app/core/src/main/res/values-pl/strings.xml index 864f54a218800..159dc92222da5 100644 --- a/app/core/src/main/res/values-pl/strings.xml +++ b/app/core/src/main/res/values-pl/strings.xml @@ -232,4 +232,11 @@ Uruchom akcję Usuń moduł Trwa… + Załatać obraz boot tego urządzenia i od razu go wgrać? + Nie zdejmuj z ładowarki + Poczekaj, aż się skończy + Wgrywa z powrotem stockowy obraz boot zapisany przy instalacji Magiska. Po ponownym uruchomieniu Magiska już nie będzie. + SHA1 kopii + Brak kopii obrazu boot + Przytrzymaj, aby przywrócić diff --git a/app/core/src/main/res/values/strings.xml b/app/core/src/main/res/values/strings.xml index 9aaeba4c9ad8c..54d421d530480 100644 --- a/app/core/src/main/res/values/strings.xml +++ b/app/core/src/main/res/values/strings.xml @@ -262,4 +262,11 @@ Run action Remove module Running… + Patch the boot image of this device and flash it now? + Keep the watch on the charger + Wait until it finishes + Flashes back the stock boot image saved when Magisk was installed. Magisk is gone after a reboot. + Backup SHA1 + No boot image backup + Hold to restore diff --git a/app/wear/src/main/java/com/topjohnwu/magisk/wear/WearUi.kt b/app/wear/src/main/java/com/topjohnwu/magisk/wear/WearUi.kt index 1ea13d4c1fc38..049dd13502612 100644 --- a/app/wear/src/main/java/com/topjohnwu/magisk/wear/WearUi.kt +++ b/app/wear/src/main/java/com/topjohnwu/magisk/wear/WearUi.kt @@ -46,8 +46,11 @@ import com.topjohnwu.magisk.core.Config import com.topjohnwu.magisk.core.Const import com.topjohnwu.magisk.core.base.ActivityExtension import com.topjohnwu.magisk.ui.flash.FlashUtils +import com.topjohnwu.magisk.ui.flash.FlashViewModel import com.topjohnwu.magisk.ui.flash.queryDisplayName import com.topjohnwu.magisk.ui.flash.sanitizeDisplayName +import com.topjohnwu.magisk.ui.home.HomeViewModel +import com.topjohnwu.magisk.ui.install.InstallViewModel import com.topjohnwu.magisk.ui.log.LogViewModel import com.topjohnwu.magisk.ui.module.ActionViewModel import com.topjohnwu.magisk.ui.module.ModuleViewModel @@ -57,6 +60,9 @@ import com.topjohnwu.magisk.ui.superuser.SuperuserViewModel import com.topjohnwu.magisk.ui.unsupportedMessages import com.topjohnwu.magisk.wear.files.PickScreen import com.topjohnwu.magisk.wear.home.HomeScreen +import com.topjohnwu.magisk.wear.install.FlashScreen +import com.topjohnwu.magisk.wear.install.InstallScreen +import com.topjohnwu.magisk.wear.install.RestoreScreen import com.topjohnwu.magisk.wear.log.LogScreen import com.topjohnwu.magisk.wear.module.ActionScreen import com.topjohnwu.magisk.wear.module.ModuleDetailScreen @@ -134,12 +140,35 @@ class WearUi( ) ), entryProvider = entryProvider { - entry { HomeScreen(navigator) } + entry { + // Owned by the activity, so the Restore screen shares it, and + // its loading state, with this one + val vm: HomeViewModel = viewModel( + viewModelStoreOwner = activity, factory = VMFactory + ) + HomeScreen(navigator, vm) + } entry { Placeholder(stringResource(CoreR.string.denylist)) } - entry { - Placeholder(stringResource(CoreR.string.flash_screen_title)) + entry { key -> + val vm: FlashViewModel = viewModel(factory = VMFactory) + if (vm.isInterrupted) { + // Restored after process death: nothing is left to show + LeaveInterruptedScreen(navigator, key) + return@entry + } + LaunchedEffect(key) { + if (vm.flashAction.isEmpty()) { + vm.flashAction = key.action + vm.flashUri = key.additionalData?.toUri() + vm.usbDevice = key.usbDevice + vm.startFlashing() + } + } + FlashScreen(vm, action = key.action, onLeave = { + if (navigator.current() == key) navigator.pop() + }) } entry { key -> // Owned by the activity, so the list and its details share one @@ -199,14 +228,18 @@ class WearUi( ModuleDetailScreen(key.dir, vm, navigator) } entry { - Placeholder(stringResource(CoreR.string.install)) + val vm: InstallViewModel = viewModel(factory = VMFactory) + InstallScreen(vm, navigator) } entry { Placeholder(stringResource(CoreR.string.settings)) } entry { key -> PickScreen(key.kind, navigator) } - entry { - Placeholder(stringResource(CoreR.string.restore_img)) + entry { key -> + val vm: HomeViewModel = viewModel( + viewModelStoreOwner = activity, factory = VMFactory + ) + RestoreScreen(vm, navigator, key) } } ) diff --git a/app/wear/src/main/java/com/topjohnwu/magisk/wear/install/BackupInfo.kt b/app/wear/src/main/java/com/topjohnwu/magisk/wear/install/BackupInfo.kt new file mode 100644 index 0000000000000..ad42bcfb584c9 --- /dev/null +++ b/app/wear/src/main/java/com/topjohnwu/magisk/wear/install/BackupInfo.kt @@ -0,0 +1,52 @@ +package com.topjohnwu.magisk.wear.install + +import com.topjohnwu.magisk.core.ktx.await +import com.topjohnwu.magisk.terminal.shellQuoted +import com.topjohnwu.superuser.Shell +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext + +/** + * The stock boot image backup that Magisk saved when it patched the installed boot image, + * which restoring the images flashes back. + * + * @param sha1 the SHA1 of the stock image, as recorded in Magisk's config, or null if none is + * @param exists whether the backup is there to be restored + */ +data class BackupInfo(val sha1: String?, val exists: Boolean) { + + companion object { + + private const val SHA1_PREFIX = "SHA1=" + + /** Directory of the backup of the image with [sha1], see restore_imgs in the scripts */ + fun backupDir(sha1: String) = "/data/magisk_backup_$sha1" + + /** + * Read the backup from the content of `$MAGISKTMP/.magisk/config`. Like grep_prop in + * the scripts, the first `SHA1=` line counts. [backupDirExists] is asked about the + * backup directory only when there is a SHA1. + */ + fun parse(config: String, backupDirExists: (String) -> Boolean): BackupInfo { + val sha1 = config.lineSequence() + .firstOrNull { it.startsWith(SHA1_PREFIX) } + ?.removePrefix(SHA1_PREFIX) + // The scripts run the config through dos2unix + ?.trimEnd('\r') + ?.ifEmpty { null } + ?: return BackupInfo(null, false) + return BackupInfo(sha1, backupDirExists(backupDir(sha1))) + } + + /** Read the backup through the root shell. Without root, there is none. */ + suspend fun read(): BackupInfo = withContext(Dispatchers.IO) { + val config = Shell.cmd("cat \"\$(magisk --path)/.magisk/config\"").await() + if (!config.isSuccess) return@withContext BackupInfo(null, false) + parse(config.out.joinToString("\n")) { dir -> + // Same checks as restore_imgs, which fails without the image in the directory + val quoted = dir.shellQuoted() + Shell.cmd("[ -d $quoted ] && [ -f $quoted/boot.img.gz ]").exec().isSuccess + } + } + } +} diff --git a/app/wear/src/main/java/com/topjohnwu/magisk/wear/install/FlashScreen.kt b/app/wear/src/main/java/com/topjohnwu/magisk/wear/install/FlashScreen.kt new file mode 100644 index 0000000000000..d45ad7a14d592 --- /dev/null +++ b/app/wear/src/main/java/com/topjohnwu/magisk/wear/install/FlashScreen.kt @@ -0,0 +1,145 @@ +package com.topjohnwu.magisk.wear.install + +import android.widget.Toast +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.keepScreenOn +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.wear.compose.material3.AlertDialog +import androidx.wear.compose.material3.AlertDialogDefaults +import androidx.wear.compose.material3.CircularProgressIndicator +import androidx.wear.compose.material3.CompactButton +import androidx.wear.compose.material3.MaterialTheme +import androidx.wear.compose.material3.ScreenScaffold +import androidx.wear.compose.material3.Text +import com.topjohnwu.magisk.core.Const +import com.topjohnwu.magisk.core.ktx.toast +import com.topjohnwu.magisk.ui.flash.FlashViewModel +import com.topjohnwu.magisk.wear.module.TerminalText +import com.topjohnwu.magisk.wear.nav.BlockDismiss +import com.topjohnwu.magisk.core.R as CoreR + +/** + * The output of an installation, with an indeterminate progress ring on the edge of the screen + * while it runs. + * + * While it runs, the screen can't be swiped away. Flashing or patching a boot image can't be + * left at all: stopping halfway is never safer than waiting. Only a module zip, which runs a + * script from the module that may hang, can be left after a confirmation, like the phone app. + */ +@Composable +fun FlashScreen( + viewModel: FlashViewModel, + action: String, + onLeave: () -> Unit, +) { + val context = LocalContext.current + val flashState by viewModel.flashState.collectAsStateWithLifecycle() + val showReboot by viewModel.showReboot.collectAsStateWithLifecycle() + val flashing = flashState == FlashViewModel.State.FLASHING + val leavable = action == Const.Value.FLASH_ZIP + var showExit by rememberSaveable { mutableStateOf(false) } + + BlockDismiss(blocked = flashing, onBlockedBack = { + if (leavable) { + showExit = true + } else { + context.toast(CoreR.string.wear_flash_wait, Toast.LENGTH_SHORT) + } + }) + + ScreenScaffold { contentPadding -> + // Watches turn the screen off quickly. Keep it on while this runs, so the app stays in + // the foreground and is not killed for memory halfway through. + Box( + modifier = Modifier + .fillMaxSize() + .then(if (flashing) Modifier.keepScreenOn() else Modifier) + ) { + if (flashing) { + CircularProgressIndicator(modifier = Modifier.fillMaxSize()) + } + Column( + modifier = Modifier + .fillMaxSize() + .padding(contentPadding), + horizontalAlignment = Alignment.CenterHorizontally, + ) { + Text( + text = stringResource(CoreR.string.flash_screen_title), + style = MaterialTheme.typography.titleSmall, + textAlign = TextAlign.Center, + ) + val colors = MaterialTheme.colorScheme + Text( + text = stringResource( + when (flashState) { + FlashViewModel.State.FLASHING -> CoreR.string.flashing + FlashViewModel.State.SUCCESS -> CoreR.string.done + FlashViewModel.State.FAILED -> CoreR.string.failure + } + ), + style = MaterialTheme.typography.labelSmall, + color = when (flashState) { + FlashViewModel.State.FLASHING -> colors.onSurfaceVariant + FlashViewModel.State.SUCCESS -> colors.primary + FlashViewModel.State.FAILED -> colors.error + }, + ) + TerminalText( + emu = viewModel.emulator, + modifier = Modifier + .weight(1f) + .fillMaxWidth() + .padding(horizontal = 8.dp, vertical = 4.dp), + // A module install waits for this to start with the real terminal size + onResized = viewModel::onTerminalResized, + ) + if (flashing) { + Text( + text = stringResource(CoreR.string.wear_flash_keep_charging), + style = MaterialTheme.typography.labelSmall, + color = colors.onSurfaceVariant, + textAlign = TextAlign.Center, + ) + } else if (flashState == FlashViewModel.State.SUCCESS && showReboot) { + CompactButton( + onClick = { viewModel.restartPressed() }, + label = { Text(stringResource(CoreR.string.reboot)) }, + ) + } + } + } + } + + AlertDialog( + // Not shown any more once the installation has finished meanwhile: back just leaves then + visible = showExit && flashing, + onDismissRequest = { showExit = false }, + title = { Text(stringResource(CoreR.string.running_exit_title)) }, + text = { Text(stringResource(CoreR.string.running_exit_msg)) }, + confirmButton = { + AlertDialogDefaults.ConfirmButton(onClick = { + showExit = false + onLeave() + }) + }, + dismissButton = { + AlertDialogDefaults.DismissButton(onClick = { showExit = false }) + }, + ) +} diff --git a/app/wear/src/main/java/com/topjohnwu/magisk/wear/install/InstallScreen.kt b/app/wear/src/main/java/com/topjohnwu/magisk/wear/install/InstallScreen.kt new file mode 100644 index 0000000000000..2190ef552943a --- /dev/null +++ b/app/wear/src/main/java/com/topjohnwu/magisk/wear/install/InstallScreen.kt @@ -0,0 +1,156 @@ +package com.topjohnwu.magisk.wear.install + +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.wear.compose.foundation.lazy.TransformingLazyColumn +import androidx.wear.compose.foundation.lazy.TransformingLazyColumnScope +import androidx.wear.compose.foundation.lazy.rememberTransformingLazyColumnState +import androidx.wear.compose.material3.AlertDialog +import androidx.wear.compose.material3.AlertDialogDefaults +import androidx.wear.compose.material3.Button +import androidx.wear.compose.material3.FilledTonalButton +import androidx.wear.compose.material3.ListHeader +import androidx.wear.compose.material3.ScreenScaffold +import androidx.wear.compose.material3.SwitchButton +import androidx.wear.compose.material3.Text +import com.topjohnwu.magisk.core.Config +import com.topjohnwu.magisk.core.Info +import com.topjohnwu.magisk.ui.install.InstallViewModel +import com.topjohnwu.magisk.wear.files.FileKind +import com.topjohnwu.magisk.wear.files.rememberFilePicker +import com.topjohnwu.magisk.wear.nav.CollectNavEvents +import com.topjohnwu.magisk.wear.nav.WearNavigator +import com.topjohnwu.magisk.core.R as CoreR + +/** + * The ways to install Magisk, like the phone app's install dialog: patch an image file, + * install directly, or install to the inactive slot after an OTA. Each one opens the flash + * screen through [InstallViewModel.install]. + */ +@Composable +fun InstallScreen(viewModel: InstallViewModel, navigator: WearNavigator) { + val uiState by viewModel.uiState.collectAsStateWithLifecycle() + var showDirectConfirm by rememberSaveable { mutableStateOf(false) } + + CollectNavEvents(viewModel, navigator) + + // Sets the method itself and goes on to install, see onPatchSelected + val pickImage = rememberFilePicker(FileKind.IMAGE) { uri -> + viewModel.onPatchSelected(uri) + } + + val state = rememberTransformingLazyColumnState() + ScreenScaffold(state) { contentPadding -> + TransformingLazyColumn(state = state, contentPadding = contentPadding) { + item { + ListHeader { Text(stringResource(CoreR.string.install)) } + } + if (!viewModel.skipOptions) { + installOptions() + } + item { + FilledTonalButton( + onClick = pickImage, + label = { Text(stringResource(CoreR.string.patch_image)) }, + modifier = Modifier.fillMaxWidth(), + ) + } + if (viewModel.isRooted) { + item { + Button( + onClick = { showDirectConfirm = true }, + label = { Text(stringResource(CoreR.string.direct_install)) }, + modifier = Modifier.fillMaxWidth(), + ) + } + } + // Only offered with root on an A/B device, like the phone app + if (!viewModel.noSecondSlot) { + item { + FilledTonalButton( + onClick = { viewModel.selectMethod(InstallViewModel.Method.INACTIVE_SLOT) }, + label = { Text(stringResource(CoreR.string.install_inactive_slot)) }, + modifier = Modifier.fillMaxWidth(), + ) + } + } + } + } + + AlertDialog( + visible = showDirectConfirm, + onDismissRequest = { showDirectConfirm = false }, + title = { Text(stringResource(CoreR.string.direct_install)) }, + text = { Text(stringResource(CoreR.string.wear_install_direct_msg)) }, + confirmButton = { + AlertDialogDefaults.ConfirmButton(onClick = { + showDirectConfirm = false + // Set only now: the method is kept in memory, and the dialog survives the process + viewModel.selectMethod(InstallViewModel.Method.DIRECT) + viewModel.install() + }) + }, + dismissButton = { + AlertDialogDefaults.DismissButton(onClick = { showDirectConfirm = false }) + }, + ) + + // Shown while the view model asks for it, so it never outlives the method it confirms + AlertDialog( + visible = uiState.showSecondSlotWarning, + onDismissRequest = { viewModel.onSecondSlotWarningConsumed() }, + title = { Text(stringResource(android.R.string.dialog_alert_title)) }, + text = { Text(stringResource(CoreR.string.install_inactive_slot_msg)) }, + confirmButton = { + AlertDialogDefaults.ConfirmButton(onClick = { + viewModel.onSecondSlotWarningConsumed() + viewModel.install() + }) + }, + dismissButton = { + AlertDialogDefaults.DismissButton(onClick = { viewModel.onSecondSlotWarningConsumed() }) + }, + ) +} + +/** The patching options of the phone app, each shown only where it applies. */ +private fun TransformingLazyColumnScope.installOptions() { + if (!Info.isSAR) { + item { + ConfigSwitch(CoreR.string.keep_dm_verity, Config.keepVerity) { Config.keepVerity = it } + } + } + if (Info.isFDE) { + item { + ConfigSwitch(CoreR.string.keep_force_encryption, Config.keepEnc) { Config.keepEnc = it } + } + } + if (!Info.ramdisk) { + item { + ConfigSwitch(CoreR.string.recovery_mode, Config.recovery) { Config.recovery = it } + } + } +} + +@Composable +private fun ConfigSwitch(label: Int, initial: Boolean, onChange: (Boolean) -> Unit) { + // Config is not observable, so keep what the switch shows here, like the phone app + var checked by remember { mutableStateOf(initial) } + SwitchButton( + checked = checked, + onCheckedChange = { + checked = it + onChange(it) + }, + label = { Text(stringResource(label)) }, + modifier = Modifier.fillMaxWidth(), + ) +} diff --git a/app/wear/src/main/java/com/topjohnwu/magisk/wear/install/RestoreScreen.kt b/app/wear/src/main/java/com/topjohnwu/magisk/wear/install/RestoreScreen.kt new file mode 100644 index 0000000000000..0e38623f3d066 --- /dev/null +++ b/app/wear/src/main/java/com/topjohnwu/magisk/wear/install/RestoreScreen.kt @@ -0,0 +1,144 @@ +package com.topjohnwu.magisk.wear.install + +import android.widget.Toast +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.keepScreenOn +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.navigation3.runtime.NavKey +import androidx.wear.compose.foundation.lazy.TransformingLazyColumn +import androidx.wear.compose.foundation.lazy.rememberTransformingLazyColumnState +import androidx.wear.compose.material3.Button +import androidx.wear.compose.material3.ListHeader +import androidx.wear.compose.material3.MaterialTheme +import androidx.wear.compose.material3.ScreenScaffold +import androidx.wear.compose.material3.Text +import com.topjohnwu.magisk.core.ktx.toast +import com.topjohnwu.magisk.ui.home.HomeViewModel +import com.topjohnwu.magisk.wear.component.LoadingScreen +import com.topjohnwu.magisk.wear.nav.BlockDismiss +import com.topjohnwu.magisk.wear.nav.WearNavigator +import com.topjohnwu.magisk.wear.theme.destructiveButtonColors +import com.topjohnwu.magisk.core.R as CoreR + +/** + * Warns before restoring the stock images, which flashes back the boot image backup that + * Magisk saved when it patched the installed one, and shows that backup's SHA1. Restoring has + * to be confirmed by holding the button, so a stray tap can't start it. + */ +@Composable +fun RestoreScreen(viewModel: HomeViewModel, navigator: WearNavigator, key: NavKey) { + val context = LocalContext.current + val uiState by viewModel.uiState.collectAsStateWithLifecycle() + // null while loading + var backup by remember { mutableStateOf(null) } + var started by rememberSaveable { mutableStateOf(false) } + val restoring = uiState.showLoading + + LaunchedEffect(Unit) { + backup = BackupInfo.read() + } + + // Leave once the restore has run: the view model shows its result as a toast + LaunchedEffect(restoring) { + if (restoring) { + started = true + } else if (started && navigator.current() == key) { + navigator.pop() + } + } + + BlockDismiss(blocked = restoring, onBlockedBack = { + context.toast(CoreR.string.wear_flash_wait, Toast.LENGTH_SHORT) + }) + + val state = rememberTransformingLazyColumnState() + + if (restoring) { + // Keep the screen on while the images are flashed back, like FlashScreen + LoadingScreen(modifier = Modifier.keepScreenOn()) + return + } + + ScreenScaffold(state) { contentPadding -> + TransformingLazyColumn(state = state, contentPadding = contentPadding) { + item { + ListHeader { Text(stringResource(CoreR.string.restore_img)) } + } + item { + Text( + text = stringResource(CoreR.string.wear_restore_msg), + style = MaterialTheme.typography.bodySmall, + textAlign = TextAlign.Center, + ) + } + item { + BackupCard(backup) + } + item { + Button( + onClick = { context.toast(CoreR.string.wear_restore_hold, Toast.LENGTH_SHORT) }, + onLongClick = { viewModel.restoreImages() }, + onLongClickLabel = stringResource(CoreR.string.restore_img), + enabled = backup?.exists == true, + colors = destructiveButtonColors(), + label = { Text(stringResource(CoreR.string.restore_img)) }, + secondaryLabel = { Text(stringResource(CoreR.string.wear_restore_hold)) }, + modifier = Modifier.fillMaxWidth(), + ) + } + } + } +} + +@Composable +private fun BackupCard(backup: BackupInfo?) { + val colors = MaterialTheme.colorScheme + Column( + modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp), + horizontalAlignment = Alignment.CenterHorizontally, + ) { + when { + backup == null -> Text( + text = stringResource(CoreR.string.loading), + style = MaterialTheme.typography.bodySmall, + color = colors.onSurfaceVariant, + ) + backup.exists && backup.sha1 != null -> { + Text( + text = stringResource(CoreR.string.wear_restore_sha1), + style = MaterialTheme.typography.labelSmall, + color = colors.onSurfaceVariant, + ) + Text( + text = backup.sha1, + style = MaterialTheme.typography.bodySmall.copy( + fontFamily = FontFamily.Monospace + ), + textAlign = TextAlign.Center, + ) + } + else -> Text( + text = stringResource(CoreR.string.wear_restore_no_backup), + style = MaterialTheme.typography.bodySmall, + color = colors.error, + textAlign = TextAlign.Center, + ) + } + } +} diff --git a/app/wear/src/test/java/com/topjohnwu/magisk/wear/install/BackupInfoTest.kt b/app/wear/src/test/java/com/topjohnwu/magisk/wear/install/BackupInfoTest.kt new file mode 100644 index 0000000000000..63ed0f14ad48b --- /dev/null +++ b/app/wear/src/test/java/com/topjohnwu/magisk/wear/install/BackupInfoTest.kt @@ -0,0 +1,50 @@ +package com.topjohnwu.magisk.wear.install + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class BackupInfoTest { + + private val config = + "KEEPVERITY=false\nKEEPFORCEENCRYPT=true\nSHA1=abc123\nRECOVERYMODE=false\n" + + @Test + fun backupExists() { + var asked: String? = null + val info = BackupInfo.parse(config) { dir -> + asked = dir + true + } + assertEquals(BackupInfo("abc123", true), info) + assertEquals("/data/magisk_backup_abc123", asked) + } + + @Test + fun backupMissing() { + assertEquals(BackupInfo("abc123", false), BackupInfo.parse(config) { false }) + } + + @Test + fun noSha1() { + var asked = false + val info = BackupInfo.parse("KEEPVERITY=false\nRECOVERYMODE=false\n") { + asked = true + true + } + assertEquals(BackupInfo(null, false), info) + assertEquals(false, asked) + } + + @Test + fun emptySha1() { + val info = BackupInfo.parse("KEEPVERITY=false\nSHA1=\n") { true } + assertNull(info.sha1) + assertEquals(false, info.exists) + } + + @Test + fun crlfLine() { + assertEquals(BackupInfo("abc123", true), BackupInfo.parse("SHA1=abc123\r\n") { true }) + } +} From 8e20fdbd8c2c925f61b50ce127362b273ed9a3f4 Mon Sep 17 00:00:00 2001 From: Jakub Mendyka Date: Mon, 23 Nov 2026 17:20:41 +0100 Subject: [PATCH 11/12] Add Wear settings and DenyList screens Settings shows the phone UI's Magisk, Superuser and update settings that make sense on a watch, under the same conditions and through the same SettingsViewModel calls. Choices open a list of radio buttons in a dialog, and the custom channel URL is typed with the system keyboard through RemoteInput (androidx.wear:wear-input). The DenyList switches whole apps with toggleAll; picking single processes is left to the phone UI. Assisted-by: Claude Opus 5.5 --- app/apk/src/main/AndroidManifest.xml | 2 +- app/core/src/main/res/values-pl/strings.xml | 1 + app/core/src/main/res/values/strings.xml | 1 + app/gradle/libs.versions.toml | 1 + app/wear/build.gradle.kts | 1 + .../java/com/topjohnwu/magisk/wear/WearUi.kt | 48 +- .../magisk/wear/settings/DenyListScreen.kt | 97 ++++ .../magisk/wear/settings/SettingsScreen.kt | 432 ++++++++++++++++++ 8 files changed, 558 insertions(+), 25 deletions(-) create mode 100644 app/wear/src/main/java/com/topjohnwu/magisk/wear/settings/DenyListScreen.kt create mode 100644 app/wear/src/main/java/com/topjohnwu/magisk/wear/settings/SettingsScreen.kt diff --git a/app/apk/src/main/AndroidManifest.xml b/app/apk/src/main/AndroidManifest.xml index 58a19329b9fd5..df7e281653bdb 100644 --- a/app/apk/src/main/AndroidManifest.xml +++ b/app/apk/src/main/AndroidManifest.xml @@ -4,7 +4,7 @@ - + SHA1 kopii Brak kopii obrazu boot Przytrzymaj, aby przywrócić + Aktualizacje diff --git a/app/core/src/main/res/values/strings.xml b/app/core/src/main/res/values/strings.xml index 54d421d530480..8688e2e7df0e3 100644 --- a/app/core/src/main/res/values/strings.xml +++ b/app/core/src/main/res/values/strings.xml @@ -269,4 +269,5 @@ Backup SHA1 No boot image backup Hold to restore + Updates diff --git a/app/gradle/libs.versions.toml b/app/gradle/libs.versions.toml index c9cd610b76baa..7741a67a414dc 100644 --- a/app/gradle/libs.versions.toml +++ b/app/gradle/libs.versions.toml @@ -77,6 +77,7 @@ navigationevent-compose = { module = "androidx.navigationevent:navigationevent-c wear-compose-foundation = { module = "androidx.wear.compose:compose-foundation", version.ref = "wear-compose" } wear-compose-material3 = { module = "androidx.wear.compose:compose-material3", version.ref = "wear-compose" } wear-compose-navigation3 = { module = "androidx.wear.compose:compose-navigation3", version.ref = "wear-compose" } +wear-input = { module = "androidx.wear:wear-input", version = "1.1.0" } # For build-logic android-gradle-plugin = { module = "com.android.tools.build:gradle", version.ref = "android" } diff --git a/app/wear/build.gradle.kts b/app/wear/build.gradle.kts index 78da65e3a19c3..0011759b10dc8 100644 --- a/app/wear/build.gradle.kts +++ b/app/wear/build.gradle.kts @@ -35,6 +35,7 @@ dependencies { implementation(libs.wear.compose.foundation) implementation(libs.wear.compose.material3) implementation(libs.wear.compose.navigation3) + implementation(libs.wear.input) // Navigation3 implementation(libs.navigation3.runtime) diff --git a/app/wear/src/main/java/com/topjohnwu/magisk/wear/WearUi.kt b/app/wear/src/main/java/com/topjohnwu/magisk/wear/WearUi.kt index 049dd13502612..3e6364e4f9e3b 100644 --- a/app/wear/src/main/java/com/topjohnwu/magisk/wear/WearUi.kt +++ b/app/wear/src/main/java/com/topjohnwu/magisk/wear/WearUi.kt @@ -3,14 +3,12 @@ package com.topjohnwu.magisk.wear import android.Manifest import android.annotation.SuppressLint import android.content.Context +import android.content.Intent import android.content.res.Configuration import android.os.Build import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.LaunchedEffect @@ -20,12 +18,9 @@ import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalResources import androidx.compose.ui.res.stringResource -import androidx.compose.ui.text.style.TextAlign import androidx.core.net.toUri import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.viewmodel.compose.viewModel @@ -37,7 +32,6 @@ import androidx.navigation3.ui.NavDisplay import androidx.wear.compose.material3.AlertDialog import androidx.wear.compose.material3.AlertDialogDefaults import androidx.wear.compose.material3.AppScaffold -import androidx.wear.compose.material3.ScreenScaffold import androidx.wear.compose.material3.Text import androidx.wear.compose.material3.TimeText import androidx.wear.compose.navigation3.rememberSwipeDismissableSceneStrategy @@ -45,6 +39,7 @@ import com.topjohnwu.magisk.arch.VMFactory import com.topjohnwu.magisk.core.Config import com.topjohnwu.magisk.core.Const import com.topjohnwu.magisk.core.base.ActivityExtension +import com.topjohnwu.magisk.ui.deny.DenyListViewModel import com.topjohnwu.magisk.ui.flash.FlashUtils import com.topjohnwu.magisk.ui.flash.FlashViewModel import com.topjohnwu.magisk.ui.flash.queryDisplayName @@ -55,6 +50,7 @@ import com.topjohnwu.magisk.ui.log.LogViewModel import com.topjohnwu.magisk.ui.module.ActionViewModel import com.topjohnwu.magisk.ui.module.ModuleViewModel import com.topjohnwu.magisk.ui.navigation.Route +import com.topjohnwu.magisk.ui.settings.SettingsViewModel import com.topjohnwu.magisk.ui.superuser.SuperuserGrantViewModel import com.topjohnwu.magisk.ui.superuser.SuperuserViewModel import com.topjohnwu.magisk.ui.unsupportedMessages @@ -71,6 +67,8 @@ import com.topjohnwu.magisk.wear.nav.LocalWearNavigator import com.topjohnwu.magisk.wear.nav.WearNavigator import com.topjohnwu.magisk.wear.nav.WearRoute import com.topjohnwu.magisk.wear.nav.rememberWearNavigator +import com.topjohnwu.magisk.wear.settings.DenyListScreen +import com.topjohnwu.magisk.wear.settings.SettingsScreen import com.topjohnwu.magisk.wear.superuser.GrantScreen import com.topjohnwu.magisk.wear.superuser.SuperuserDetailScreen import com.topjohnwu.magisk.wear.superuser.SuperuserScreen @@ -120,6 +118,7 @@ class WearUi( val moduleLoadedStates = rememberSaveable { HashMap() } CompositionLocalProvider(LocalWearNavigator provides navigator) { HandleFlashIntent(navigator) + HandleSettingsIntent(navigator) NavDisplay( backStack = navigator.backStack, @@ -149,7 +148,9 @@ class WearUi( HomeScreen(navigator, vm) } entry { - Placeholder(stringResource(CoreR.string.denylist)) + val vm: DenyListViewModel = viewModel(factory = VMFactory) + LaunchedEffect(Unit) { vm.startLoading() } + DenyListScreen(vm) } entry { key -> val vm: FlashViewModel = viewModel(factory = VMFactory) @@ -232,7 +233,8 @@ class WearUi( InstallScreen(vm, navigator) } entry { - Placeholder(stringResource(CoreR.string.settings)) + val vm: SettingsViewModel = viewModel(factory = VMFactory) + SettingsScreen(vm, navigator) } entry { key -> PickScreen(key.kind, navigator) } entry { key -> @@ -323,6 +325,19 @@ class WearUi( ) } + /** Opens the settings when the system asks for the app's preferences, like the phone app. */ + @Composable + private fun HandleSettingsIntent(navigator: WearNavigator) { + val intentVersion by intentState.collectAsStateWithLifecycle() + + LaunchedEffect(intentVersion) { + val currentIntent = activity.intent ?: return@LaunchedEffect + if (currentIntent.action != Intent.ACTION_APPLICATION_PREFERENCES) return@LaunchedEffect + currentIntent.action = null + navigator.navigate(WearRoute.Settings) + } + } + /** A confirmation shown by [HandleFlashIntent], completed with the user's answer. */ private class ConfirmRequest(val content: String) { val result = CompletableDeferred() @@ -348,21 +363,6 @@ private fun LeaveInterruptedScreen(navigator: WearNavigator, key: NavKey) { } } -/** Stands in for a screen that is not implemented yet. */ -@Composable -private fun Placeholder(title: String) { - ScreenScaffold { contentPadding -> - Box( - modifier = Modifier - .fillMaxSize() - .padding(contentPadding), - contentAlignment = Alignment.Center, - ) { - Text(title, textAlign = TextAlign.Center) - } - } -} - /** Shows each problem found by [unsupportedMessages] in turn, like the phone app on startup. */ @Composable private fun UnsupportedDialogs(messages: List>) { diff --git a/app/wear/src/main/java/com/topjohnwu/magisk/wear/settings/DenyListScreen.kt b/app/wear/src/main/java/com/topjohnwu/magisk/wear/settings/DenyListScreen.kt new file mode 100644 index 0000000000000..a93067570a41b --- /dev/null +++ b/app/wear/src/main/java/com/topjohnwu/magisk/wear/settings/DenyListScreen.kt @@ -0,0 +1,97 @@ +package com.topjohnwu.magisk.wear.settings + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.wear.compose.foundation.lazy.TransformingLazyColumn +import androidx.wear.compose.foundation.lazy.items +import androidx.wear.compose.foundation.lazy.rememberTransformingLazyColumnState +import androidx.wear.compose.material3.ListHeader +import androidx.wear.compose.material3.MaterialTheme +import androidx.wear.compose.material3.ScreenScaffold +import androidx.wear.compose.material3.SwitchButton +import androidx.wear.compose.material3.Text +import com.topjohnwu.magisk.ui.deny.DenyAppState +import com.topjohnwu.magisk.ui.deny.DenyListViewModel +import com.topjohnwu.magisk.wear.component.AppIcon +import com.topjohnwu.magisk.wear.component.LoadingScreen +import com.topjohnwu.magisk.core.R as CoreR + +/** + * The apps on the DenyList. Unlike the phone app, an app is switched as a whole with + * [DenyListViewModel.toggleAll]; its processes can't be picked one by one here. + */ +@Composable +fun DenyListScreen(viewModel: DenyListViewModel) { + val loading by viewModel.loading.collectAsStateWithLifecycle() + val apps by viewModel.filteredApps.collectAsStateWithLifecycle() + val showSystem by viewModel.showSystem.collectAsStateWithLifecycle() + + // Kept across the loading screen, so the list doesn't scroll back when it ends + val state = rememberTransformingLazyColumnState() + + if (loading) { + LoadingScreen() + return + } + + ScreenScaffold(state) { contentPadding -> + TransformingLazyColumn(state = state, contentPadding = contentPadding) { + item { + ListHeader { Text(stringResource(CoreR.string.denylist)) } + } + items( + items = apps, + key = { it.info.packageName }, + ) { app -> + DenyAppRow(app = app, onToggle = { viewModel.toggleAll(app) }) + } + item(key = "show_system") { + SwitchButton( + checked = showSystem, + onCheckedChange = viewModel::setShowSystem, + label = { Text(stringResource(CoreR.string.show_system_app)) }, + modifier = Modifier.fillMaxWidth(), + ) + } + } + } +} + +@Composable +private fun DenyAppRow(app: DenyAppState, onToggle: () -> Unit) { + SwitchButton( + // On when any of its processes is denied; switching it then removes them all, + // like tapping the partly checked box in the phone app + checked = app.isChecked, + onCheckedChange = { onToggle() }, + modifier = Modifier.fillMaxWidth(), + label = { + AppIcon(packageName = app.info.packageName, size = 28.dp) + Column( + modifier = Modifier.weight(1f).padding(start = 8.dp), + verticalArrangement = Arrangement.Center, + ) { + Text( + text = app.info.label, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + Text( + text = app.info.packageName, + style = MaterialTheme.typography.labelSmall, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + }, + ) +} diff --git a/app/wear/src/main/java/com/topjohnwu/magisk/wear/settings/SettingsScreen.kt b/app/wear/src/main/java/com/topjohnwu/magisk/wear/settings/SettingsScreen.kt new file mode 100644 index 0000000000000..fed8eb28488fb --- /dev/null +++ b/app/wear/src/main/java/com/topjohnwu/magisk/wear/settings/SettingsScreen.kt @@ -0,0 +1,432 @@ +package com.topjohnwu.magisk.wear.settings + +import android.Manifest.permission.POST_NOTIFICATIONS +import android.app.RemoteInput +import android.content.ActivityNotFoundException +import android.content.pm.PackageManager +import android.os.Build +import android.webkit.URLUtil +import android.widget.Toast +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Edit +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringArrayResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.dp +import androidx.core.content.ContextCompat +import androidx.lifecycle.compose.LifecycleResumeEffect +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.wear.compose.foundation.lazy.TransformingLazyColumn +import androidx.wear.compose.foundation.lazy.TransformingLazyColumnScope +import androidx.wear.compose.foundation.lazy.rememberTransformingLazyColumnState +import androidx.wear.compose.material3.AlertDialog +import androidx.wear.compose.material3.AlertDialogDefaults +import androidx.wear.compose.material3.ButtonDefaults +import androidx.wear.compose.material3.CompactButton +import androidx.wear.compose.material3.Dialog +import androidx.wear.compose.material3.FilledTonalButton +import androidx.wear.compose.material3.Icon +import androidx.wear.compose.material3.ListHeader +import androidx.wear.compose.material3.MaterialTheme +import androidx.wear.compose.material3.RadioButton +import androidx.wear.compose.material3.ScreenScaffold +import androidx.wear.compose.material3.SplitSwitchButton +import androidx.wear.compose.material3.SwitchButton +import androidx.wear.compose.material3.Text +import androidx.wear.input.RemoteInputIntentHelper +import com.topjohnwu.magisk.core.ktx.toast +import com.topjohnwu.magisk.ui.settings.SettingsDialog +import com.topjohnwu.magisk.ui.settings.SettingsUiState +import com.topjohnwu.magisk.ui.settings.SettingsViewModel +import com.topjohnwu.magisk.wear.nav.CollectNavEvents +import com.topjohnwu.magisk.wear.nav.WearNavigator +import com.topjohnwu.magisk.core.R as CoreR + +private const val URL_INPUT_KEY = "url" + +/** + * The settings of the phone app that apply to a watch, shown under the same conditions. + * + * Left out on Wear: + * - Language: the app follows the system language of the watch. + * - Color mode: the Wear theme is always dark. + * - Download path and randomized output name: patched images stay in the Download folder, + * which is where the root file list of the Wear file picker looks. + * - Superuser authentication: the biometric prompt is not available in the Wear app. + * - Multiuser mode: Wear OS has no secondary users. + */ +@Composable +fun SettingsScreen(viewModel: SettingsViewModel, navigator: WearNavigator) { + val uiState by viewModel.uiState.collectAsStateWithLifecycle() + val enableCheckUpdate = rememberNotificationPermissionLauncher { + viewModel.setCheckUpdate(true) + } + + LifecycleResumeEffect(viewModel) { + viewModel.refreshEnvironment() + onPauseOrDispose {} + } + CollectNavEvents(viewModel, navigator) + + val state = rememberTransformingLazyColumnState() + ScreenScaffold(state) { contentPadding -> + TransformingLazyColumn(state = state, contentPadding = contentPadding) { + item { + ListHeader { Text(stringResource(CoreR.string.settings)) } + } + if (uiState.isMagiskInstalled) { + magiskItems(uiState, viewModel) + } + if (uiState.isSuperUserAvailable) { + superuserItems(uiState, viewModel) + } + item { + ListHeader { Text(stringResource(CoreR.string.wear_settings_updates)) } + } + item { + SwitchButton( + checked = uiState.checkUpdateEnabled, + // Update notifications need the notification permission + onCheckedChange = { enabled -> + if (enabled) enableCheckUpdate() else viewModel.setCheckUpdate(false) + }, + label = { Text(stringResource(CoreR.string.settings_check_update_title)) }, + modifier = Modifier.fillMaxWidth(), + ) + } + item { + ChannelPicker( + current = uiState.selectedUpdateChannelIndex, + onSelect = viewModel::setUpdateChannel, + ) + } + if (uiState.isCustomChannel) { + item { + val url = uiState.customChannelUrl + FilledTonalButton( + onClick = viewModel::openCustomChannelUrlDialog, + label = { Text(stringResource(CoreR.string.settings_update_custom)) }, + secondaryLabel = if (url.isNotBlank()) { + { Text(url, maxLines = 2) } + } else null, + modifier = Modifier.fillMaxWidth(), + ) + } + } + item { + SwitchButton( + checked = uiState.dohEnabled, + onCheckedChange = viewModel::setDoh, + label = { Text(stringResource(CoreR.string.settings_doh_title)) }, + modifier = Modifier.fillMaxWidth(), + ) + } + } + } + + CustomChannelUrlDialog( + dialog = uiState.activeDialog as? SettingsDialog.CustomChannelUrl, + onSave = viewModel::saveCustomChannelUrl, + onDismiss = viewModel::dismissDialog, + ) +} + +private fun TransformingLazyColumnScope.magiskItems( + uiState: SettingsUiState, + viewModel: SettingsViewModel, +) { + if (uiState.isZygiskSupported) { + item { + SwitchButton( + checked = uiState.zygiskEnabled, + onCheckedChange = viewModel::toggleZygisk, + label = { Text(stringResource(CoreR.string.zygisk)) }, + secondaryLabel = { + Text( + stringResource( + if (uiState.isZygiskPendingReboot) CoreR.string.reboot_apply_change + else CoreR.string.settings_zygisk_summary + ) + ) + }, + modifier = Modifier.fillMaxWidth(), + ) + } + item { + // The switch enforces the DenyList, the rest of the button opens it + SplitSwitchButton( + checked = uiState.denyListEnabled, + onCheckedChange = viewModel::toggleDenyList, + toggleContentDescription = stringResource(CoreR.string.settings_denylist_title), + onContainerClick = viewModel::navigateToDenyList, + label = { Text(stringResource(CoreR.string.denylist)) }, + secondaryLabel = { + Text(stringResource(CoreR.string.settings_denylist_config_title)) + }, + modifier = Modifier.fillMaxWidth(), + ) + } + } + item { + FilledTonalButton( + onClick = viewModel::createHosts, + label = { Text(stringResource(CoreR.string.settings_hosts_title)) }, + secondaryLabel = { Text(stringResource(CoreR.string.settings_hosts_summary)) }, + modifier = Modifier.fillMaxWidth(), + ) + } +} + +private fun TransformingLazyColumnScope.superuserItems( + uiState: SettingsUiState, + viewModel: SettingsViewModel, +) { + if (uiState.isSuRestrictSupported) { + item { + SwitchButton( + checked = uiState.suRestrictEnabled, + onCheckedChange = viewModel::setSuRestrict, + label = { Text(stringResource(CoreR.string.settings_su_restrict_title)) }, + // What new grants get + secondaryLabel = { + Text( + stringResource( + if (uiState.suRestrictEnabled) CoreR.string.wear_root_restricted + else CoreR.string.wear_root_full + ) + ) + }, + modifier = Modifier.fillMaxWidth(), + ) + } + } + item { + ChoicePicker( + title = stringResource(CoreR.string.superuser_notification), + items = stringArrayResource(CoreR.array.su_notification).asList(), + selected = uiState.selectedNotificationModeIndex, + onSelect = viewModel::setNotificationMode, + ) + } + item { + ChoicePicker( + title = stringResource(CoreR.string.mount_namespace_mode), + items = stringArrayResource(CoreR.array.namespace).asList(), + descriptions = stringArrayResource(CoreR.array.namespace_summary).asList(), + selected = uiState.selectedNamespaceModeIndex, + onSelect = viewModel::setNamespaceMode, + ) + } +} + +/** + * The update channel setting: shows [current] and lets the user pick another channel, which + * is passed to [onSelect]. Indices are those of the update_channel array (Config.updateChannel). + */ +@Composable +fun ChannelPicker(current: Int, onSelect: (Int) -> Unit) { + ChoicePicker( + title = stringResource(CoreR.string.settings_update_channel_title), + items = stringArrayResource(CoreR.array.update_channel).asList(), + selected = current, + onSelect = onSelect, + ) +} + +/** + * A setting with one of several values, the Wear counterpart of the phone app's dropdown: + * a button showing the selected item, which opens a list to pick from. + */ +@Composable +private fun ChoicePicker( + title: String, + items: List, + selected: Int, + onSelect: (Int) -> Unit, + descriptions: List? = null, +) { + var open by rememberSaveable { mutableStateOf(false) } + val selectedItem = items.getOrNull(selected) + + FilledTonalButton( + onClick = { open = true }, + label = { Text(title) }, + secondaryLabel = if (selectedItem != null) { + { Text(selectedItem) } + } else null, + modifier = Modifier.fillMaxWidth(), + ) + + Dialog(visible = open, onDismissRequest = { open = false }) { + val state = rememberTransformingLazyColumnState() + ScreenScaffold(state) { contentPadding -> + TransformingLazyColumn(state = state, contentPadding = contentPadding) { + item { + ListHeader { Text(title, textAlign = TextAlign.Center) } + } + items.forEachIndexed { index, choice -> + val description = descriptions?.getOrNull(index) + item(key = index) { + RadioButton( + selected = index == selected, + onSelect = { + open = false + if (index != selected) onSelect(index) + }, + label = { Text(choice) }, + secondaryLabel = if (description != null) { + { Text(description) } + } else null, + modifier = Modifier.fillMaxWidth(), + ) + } + } + } + } + } +} + +/** + * The custom channel URL dialog, shown while the view model asks for it, like the phone app. + * The URL is typed with the system keyboard of the watch through RemoteInput. + */ +@Composable +private fun CustomChannelUrlDialog( + dialog: SettingsDialog.CustomChannelUrl?, + onSave: (String) -> Unit, + onDismiss: () -> Unit, +) { + val context = LocalContext.current + var url by rememberSaveable { mutableStateOf("") } + // Whether url holds the text of the dialog being shown, so a recreated activity keeps + // what was typed instead of starting over from the saved URL + var editing by rememberSaveable { mutableStateOf(false) } + + LaunchedEffect(dialog) { + if (dialog == null) { + // Keep url, so the text stays while the dialog animates out + editing = false + } else if (!editing) { + url = dialog.initialUrl + editing = true + } + } + + // Same rule as the phone app: blank resets to no custom channel + val isValidUrl = url.isBlank() || ( + (url.startsWith("http://", ignoreCase = true) || + url.startsWith("https://", ignoreCase = true)) && + URLUtil.isValidUrl(url) + ) + + val keyboard = rememberLauncherForActivityResult( + ActivityResultContracts.StartActivityForResult() + ) { result -> + val text = result.data + ?.let { RemoteInput.getResultsFromIntent(it) } + ?.getCharSequence(URL_INPUT_KEY) + if (text != null) url = text.toString().trim() + } + val inputLabel = stringResource(CoreR.string.settings_update_custom_msg) + val openKeyboard: () -> Unit = { + val input = RemoteInput.Builder(URL_INPUT_KEY).setLabel(inputLabel).build() + val intent = RemoteInputIntentHelper.createActionRemoteInputIntent() + RemoteInputIntentHelper.putRemoteInputsExtra(intent, listOf(input)) + RemoteInputIntentHelper.putTitleExtra(intent, inputLabel) + // Every Wear OS device has a keyboard, but don't crash on one that doesn't + try { + keyboard.launch(intent) + } catch (e: ActivityNotFoundException) { + context.toast(CoreR.string.app_not_found, Toast.LENGTH_SHORT) + } + } + + AlertDialog( + visible = dialog != null, + onDismissRequest = onDismiss, + title = { Text(inputLabel) }, + text = { + Column( + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(4.dp), + modifier = Modifier.fillMaxWidth(), + ) { + if (url.isNotBlank()) { + Text( + text = url, + textAlign = TextAlign.Center, + color = if (isValidUrl) MaterialTheme.colorScheme.onSurface + else MaterialTheme.colorScheme.error, + ) + } + CompactButton( + onClick = openKeyboard, + icon = { Icon(Icons.Filled.Edit, contentDescription = inputLabel) }, + colors = ButtonDefaults.filledTonalButtonColors(), + ) + } + }, + confirmButton = { + AlertDialogDefaults.ConfirmButton(onClick = { + // An invalid URL stays shown in the error color until it is fixed + if (isValidUrl) { + onSave(url) + } else { + context.toast(CoreR.string.invalid_update_channel, Toast.LENGTH_SHORT) + } + }) + }, + dismissButton = { + AlertDialogDefaults.DismissButton(onClick = onDismiss) + }, + ) +} + +/** + * Returns a function that runs [onGranted] once the notification permission is granted, + * asking for it first when needed, like the phone app. + */ +@Composable +private fun rememberNotificationPermissionLauncher(onGranted: () -> Unit): () -> Unit { + val context = LocalContext.current + val currentOnGranted by rememberUpdatedState(onGranted) + + val launcher = rememberLauncherForActivityResult( + ActivityResultContracts.RequestPermission() + ) { granted -> + if (granted) { + currentOnGranted() + } else { + context.toast(CoreR.string.post_notifications_denied, Toast.LENGTH_SHORT) + } + } + + return remember(launcher, context) { + { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU || + ContextCompat.checkSelfPermission(context, POST_NOTIFICATIONS) == + PackageManager.PERMISSION_GRANTED + ) { + currentOnGranted() + } else { + launcher.launch(POST_NOTIFICATIONS) + } + } + } +} From 9f2f223011522679858b8363c70fb1ba994ef17a Mon Sep 17 00:00:00 2001 From: Jakub Mendyka Date: Fri, 27 Nov 2026 04:42:09 +0100 Subject: [PATCH 12/12] Run the app unit tests in CI The app modules now have JVM unit tests (:shared and :wear), but CI only assembles the APKs. Run testDebugUnitTest after the debug build, which already generated the files the build reads. Assisted-by: Claude Opus 5.5 --- .github/workflows/build.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 4989d640ecacf..035a1d672a273 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -35,6 +35,9 @@ jobs: - name: Build debug run: ./build.py -v all + - name: Run app unit tests + run: ./app/gradlew -p app testDebugUnitTest + - name: Stop gradle daemon run: ./app/gradlew --stop