app: implement UDF for settings and decouple auth

Refactor SettingsScreen and SettingsViewModel to adhere to modern
Unidirectional Data Flow (UDF) patterns. Hoist all preference
settings, environment visibility flags, and modal dialog states into an
immutable SettingsUiState collected via collectAsStateWithLifecycle.
Decompose SettingsScreen into a pure stateless SettingsContent
composable with configuration-resilient, validated dialogs.

Keep localized strings out of SettingsUiState and resolve them during
composition, so they follow per-app locale changes even though the
ViewModel outlives the recreated Activity. Refresh device security and
environment flags whenever the screen resumes.

Eliminate Activity memory leaks caused by passing ActivityExtension
lambdas into retained ViewModels. Introduce rememberBiometricAuth
scoped to Composable lifecycles using rememberLauncherForActivityResult
with RequestAuthentication contract. Remove authenticate callback
properties from SettingsViewModel, SuperuserViewModel, and
SuperuserGrantViewModel, and invoke biometric authentication at
call-time in the UI layer.

Assisted-by: Gemini 4 Argon
Assisted-by: Claude Opus 5.5
This commit is contained in:
topjohnwu
2026-10-24 13:01:45 -07:00
committed by John Wu
parent 1ae3cd9288
commit bb533df6e0
11 changed files with 616 additions and 328 deletions
@@ -138,9 +138,6 @@ class MainActivity : ComponentActivity(), SplashScreenHost {
MainScreen( MainScreen(
initialTab = initialTab, initialTab = initialTab,
superuserViewModel = superuserVm, superuserViewModel = superuserVm,
onAuthenticate = { action ->
extension.withAuthentication { if (it) action() }
}
) )
} }
entry<Route.DenyList> { _ -> entry<Route.DenyList> { _ ->
@@ -164,26 +161,15 @@ class MainActivity : ComponentActivity(), SplashScreenHost {
val vm: SuperuserViewModel = viewModel( val vm: SuperuserViewModel = viewModel(
viewModelStoreOwner = this@MainActivity, factory = VMFactory viewModelStoreOwner = this@MainActivity, factory = VMFactory
) )
LaunchedEffect(Unit) {
vm.authenticate = { onSuccess ->
extension.withAuthentication { if (it) onSuccess() }
}
}
SuperuserDetailScreen( SuperuserDetailScreen(
uid = key.uid, uid = key.uid,
viewModel = vm, viewModel = vm,
onBack = { navigator.pop() }, onBack = { navigator.pop() },
onAuthenticate = { action ->
extension.withAuthentication { if (it) action() }
}
) )
} }
entry<Route.SuperuserGrant> { _ -> entry<Route.SuperuserGrant> { _ ->
val vm: SuperuserGrantViewModel = viewModel(factory = VMFactory) val vm: SuperuserGrantViewModel = viewModel(factory = VMFactory)
LaunchedEffect(Unit) { LaunchedEffect(Unit) {
vm.authenticate = { onSuccess ->
extension.withAuthentication { if (it) onSuccess() }
}
vm.startLoading() vm.startLoading()
} }
SuperuserGrantScreen( SuperuserGrantScreen(
@@ -88,7 +88,6 @@ fun MainScreen(
modifier: Modifier = Modifier, modifier: Modifier = Modifier,
initialTab: Int = Tab.HOME.ordinal, initialTab: Int = Tab.HOME.ordinal,
superuserViewModel: SuperuserViewModel? = null, superuserViewModel: SuperuserViewModel? = null,
onAuthenticate: ((onSuccess: () -> Unit) -> Unit)? = null,
) { ) {
val navigator = LocalNavigator.current val navigator = LocalNavigator.current
val scope = rememberCoroutineScope() val scope = rememberCoroutineScope()
@@ -279,11 +278,6 @@ fun MainScreen(
} else { } else {
viewModel(factory = VMFactory) viewModel(factory = VMFactory)
} }
LaunchedEffect(onAuthenticate) {
if (onAuthenticate != null) {
vm.authenticate = onAuthenticate
}
}
LaunchedEffect(isCurrentPage) { LaunchedEffect(isCurrentPage) {
if (isCurrentPage) vm.startLoading() if (isCurrentPage) vm.startLoading()
} }
@@ -315,11 +309,6 @@ fun MainScreen(
} }
Tab.SETTINGS -> { Tab.SETTINGS -> {
val vm: SettingsViewModel = viewModel(factory = VMFactory) val vm: SettingsViewModel = viewModel(factory = VMFactory)
LaunchedEffect(onAuthenticate) {
if (onAuthenticate != null) {
vm.authenticate = onAuthenticate
}
}
CollectNavEvents(vm, navigator) CollectNavEvents(vm, navigator)
SettingsScreen(vm) SettingsScreen(vm)
} }
@@ -0,0 +1,51 @@
package com.topjohnwu.magisk.ui.component
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import com.topjohnwu.magisk.core.Config
import com.topjohnwu.magisk.core.Info
import com.topjohnwu.magisk.core.utils.RequestAuthentication
class BiometricAuth internal constructor(
private val launch: (force: Boolean, action: () -> Unit) -> Unit
) : ((() -> Unit) -> Unit) {
override fun invoke(action: () -> Unit) {
launch(false, action)
}
operator fun invoke(force: Boolean, action: () -> Unit) {
launch(force, action)
}
}
/**
* Returns a lifecycle-safe authenticator that prompts for biometric or device credentials
* (PIN, pattern, password) before executing sensitive actions.
*
* Scoped directly to the Composable lifecycle using [rememberLauncherForActivityResult],
* ensuring zero Activity references are leaked to ViewModels or retained singletons.
*/
@Composable
fun rememberBiometricAuth(): BiometricAuth {
var pendingAction by remember { mutableStateOf<(() -> Unit)?>(null) }
val launcher = rememberLauncherForActivityResult(RequestAuthentication()) { success ->
if (success) {
pendingAction?.invoke()
}
pendingAction = null
}
return remember(launcher) {
BiometricAuth { force, action ->
if ((force || Config.suAuth) && Info.isDeviceSecure) {
pendingAction = action
launcher.launch(Unit)
} else {
action()
}
}
}
}
@@ -1,6 +1,6 @@
package com.topjohnwu.magisk.ui.settings package com.topjohnwu.magisk.ui.settings
import android.os.Build import android.webkit.URLUtil
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.consumeWindowInsets import androidx.compose.foundation.layout.consumeWindowInsets
@@ -22,7 +22,6 @@ import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.saveable.rememberSaveable
@@ -30,17 +29,13 @@ import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.input.nestedscroll.nestedScroll import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalResources import androidx.compose.ui.res.stringArrayResource
import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.LifecycleResumeEffect
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.topjohnwu.magisk.core.Config
import com.topjohnwu.magisk.core.Const
import com.topjohnwu.magisk.core.Info
import com.topjohnwu.magisk.core.model.ColorMode
import com.topjohnwu.magisk.core.utils.LocaleSetting import com.topjohnwu.magisk.core.utils.LocaleSetting
import com.topjohnwu.magisk.core.utils.MediaStoreUtils import com.topjohnwu.magisk.core.utils.MediaStoreUtils
import com.topjohnwu.magisk.ui.ThemeState
import com.topjohnwu.magisk.ui.component.AdaptiveColumns import com.topjohnwu.magisk.ui.component.AdaptiveColumns
import com.topjohnwu.magisk.ui.component.MagiskDialog import com.topjohnwu.magisk.ui.component.MagiskDialog
import com.topjohnwu.magisk.ui.component.SettingsArrow import com.topjohnwu.magisk.ui.component.SettingsArrow
@@ -48,17 +43,87 @@ import com.topjohnwu.magisk.ui.component.SettingsDropdown
import com.topjohnwu.magisk.ui.component.SettingsSwitch import com.topjohnwu.magisk.ui.component.SettingsSwitch
import com.topjohnwu.magisk.ui.component.SmallTitle import com.topjohnwu.magisk.ui.component.SmallTitle
import com.topjohnwu.magisk.ui.component.onlyHorizontal import com.topjohnwu.magisk.ui.component.onlyHorizontal
import com.topjohnwu.magisk.ui.component.rememberBiometricAuth
import com.topjohnwu.magisk.ui.component.verticalScrollbar import com.topjohnwu.magisk.ui.component.verticalScrollbar
import com.topjohnwu.magisk.core.R as CoreR import com.topjohnwu.magisk.core.R as CoreR
@OptIn(ExperimentalMaterial3Api::class)
@Composable @Composable
fun SettingsScreen( fun SettingsScreen(
viewModel: SettingsViewModel, viewModel: SettingsViewModel,
modifier: Modifier = Modifier modifier: Modifier = Modifier,
) {
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
val context = LocalContext.current
val requireAuth = rememberBiometricAuth()
LifecycleResumeEffect(viewModel) {
viewModel.refreshEnvironment()
onPauseOrDispose {}
}
SettingsContent(
uiState = uiState,
onOpenSystemLocale = {
context.startActivity(LocaleSetting.localeSettingsIntent)
},
onLanguageSelected = viewModel::setLanguage,
onColorModeSelected = viewModel::setColorMode,
onUpdateChannelSelected = viewModel::setUpdateChannel,
onOpenCustomUrlDialog = viewModel::openCustomChannelUrlDialog,
onSaveCustomUrl = viewModel::saveCustomChannelUrl,
onToggleDoh = viewModel::setDoh,
onToggleCheckUpdate = viewModel::setCheckUpdate,
onOpenDownloadPathDialog = viewModel::openDownloadPathDialog,
onSaveDownloadPath = viewModel::saveDownloadPath,
onToggleRandomPackageName = viewModel::setRandomPackageName,
onCreateHosts = viewModel::createHosts,
onToggleZygisk = viewModel::toggleZygisk,
onToggleDenyList = viewModel::toggleDenyList,
onNavigateToDenyList = viewModel::navigateToDenyList,
onToggleSuAuth = { newValue ->
requireAuth(force = true) {
viewModel.setSuAuth(newValue)
}
},
onMultiuserModeSelected = viewModel::setMultiuserMode,
onNamespaceModeSelected = viewModel::setNamespaceMode,
onNotificationModeSelected = viewModel::setNotificationMode,
onToggleSuRestrict = viewModel::setSuRestrict,
onDismissDialog = viewModel::dismissDialog,
modifier = modifier,
)
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SettingsContent(
uiState: SettingsUiState,
onOpenSystemLocale: () -> Unit,
onLanguageSelected: (Int) -> Unit,
onColorModeSelected: (Int) -> Unit,
onUpdateChannelSelected: (Int) -> Unit,
onOpenCustomUrlDialog: () -> Unit,
onSaveCustomUrl: (String) -> Unit,
onToggleDoh: (Boolean) -> Unit,
onToggleCheckUpdate: (Boolean) -> Unit,
onOpenDownloadPathDialog: () -> Unit,
onSaveDownloadPath: (String) -> Unit,
onToggleRandomPackageName: (Boolean) -> Unit,
onCreateHosts: () -> Unit,
onToggleZygisk: (Boolean) -> Unit,
onToggleDenyList: (Boolean) -> Unit,
onNavigateToDenyList: () -> Unit,
onToggleSuAuth: (Boolean) -> Unit,
onMultiuserModeSelected: (Int) -> Unit,
onNamespaceModeSelected: (Int) -> Unit,
onNotificationModeSelected: (Int) -> Unit,
onToggleSuRestrict: (Boolean) -> Unit,
onDismissDialog: () -> Unit,
modifier: Modifier = Modifier,
) { ) {
val scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior() val scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior()
val scrollState = rememberScrollState() val scrollState = rememberScrollState()
Scaffold( Scaffold(
modifier = modifier, modifier = modifier,
topBar = { topBar = {
@@ -70,7 +135,6 @@ fun SettingsScreen(
) { padding -> ) { padding ->
// Without root, the Magisk and Superuser sections are hidden, so move the // Without root, the Magisk and Superuser sections are hidden, so move the
// App section to the second column to avoid leaving it empty. // App section to the second column to avoid leaving it empty.
val hasRootSections = Info.env.isActive || Info.showSuperUser
// Each section emits a title and a card, so wrap them in a Column to keep them together // Each section emits a title and a card, so wrap them in a Column to keep them together
AdaptiveColumns( AdaptiveColumns(
modifier = Modifier modifier = Modifier
@@ -94,65 +158,118 @@ fun SettingsScreen(
), ),
spacing = 16.dp, spacing = 16.dp,
first = { first = {
Column { CustomizationSection(viewModel = viewModel) } Column {
if (hasRootSections) { CustomizationSection(
Column { AppSettingsSection() } uiState = uiState,
onOpenSystemLocale = onOpenSystemLocale,
onLanguageSelected = onLanguageSelected,
onColorModeSelected = onColorModeSelected,
)
}
if (uiState.hasRootSections) {
Column {
AppSettingsSection(
uiState = uiState,
onUpdateChannelSelected = onUpdateChannelSelected,
onOpenCustomUrlDialog = onOpenCustomUrlDialog,
onToggleDoh = onToggleDoh,
onToggleCheckUpdate = onToggleCheckUpdate,
onOpenDownloadPathDialog = onOpenDownloadPathDialog,
onToggleRandomPackageName = onToggleRandomPackageName,
)
}
} }
}, },
second = { second = {
if (!hasRootSections) { if (!uiState.hasRootSections) {
Column { AppSettingsSection() } Column {
AppSettingsSection(
uiState = uiState,
onUpdateChannelSelected = onUpdateChannelSelected,
onOpenCustomUrlDialog = onOpenCustomUrlDialog,
onToggleDoh = onToggleDoh,
onToggleCheckUpdate = onToggleCheckUpdate,
onOpenDownloadPathDialog = onOpenDownloadPathDialog,
onToggleRandomPackageName = onToggleRandomPackageName,
)
}
} }
if (Info.env.isActive) { if (uiState.isMagiskInstalled) {
Column { MagiskSection(viewModel = viewModel) } Column {
MagiskSection(
uiState = uiState,
onCreateHosts = onCreateHosts,
onToggleZygisk = onToggleZygisk,
onToggleDenyList = onToggleDenyList,
onNavigateToDenyList = onNavigateToDenyList,
)
}
} }
if (Info.showSuperUser) { if (uiState.isSuperUserAvailable) {
Column { SuperuserSection(viewModel = viewModel) } Column {
SuperuserSection(
uiState = uiState,
onToggleSuAuth = onToggleSuAuth,
onMultiuserModeSelected = onMultiuserModeSelected,
onNamespaceModeSelected = onNamespaceModeSelected,
onNotificationModeSelected = onNotificationModeSelected,
onToggleSuRestrict = onToggleSuRestrict,
)
}
} }
}, },
) )
} }
when (val dialog = uiState.activeDialog) {
is SettingsDialog.CustomChannelUrl -> {
UpdateChannelUrlDialog(
initialUrl = dialog.initialUrl,
onConfirm = onSaveCustomUrl,
onDismiss = onDismissDialog,
)
}
is SettingsDialog.DownloadPath -> {
DownloadPathDialog(
initialPath = dialog.initialPath,
onConfirm = onSaveDownloadPath,
onDismiss = onDismissDialog,
)
}
null -> Unit
}
} }
// --- Customization --- // --- Customization ---
@Composable @Composable
private fun CustomizationSection( private fun CustomizationSection(
viewModel: SettingsViewModel, uiState: SettingsUiState,
onOpenSystemLocale: () -> Unit,
onLanguageSelected: (Int) -> Unit,
onColorModeSelected: (Int) -> Unit,
modifier: Modifier = Modifier modifier: Modifier = Modifier
) { ) {
val context = LocalContext.current
SmallTitle(text = stringResource(CoreR.string.settings_customization)) SmallTitle(text = stringResource(CoreR.string.settings_customization))
Card( Card(
modifier = modifier.fillMaxWidth(), modifier = modifier.fillMaxWidth(),
shape = RoundedCornerShape(20.dp), shape = RoundedCornerShape(20.dp),
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainerLow) colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainerLow)
) { ) {
if (LocaleSetting.useLocaleManager) { if (uiState.useLocaleManager) {
val locale = LocaleSetting.instance.appLocale val appLocale = LocaleSetting.instance.appLocale
val summary = locale?.getDisplayName(locale) ?: stringResource(CoreR.string.system_default)
SettingsArrow( SettingsArrow(
title = stringResource(CoreR.string.language), title = stringResource(CoreR.string.language),
summary = summary, summary = appLocale?.getDisplayName(appLocale)
onClick = { ?: stringResource(CoreR.string.system_default),
context.startActivity(LocaleSetting.localeSettingsIntent) onClick = onOpenSystemLocale
}
) )
} else { } else {
val names = remember { LocaleSetting.available.names }
val tags = remember { LocaleSetting.available.tags }
var selectedIndex by remember {
mutableIntStateOf(tags.indexOf(Config.locale).coerceAtLeast(0))
}
SettingsDropdown( SettingsDropdown(
title = stringResource(CoreR.string.language), title = stringResource(CoreR.string.language),
items = names.toList(), items = uiState.availableLanguages,
selectedIndex = selectedIndex, selectedIndex = uiState.selectedLanguageIndex,
onSelectedIndexChange = { index -> onSelectedIndexChange = onLanguageSelected
selectedIndex = index
Config.locale = tags[index]
}
) )
} }
@@ -162,31 +279,12 @@ private fun CustomizationSection(
) )
// Color Mode // Color Mode
val isDynamicColorSupported = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S val colorModes = stringArrayResource(CoreR.array.color_mode).asList()
val resources = LocalResources.current
val rawColorModeEntries = remember {
resources.getStringArray(CoreR.array.color_mode).toList()
}
val colorModeEntries = remember(isDynamicColorSupported) {
if (isDynamicColorSupported) {
rawColorModeEntries
} else {
rawColorModeEntries.drop(3)
}
}
var colorMode by remember { mutableIntStateOf(Config.colorMode) }
val selectedIndex = ColorMode.fromValue(colorMode).toUiIndex(isDynamicColorSupported)
SettingsDropdown( SettingsDropdown(
title = stringResource(CoreR.string.settings_color_mode), title = stringResource(CoreR.string.settings_color_mode),
items = colorModeEntries, items = if (uiState.isDynamicColorSupported) colorModes else colorModes.drop(3),
selectedIndex = selectedIndex, selectedIndex = uiState.selectedColorModeIndex,
onSelectedIndexChange = { index -> onSelectedIndexChange = onColorModeSelected
val newMode = ColorMode.fromUiIndex(index, isDynamicColorSupported)
colorMode = newMode.value
Config.colorMode = newMode.value
ThemeState.colorMode = newMode.value
}
) )
} }
} }
@@ -195,10 +293,15 @@ private fun CustomizationSection(
@Composable @Composable
private fun AppSettingsSection( private fun AppSettingsSection(
uiState: SettingsUiState,
onUpdateChannelSelected: (Int) -> Unit,
onOpenCustomUrlDialog: () -> Unit,
onToggleDoh: (Boolean) -> Unit,
onToggleCheckUpdate: (Boolean) -> Unit,
onOpenDownloadPathDialog: () -> Unit,
onToggleRandomPackageName: (Boolean) -> Unit,
modifier: Modifier = Modifier modifier: Modifier = Modifier
) { ) {
val resources = LocalResources.current
SmallTitle(text = stringResource(CoreR.string.home_app_title)) SmallTitle(text = stringResource(CoreR.string.home_app_title))
Card( Card(
modifier = modifier.fillMaxWidth(), modifier = modifier.fillMaxWidth(),
@@ -206,43 +309,23 @@ private fun AppSettingsSection(
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainerLow) colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainerLow)
) { ) {
// Update Channel // Update Channel
val updateChannelEntries = remember {
resources.getStringArray(CoreR.array.update_channel).toList()
}
var updateChannel by remember {
mutableIntStateOf(Config.updateChannelIndex)
}
var showUrlDialog by remember { mutableStateOf(false) }
SettingsDropdown( SettingsDropdown(
title = stringResource(CoreR.string.settings_update_channel_title), title = stringResource(CoreR.string.settings_update_channel_title),
items = updateChannelEntries, items = stringArrayResource(CoreR.array.update_channel).asList(),
selectedIndex = updateChannel, selectedIndex = uiState.selectedUpdateChannelIndex,
onSelectedIndexChange = { index -> onSelectedIndexChange = onUpdateChannelSelected
updateChannel = index
Config.updateChannel = index
Info.resetUpdate()
if (index == Config.Value.CUSTOM_CHANNEL && Config.customChannelUrl.isBlank()) {
showUrlDialog = true
}
}
) )
// Update Channel URL (for custom channel) // Update Channel URL (for custom channel)
if (updateChannel == Config.Value.CUSTOM_CHANNEL) { if (uiState.isCustomChannel) {
HorizontalDivider( HorizontalDivider(
modifier = Modifier.padding(horizontal = 16.dp), modifier = Modifier.padding(horizontal = 16.dp),
color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f) color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f)
) )
if (showUrlDialog) {
UpdateChannelUrlDialog(
onDismiss = { showUrlDialog = false }
)
}
SettingsArrow( SettingsArrow(
title = stringResource(CoreR.string.settings_update_custom), title = stringResource(CoreR.string.settings_update_custom),
summary = Config.customChannelUrl.ifBlank { null }, summary = uiState.customChannelUrl.ifBlank { null },
onClick = { showUrlDialog = true } onClick = onOpenCustomUrlDialog
) )
} }
@@ -252,15 +335,11 @@ private fun AppSettingsSection(
) )
// DoH Toggle // DoH Toggle
var doh by remember { mutableStateOf(Config.doh) }
SettingsSwitch( SettingsSwitch(
title = stringResource(CoreR.string.settings_doh_title), title = stringResource(CoreR.string.settings_doh_title),
summary = stringResource(CoreR.string.settings_doh_description), summary = stringResource(CoreR.string.settings_doh_description),
checked = doh, checked = uiState.dohEnabled,
onCheckedChange = { onCheckedChange = onToggleDoh
doh = it
Config.doh = it
}
) )
HorizontalDivider( HorizontalDivider(
@@ -269,15 +348,11 @@ private fun AppSettingsSection(
) )
// Update Checker // Update Checker
var checkUpdate by remember { mutableStateOf(Config.checkUpdate) }
SettingsSwitch( SettingsSwitch(
title = stringResource(CoreR.string.settings_check_update_title), title = stringResource(CoreR.string.settings_check_update_title),
summary = stringResource(CoreR.string.settings_check_update_summary), summary = stringResource(CoreR.string.settings_check_update_summary),
checked = checkUpdate, checked = uiState.checkUpdateEnabled,
onCheckedChange = { newValue -> onCheckedChange = onToggleCheckUpdate
checkUpdate = newValue
Config.checkUpdate = newValue
}
) )
HorizontalDivider( HorizontalDivider(
@@ -286,18 +361,10 @@ private fun AppSettingsSection(
) )
// Download Path // Download Path
var showDownloadDialog by remember { mutableStateOf(false) }
if (showDownloadDialog) {
DownloadPathDialog(
onDismiss = { showDownloadDialog = false }
)
}
SettingsArrow( SettingsArrow(
title = stringResource(CoreR.string.settings_download_path_title), title = stringResource(CoreR.string.settings_download_path_title),
summary = MediaStoreUtils.fullPath(Config.downloadDir), summary = uiState.downloadPathDisplay,
onClick = { onClick = onOpenDownloadPathDialog
showDownloadDialog = true
}
) )
HorizontalDivider( HorizontalDivider(
@@ -306,15 +373,11 @@ private fun AppSettingsSection(
) )
// Random Package Name // Random Package Name
var randName by remember { mutableStateOf(Config.randName) }
SettingsSwitch( SettingsSwitch(
title = stringResource(CoreR.string.settings_random_name_title), title = stringResource(CoreR.string.settings_random_name_title),
summary = stringResource(CoreR.string.settings_random_name_description), summary = stringResource(CoreR.string.settings_random_name_description),
checked = randName, checked = uiState.randomPackageNameEnabled,
onCheckedChange = { onCheckedChange = onToggleRandomPackageName
randName = it
Config.randName = it
}
) )
} }
} }
@@ -323,7 +386,11 @@ private fun AppSettingsSection(
@Composable @Composable
private fun MagiskSection( private fun MagiskSection(
viewModel: SettingsViewModel, uiState: SettingsUiState,
onCreateHosts: () -> Unit,
onToggleZygisk: (Boolean) -> Unit,
onToggleDenyList: (Boolean) -> Unit,
onNavigateToDenyList: () -> Unit,
modifier: Modifier = Modifier modifier: Modifier = Modifier
) { ) {
SmallTitle(text = stringResource(CoreR.string.magisk)) SmallTitle(text = stringResource(CoreR.string.magisk))
@@ -336,29 +403,24 @@ private fun MagiskSection(
SettingsArrow( SettingsArrow(
title = stringResource(CoreR.string.settings_hosts_title), title = stringResource(CoreR.string.settings_hosts_title),
summary = stringResource(CoreR.string.settings_hosts_summary), summary = stringResource(CoreR.string.settings_hosts_summary),
onClick = { viewModel.createHosts() } onClick = onCreateHosts
) )
if (Const.Version.atLeast_24_0()) { if (uiState.isZygiskSupported) {
HorizontalDivider( HorizontalDivider(
modifier = Modifier.padding(horizontal = 16.dp), modifier = Modifier.padding(horizontal = 16.dp),
color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f) color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f)
) )
// Zygisk // Zygisk
var zygisk by remember { mutableStateOf(Config.zygisk) }
SettingsSwitch( SettingsSwitch(
title = stringResource(CoreR.string.zygisk), title = stringResource(CoreR.string.zygisk),
summary = stringResource( summary = stringResource(
if (zygisk != Info.isZygiskEnabled) CoreR.string.reboot_apply_change if (uiState.isZygiskPendingReboot) CoreR.string.reboot_apply_change
else CoreR.string.settings_zygisk_summary else CoreR.string.settings_zygisk_summary
), ),
checked = zygisk, checked = uiState.zygiskEnabled,
onCheckedChange = { onCheckedChange = onToggleZygisk
zygisk = it
Config.zygisk = it
viewModel.notifyZygiskChange()
}
) )
HorizontalDivider( HorizontalDivider(
@@ -367,12 +429,11 @@ private fun MagiskSection(
) )
// DenyList // DenyList
val denyListEnabled by viewModel.denyListEnabled.collectAsStateWithLifecycle()
SettingsSwitch( SettingsSwitch(
title = stringResource(CoreR.string.settings_denylist_title), title = stringResource(CoreR.string.settings_denylist_title),
summary = stringResource(CoreR.string.settings_denylist_summary), summary = stringResource(CoreR.string.settings_denylist_summary),
checked = denyListEnabled, checked = uiState.denyListEnabled,
onCheckedChange = { viewModel.toggleDenyList(it) } onCheckedChange = onToggleDenyList
) )
HorizontalDivider( HorizontalDivider(
@@ -384,7 +445,7 @@ private fun MagiskSection(
SettingsArrow( SettingsArrow(
title = stringResource(CoreR.string.settings_denylist_config_title), title = stringResource(CoreR.string.settings_denylist_config_title),
summary = stringResource(CoreR.string.settings_denylist_config_summary), summary = stringResource(CoreR.string.settings_denylist_config_summary),
onClick = { viewModel.navigateToDenyList() } onClick = onNavigateToDenyList
) )
} }
} }
@@ -394,86 +455,63 @@ private fun MagiskSection(
@Composable @Composable
private fun SuperuserSection( private fun SuperuserSection(
viewModel: SettingsViewModel, uiState: SettingsUiState,
onToggleSuAuth: (Boolean) -> Unit,
onMultiuserModeSelected: (Int) -> Unit,
onNamespaceModeSelected: (Int) -> Unit,
onNotificationModeSelected: (Int) -> Unit,
onToggleSuRestrict: (Boolean) -> Unit,
modifier: Modifier = Modifier modifier: Modifier = Modifier
) { ) {
val resources = LocalResources.current
SmallTitle(text = stringResource(CoreR.string.superuser)) SmallTitle(text = stringResource(CoreR.string.superuser))
Card( Card(
modifier = modifier.fillMaxWidth(), modifier = modifier.fillMaxWidth(),
shape = RoundedCornerShape(20.dp), shape = RoundedCornerShape(20.dp),
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainerLow) colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainerLow)
) { ) {
// Authentication // Authentication
var suAuth by remember { mutableStateOf(Config.suAuth) }
SettingsSwitch( SettingsSwitch(
title = stringResource(CoreR.string.settings_su_auth_title), title = stringResource(CoreR.string.settings_su_auth_title),
summary = stringResource( summary = stringResource(
if (Info.isDeviceSecure) CoreR.string.settings_su_auth_summary if (uiState.isDeviceSecure) CoreR.string.settings_su_auth_summary
else CoreR.string.settings_su_auth_insecure else CoreR.string.settings_su_auth_insecure
), ),
checked = suAuth, checked = uiState.suAuthEnabled,
enabled = Info.isDeviceSecure, enabled = uiState.isDeviceSecure,
onCheckedChange = { newValue -> onCheckedChange = onToggleSuAuth
viewModel.withAuth {
suAuth = newValue
Config.suAuth = newValue
}
}
) )
if (uiState.isMultiuserSupported) {
HorizontalDivider(
modifier = Modifier.padding(horizontal = 16.dp),
color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f)
)
// Multiuser Mode
val multiuserSummaries = stringArrayResource(CoreR.array.multiuser_summary)
SettingsDropdown(
title = stringResource(CoreR.string.multiuser_mode),
summary = multiuserSummaries.getOrElse(uiState.selectedMultiuserModeIndex) { "" },
items = stringArrayResource(CoreR.array.multiuser_mode).asList(),
selectedIndex = uiState.selectedMultiuserModeIndex,
enabled = uiState.isMultiuserEditable,
onSelectedIndexChange = onMultiuserModeSelected
)
}
HorizontalDivider( HorizontalDivider(
modifier = Modifier.padding(horizontal = 16.dp), modifier = Modifier.padding(horizontal = 16.dp),
color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f) color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f)
) )
if (!Info.isHeadlessSystemUser) {
// Multiuser Mode
val multiuserEntries = remember {
resources.getStringArray(CoreR.array.multiuser_mode).toList()
}
val multiuserDescriptions = remember {
resources.getStringArray(CoreR.array.multiuser_summary).toList()
}
var multiuserMode by remember { mutableIntStateOf(Config.suMultiuserMode) }
SettingsDropdown(
title = stringResource(CoreR.string.multiuser_mode),
summary = multiuserDescriptions.getOrElse(multiuserMode) { "" },
items = multiuserEntries,
selectedIndex = multiuserMode,
enabled = Const.USER_ID == 0,
onSelectedIndexChange = {
multiuserMode = it
Config.suMultiuserMode = it
}
)
HorizontalDivider(
modifier = Modifier.padding(horizontal = 16.dp),
color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f)
)
}
// Mount Namespace Mode // Mount Namespace Mode
val namespaceEntries = remember { val namespaceSummaries = stringArrayResource(CoreR.array.namespace_summary)
resources.getStringArray(CoreR.array.namespace).toList()
}
val namespaceDescriptions = remember {
resources.getStringArray(CoreR.array.namespace_summary).toList()
}
var mntNamespaceMode by remember { mutableIntStateOf(Config.suMntNamespaceMode) }
SettingsDropdown( SettingsDropdown(
title = stringResource(CoreR.string.mount_namespace_mode), title = stringResource(CoreR.string.mount_namespace_mode),
summary = namespaceDescriptions.getOrElse(mntNamespaceMode) { "" }, summary = namespaceSummaries.getOrElse(uiState.selectedNamespaceModeIndex) { "" },
items = namespaceEntries, items = stringArrayResource(CoreR.array.namespace).asList(),
selectedIndex = mntNamespaceMode, selectedIndex = uiState.selectedNamespaceModeIndex,
onSelectedIndexChange = { onSelectedIndexChange = onNamespaceModeSelected
mntNamespaceMode = it
Config.suMntNamespaceMode = it
}
) )
HorizontalDivider( HorizontalDivider(
@@ -482,36 +520,24 @@ private fun SuperuserSection(
) )
// SU Notification // SU Notification
val notifEntries = remember {
resources.getStringArray(CoreR.array.su_notification).toList()
}
var suNotification by remember { mutableIntStateOf(Config.suNotification) }
SettingsDropdown( SettingsDropdown(
title = stringResource(CoreR.string.superuser_notification), title = stringResource(CoreR.string.superuser_notification),
items = notifEntries, items = stringArrayResource(CoreR.array.su_notification).asList(),
selectedIndex = suNotification, selectedIndex = uiState.selectedNotificationModeIndex,
onSelectedIndexChange = { onSelectedIndexChange = onNotificationModeSelected
suNotification = it
Config.suNotification = it
}
) )
// Restrict (version >= 30.1) // Restrict (version >= 30.1)
if (Const.Version.atLeast_30_1()) { if (uiState.isSuRestrictSupported) {
HorizontalDivider( HorizontalDivider(
modifier = Modifier.padding(horizontal = 16.dp), modifier = Modifier.padding(horizontal = 16.dp),
color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f) color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f)
) )
var restrict by remember { mutableStateOf(Config.suRestrict) }
SettingsSwitch( SettingsSwitch(
title = stringResource(CoreR.string.settings_su_restrict_title), title = stringResource(CoreR.string.settings_su_restrict_title),
summary = stringResource(CoreR.string.settings_su_restrict_summary), summary = stringResource(CoreR.string.settings_su_restrict_summary),
checked = restrict, checked = uiState.suRestrictEnabled,
onCheckedChange = { onCheckedChange = onToggleSuRestrict
restrict = it
Config.suRestrict = it
}
) )
} }
} }
@@ -521,20 +547,29 @@ private fun SuperuserSection(
@Composable @Composable
private fun UpdateChannelUrlDialog( private fun UpdateChannelUrlDialog(
initialUrl: String,
onConfirm: (String) -> Unit,
onDismiss: () -> Unit, onDismiss: () -> Unit,
modifier: Modifier = Modifier modifier: Modifier = Modifier
) { ) {
var url by rememberSaveable { mutableStateOf(Config.customChannelUrl) } var url by rememberSaveable(initialUrl) { mutableStateOf(initialUrl) }
val isValidUrl = remember(url) {
url.isBlank() || (
(url.startsWith("http://", ignoreCase = true) || url.startsWith("https://", ignoreCase = true)) &&
URLUtil.isValidUrl(url)
)
}
MagiskDialog( MagiskDialog(
modifier = modifier, modifier = modifier,
onDismissRequest = onDismiss, onDismissRequest = onDismiss,
title = stringResource(CoreR.string.settings_update_custom_msg), title = stringResource(CoreR.string.settings_update_custom_msg),
confirmText = stringResource(android.R.string.ok), confirmText = stringResource(android.R.string.ok),
confirmEnabled = isValidUrl,
onConfirm = { onConfirm = {
Config.customChannelUrl = url if (isValidUrl) {
Info.resetUpdate() onConfirm(url)
onDismiss() }
}, },
dismissText = stringResource(android.R.string.cancel), dismissText = stringResource(android.R.string.cancel),
onDismiss = onDismiss, onDismiss = onDismiss,
@@ -544,6 +579,7 @@ private fun UpdateChannelUrlDialog(
OutlinedTextField( OutlinedTextField(
value = url, value = url,
onValueChange = { url = it }, onValueChange = { url = it },
isError = !isValidUrl,
shape = RoundedCornerShape(12.dp), shape = RoundedCornerShape(12.dp),
modifier = Modifier.fillMaxWidth() modifier = Modifier.fillMaxWidth()
) )
@@ -553,10 +589,12 @@ private fun UpdateChannelUrlDialog(
@Composable @Composable
private fun DownloadPathDialog( private fun DownloadPathDialog(
initialPath: String,
onConfirm: (String) -> Unit,
onDismiss: () -> Unit, onDismiss: () -> Unit,
modifier: Modifier = Modifier modifier: Modifier = Modifier
) { ) {
var path by rememberSaveable { mutableStateOf(Config.downloadDir) } var path by rememberSaveable(initialPath) { mutableStateOf(initialPath) }
MagiskDialog( MagiskDialog(
modifier = modifier, modifier = modifier,
@@ -564,8 +602,7 @@ private fun DownloadPathDialog(
title = stringResource(CoreR.string.settings_download_path_title), title = stringResource(CoreR.string.settings_download_path_title),
confirmText = stringResource(android.R.string.ok), confirmText = stringResource(android.R.string.ok),
onConfirm = { onConfirm = {
Config.downloadDir = path onConfirm(path.trim())
onDismiss()
}, },
dismissText = stringResource(android.R.string.cancel), dismissText = stringResource(android.R.string.cancel),
onDismiss = onDismiss, onDismiss = onDismiss,
@@ -0,0 +1,54 @@
package com.topjohnwu.magisk.ui.settings
import androidx.compose.runtime.Immutable
sealed interface SettingsDialog {
data class CustomChannelUrl(val initialUrl: String) : SettingsDialog
data class DownloadPath(val initialPath: String) : SettingsDialog
}
@Immutable
data class SettingsUiState(
// Environment & Section Visibility flags
val hasRootSections: Boolean = false,
val isMagiskInstalled: Boolean = false,
val isSuperUserAvailable: Boolean = false,
val isZygiskSupported: Boolean = false,
val isSuRestrictSupported: Boolean = false,
val isMultiuserSupported: Boolean = false,
val isMultiuserEditable: Boolean = false,
val isDeviceSecure: Boolean = false,
val useLocaleManager: Boolean = false,
// Customization Section
val availableLanguages: List<String> = emptyList(),
val availableLanguageTags: List<String> = emptyList(),
val selectedLanguageIndex: Int = 0,
val selectedColorModeIndex: Int = 0,
val isDynamicColorSupported: Boolean = false,
// App Settings Section
val selectedUpdateChannelIndex: Int = 0,
val isCustomChannel: Boolean = false,
val customChannelUrl: String = "",
val dohEnabled: Boolean = false,
val checkUpdateEnabled: Boolean = true,
val downloadPath: String = "",
val downloadPathDisplay: String = "",
val randomPackageNameEnabled: Boolean = true,
// Magisk Section
val zygiskEnabled: Boolean = false,
val isZygiskPendingReboot: Boolean = false,
val denyListEnabled: Boolean = false,
// Superuser Section
val suAuthEnabled: Boolean = false,
val selectedMultiuserModeIndex: Int = 0,
val selectedNamespaceModeIndex: Int = 0,
val selectedNotificationModeIndex: Int = 0,
val suRestrictEnabled: Boolean = false,
// Active Modal Dialog
val activeDialog: SettingsDialog? = null,
)
@@ -1,56 +1,234 @@
package com.topjohnwu.magisk.ui.settings package com.topjohnwu.magisk.ui.settings
import android.os.Build
import android.widget.Toast import android.widget.Toast
import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewModelScope
import com.topjohnwu.magisk.arch.BaseViewModel import com.topjohnwu.magisk.arch.BaseViewModel
import com.topjohnwu.magisk.core.AppContext import com.topjohnwu.magisk.core.AppContext
import com.topjohnwu.magisk.core.Config import com.topjohnwu.magisk.core.Config
import com.topjohnwu.magisk.core.Const
import com.topjohnwu.magisk.core.Info import com.topjohnwu.magisk.core.Info
import com.topjohnwu.magisk.core.R import com.topjohnwu.magisk.core.R as CoreR
import com.topjohnwu.magisk.core.ktx.toast import com.topjohnwu.magisk.core.ktx.toast
import com.topjohnwu.magisk.core.model.ColorMode
import com.topjohnwu.magisk.core.utils.LocaleSetting
import com.topjohnwu.magisk.core.utils.MediaStoreUtils
import com.topjohnwu.magisk.core.utils.RootUtils import com.topjohnwu.magisk.core.utils.RootUtils
import com.topjohnwu.magisk.ui.ThemeState
import com.topjohnwu.magisk.ui.navigation.Route import com.topjohnwu.magisk.ui.navigation.Route
import com.topjohnwu.superuser.Shell import com.topjohnwu.superuser.Shell
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
class SettingsViewModel : BaseViewModel() { class SettingsViewModel : BaseViewModel() {
private val _denyListEnabled = MutableStateFlow(Config.denyList) private val _uiState = MutableStateFlow(buildInitialState())
val denyListEnabled: StateFlow<Boolean> = _denyListEnabled.asStateFlow() val uiState: StateFlow<SettingsUiState> = _uiState.asStateFlow()
val zygiskMismatch get() = Config.zygisk != Info.isZygiskEnabled private fun buildInitialState(): SettingsUiState {
val isDynamicColorSupported = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S
val selectedColorIndex = ColorMode.fromValue(Config.colorMode).toUiIndex(isDynamicColorSupported)
var authenticate: (onSuccess: () -> Unit) -> Unit = { it() } val localeTags = LocaleSetting.available.tags.toList()
val localeNames = LocaleSetting.available.names.toList()
val selectedLocaleIndex = localeTags.indexOf(Config.locale).coerceAtLeast(0)
fun navigateToDenyList() { val updateIndex = Config.updateChannelIndex
navigateTo(Route.DenyList) val isCustomChannel = updateIndex == Config.Value.CUSTOM_CHANNEL
return SettingsUiState(
isZygiskSupported = Const.Version.atLeast_24_0(),
isSuRestrictSupported = Const.Version.atLeast_30_1(),
isMultiuserSupported = !Info.isHeadlessSystemUser,
isMultiuserEditable = Const.USER_ID == 0,
useLocaleManager = LocaleSetting.useLocaleManager,
availableLanguages = localeNames,
availableLanguageTags = localeTags,
selectedLanguageIndex = selectedLocaleIndex,
selectedColorModeIndex = selectedColorIndex,
isDynamicColorSupported = isDynamicColorSupported,
selectedUpdateChannelIndex = updateIndex,
isCustomChannel = isCustomChannel,
customChannelUrl = Config.customChannelUrl,
dohEnabled = Config.doh,
checkUpdateEnabled = Config.checkUpdate,
downloadPath = Config.downloadDir,
downloadPathDisplay = MediaStoreUtils.fullPath(Config.downloadDir),
randomPackageNameEnabled = Config.randName,
zygiskEnabled = Config.zygisk,
isZygiskPendingReboot = Config.zygisk != Info.isZygiskEnabled,
denyListEnabled = Config.denyList,
selectedMultiuserModeIndex = Config.suMultiuserMode,
selectedNamespaceModeIndex = Config.suMntNamespaceMode,
selectedNotificationModeIndex = Config.suNotification,
suRestrictEnabled = Config.suRestrict,
).withEnvironment()
}
// Device and environment state that can change while the app is in the background
private fun SettingsUiState.withEnvironment(): SettingsUiState {
val isMagiskInstalled = Info.env.isActive
val isSuperUserAvailable = Info.showSuperUser
return copy(
hasRootSections = isMagiskInstalled || isSuperUserAvailable,
isMagiskInstalled = isMagiskInstalled,
isSuperUserAvailable = isSuperUserAvailable,
isDeviceSecure = Info.isDeviceSecure,
// Config.suAuth also depends on whether the device is secure
suAuthEnabled = Config.suAuth,
)
}
fun refreshEnvironment() {
_uiState.update { it.withEnvironment() }
}
fun setColorMode(index: Int) {
val newMode = ColorMode.fromUiIndex(index, _uiState.value.isDynamicColorSupported)
Config.colorMode = newMode.value
ThemeState.colorMode = newMode.value
_uiState.update { it.copy(selectedColorModeIndex = index) }
}
fun setLanguage(index: Int) {
val tag = _uiState.value.availableLanguageTags.getOrNull(index) ?: return
Config.locale = tag
_uiState.update { it.copy(selectedLanguageIndex = index) }
}
fun setUpdateChannel(index: Int) {
Config.updateChannel = index
Info.resetUpdate()
val isCustom = index == Config.Value.CUSTOM_CHANNEL
val showUrlDialog = isCustom && Config.customChannelUrl.isBlank()
_uiState.update {
it.copy(
selectedUpdateChannelIndex = index,
isCustomChannel = isCustom,
activeDialog = if (showUrlDialog) SettingsDialog.CustomChannelUrl("") else it.activeDialog,
)
}
}
fun openCustomChannelUrlDialog() {
_uiState.update {
it.copy(activeDialog = SettingsDialog.CustomChannelUrl(it.customChannelUrl))
}
}
fun saveCustomChannelUrl(url: String) {
Config.customChannelUrl = url
Info.resetUpdate()
_uiState.update {
it.copy(
customChannelUrl = url,
activeDialog = null,
)
}
}
fun setDoh(enabled: Boolean) {
Config.doh = enabled
_uiState.update { it.copy(dohEnabled = enabled) }
}
fun setCheckUpdate(enabled: Boolean) {
Config.checkUpdate = enabled
_uiState.update { it.copy(checkUpdateEnabled = enabled) }
}
fun openDownloadPathDialog() {
_uiState.update {
it.copy(activeDialog = SettingsDialog.DownloadPath(it.downloadPath))
}
}
fun saveDownloadPath(path: String) {
Config.downloadDir = path
_uiState.update {
it.copy(
downloadPath = path,
downloadPathDisplay = MediaStoreUtils.fullPath(path),
activeDialog = null,
)
}
}
fun setRandomPackageName(enabled: Boolean) {
Config.randName = enabled
_uiState.update { it.copy(randomPackageNameEnabled = enabled) }
} }
fun createHosts() { fun createHosts() {
viewModelScope.launch { viewModelScope.launch {
RootUtils.addSystemlessHosts() RootUtils.addSystemlessHosts()
AppContext.toast(R.string.settings_hosts_toast, Toast.LENGTH_SHORT) AppContext.toast(CoreR.string.settings_hosts_toast, Toast.LENGTH_SHORT)
}
}
fun toggleZygisk(enabled: Boolean) {
Config.zygisk = enabled
val isMismatch = enabled != Info.isZygiskEnabled
_uiState.update {
it.copy(
zygiskEnabled = enabled,
isZygiskPendingReboot = isMismatch,
)
}
if (isMismatch) {
showSnackbar(CoreR.string.reboot_apply_change)
} }
} }
fun toggleDenyList(enabled: Boolean) { fun toggleDenyList(enabled: Boolean) {
_denyListEnabled.value = enabled _uiState.update { it.copy(denyListEnabled = enabled) }
val cmd = if (enabled) "enable" else "disable" val cmd = if (enabled) "enable" else "disable"
Shell.cmd("magisk --denylist $cmd").submit { result -> Shell.cmd("magisk --denylist $cmd").submit { result ->
if (result.isSuccess) { if (result.isSuccess) {
Config.denyList = enabled Config.denyList = enabled
} else { } else {
_denyListEnabled.value = !enabled _uiState.update { it.copy(denyListEnabled = !enabled) }
} }
} }
} }
fun withAuth(action: () -> Unit) = authenticate(action) fun navigateToDenyList() {
navigateTo(Route.DenyList)
}
fun notifyZygiskChange() { fun setSuAuth(enabled: Boolean) {
if (zygiskMismatch) showSnackbar(R.string.reboot_apply_change) Config.suAuth = enabled
_uiState.update { it.copy(suAuthEnabled = enabled) }
}
fun setMultiuserMode(index: Int) {
Config.suMultiuserMode = index
_uiState.update { it.copy(selectedMultiuserModeIndex = index) }
}
fun setNamespaceMode(index: Int) {
Config.suMntNamespaceMode = index
_uiState.update { it.copy(selectedNamespaceModeIndex = index) }
}
fun setNotificationMode(index: Int) {
Config.suNotification = index
_uiState.update { it.copy(selectedNotificationModeIndex = index) }
}
fun setSuRestrict(enabled: Boolean) {
Config.suRestrict = enabled
_uiState.update { it.copy(suRestrictEnabled = enabled) }
}
fun dismissDialog() {
_uiState.update { it.copy(activeDialog = null) }
} }
} }
@@ -46,8 +46,10 @@ import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.google.accompanist.drawablepainter.rememberDrawablePainter import com.google.accompanist.drawablepainter.rememberDrawablePainter
import com.topjohnwu.magisk.core.Config
import com.topjohnwu.magisk.ui.component.ConfirmResult import com.topjohnwu.magisk.ui.component.ConfirmResult
import com.topjohnwu.magisk.ui.component.SettingsSwitch import com.topjohnwu.magisk.ui.component.SettingsSwitch
import com.topjohnwu.magisk.ui.component.rememberBiometricAuth
import com.topjohnwu.magisk.ui.component.rememberConfirmDialog import com.topjohnwu.magisk.ui.component.rememberConfirmDialog
import com.topjohnwu.magisk.ui.component.verticalScrollbar import com.topjohnwu.magisk.ui.component.verticalScrollbar
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
@@ -60,7 +62,6 @@ fun SuperuserDetailScreen(
viewModel: SuperuserViewModel, viewModel: SuperuserViewModel,
onBack: () -> Unit, onBack: () -> Unit,
modifier: Modifier = Modifier, modifier: Modifier = Modifier,
onAuthenticate: ((onSuccess: () -> Unit) -> Unit)? = null,
) { ) {
val uiState by viewModel.uiState.collectAsStateWithLifecycle() val uiState by viewModel.uiState.collectAsStateWithLifecycle()
val items = uiState.policies.filter { it.policy.uid == uid } val items = uiState.policies.filter { it.policy.uid == uid }
@@ -68,6 +69,7 @@ fun SuperuserDetailScreen(
val scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior() val scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior()
val scrollState = rememberScrollState() val scrollState = rememberScrollState()
val scope = rememberCoroutineScope() val scope = rememberCoroutineScope()
val requireAuth = rememberBiometricAuth()
val revokeDialog = rememberConfirmDialog() val revokeDialog = rememberConfirmDialog()
val revokeTitle = stringResource(CoreR.string.su_revoke_title) val revokeTitle = stringResource(CoreR.string.su_revoke_title)
val revokeMsg = item?.let { stringResource(CoreR.string.su_revoke_msg, it.appName) } ?: "" val revokeMsg = item?.let { stringResource(CoreR.string.su_revoke_msg, it.appName) } ?: ""
@@ -78,11 +80,6 @@ fun SuperuserDetailScreen(
viewModel.startLoading() viewModel.startLoading()
} }
} }
LaunchedEffect(onAuthenticate) {
if (onAuthenticate != null) {
viewModel.authenticate = onAuthenticate
}
}
Scaffold( Scaffold(
modifier = modifier, modifier = modifier,
@@ -180,7 +177,11 @@ fun SuperuserDetailScreen(
SettingsSwitch( SettingsSwitch(
title = stringResource(CoreR.string.settings_su_restrict_title), title = stringResource(CoreR.string.settings_su_restrict_title),
checked = item.isRestricted, checked = item.isRestricted,
onCheckedChange = { viewModel.toggleRestrict(item) } onCheckedChange = {
requireAuth {
viewModel.toggleRestrict(item)
}
}
) )
HorizontalDivider(modifier = Modifier.padding(horizontal = 16.dp)) HorizontalDivider(modifier = Modifier.padding(horizontal = 16.dp))
} }
@@ -199,8 +200,8 @@ fun SuperuserDetailScreen(
RevokeButton( RevokeButton(
onClick = { onClick = {
if (viewModel.requiresAuth) { if (Config.suAuth) {
viewModel.authenticate { viewModel.performDelete(item, onBack) } requireAuth { viewModel.performDelete(item, onBack) }
} else { } else {
scope.launch { scope.launch {
val result = revokeDialog.awaitConfirm( val result = revokeDialog.awaitConfirm(
@@ -53,6 +53,7 @@ import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.DpOffset import androidx.compose.ui.unit.DpOffset
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.topjohnwu.magisk.ui.component.rememberBiometricAuth
import com.topjohnwu.magisk.ui.component.verticalScrollbar import com.topjohnwu.magisk.ui.component.verticalScrollbar
import com.topjohnwu.magisk.core.R as CoreR import com.topjohnwu.magisk.core.R as CoreR
@@ -74,6 +75,7 @@ fun SuperuserGrantScreen(
var showSortMenu by remember { mutableStateOf(false) } var showSortMenu by remember { mutableStateOf(false) }
var showFilterMenu by remember { mutableStateOf(false) } var showFilterMenu by remember { mutableStateOf(false) }
val requireAuth = rememberBiometricAuth()
val searchBackState = rememberNavigationEventState(currentInfo = NavigationEventInfo.None) val searchBackState = rememberNavigationEventState(currentInfo = NavigationEventInfo.None)
NavigationBackHandler( NavigationBackHandler(
@@ -235,7 +237,11 @@ fun SuperuserGrantScreen(
) { app -> ) { app ->
SuGrantAppCard( SuGrantAppCard(
app = app, app = app,
onToggle = { viewModel.toggleGrant(app) } onToggle = {
requireAuth {
viewModel.toggleGrant(app)
}
}
) )
} }
} }
@@ -83,8 +83,6 @@ class SuperuserGrantViewModel(
private val _sortReverse = MutableStateFlow(false) private val _sortReverse = MutableStateFlow(false)
val sortReverse: StateFlow<Boolean> = _sortReverse.asStateFlow() val sortReverse: StateFlow<Boolean> = _sortReverse.asStateFlow()
var authenticate: (onSuccess: () -> Unit) -> Unit = { it() }
val filteredApps: StateFlow<List<SuGrantAppState>> = combine( val filteredApps: StateFlow<List<SuGrantAppState>> = combine(
_allApps, _query, _showSystem, _showOS, _sortBy, _sortReverse _allApps, _query, _showSystem, _showOS, _sortBy, _sortReverse
) { args -> ) { args ->
@@ -136,52 +134,44 @@ class SuperuserGrantViewModel(
fun toggleGrant(app: SuGrantAppState) { fun toggleGrant(app: SuGrantAppState) {
val willGrant = !app.isGranted val willGrant = !app.isGranted
fun updateState() { _allApps.update { apps ->
_allApps.update { apps -> apps.map { current ->
apps.map { current -> if (current.info.uid == app.info.uid) {
if (current.info.uid == app.info.uid) { current.copy(isGranted = willGrant)
current.copy(isGranted = willGrant) } else {
} else { current
current
}
} }
} }
viewModelScope.launch {
try {
withContext(Dispatchers.IO) {
if (willGrant) {
val existing = policyDB.fetch(app.info.uid)
val suPolicy = existing ?: SuPolicy(app.info.uid)
suPolicy.policy = if (Config.suRestrict) SuPolicy.RESTRICT else SuPolicy.ALLOW
suPolicy.remain = 0L
policyDB.update(suPolicy)
} else {
policyDB.delete(app.info.uid)
}
}
} catch (e: Exception) {
if (e is CancellationException) throw e
Timber.e(e)
_allApps.update { apps ->
apps.map { current ->
if (current.info.uid == app.info.uid && current.isGranted == willGrant) {
current.copy(isGranted = !willGrant)
} else {
current
}
}
}
return@launch
}
SuEvents.notifyPolicyChanged()
}
} }
viewModelScope.launch {
try {
withContext(Dispatchers.IO) {
if (willGrant) {
val existing = policyDB.fetch(app.info.uid)
val suPolicy = existing ?: SuPolicy(app.info.uid)
suPolicy.policy = if (Config.suRestrict) SuPolicy.RESTRICT else SuPolicy.ALLOW
suPolicy.remain = 0L
policyDB.update(suPolicy)
} else {
policyDB.delete(app.info.uid)
}
}
} catch (e: Exception) {
if (e is CancellationException) throw e
Timber.e(e)
_allApps.update { apps ->
apps.map { current ->
if (current.info.uid == app.info.uid && current.isGranted == willGrant) {
current.copy(isGranted = !willGrant)
} else {
current
}
}
}
return@launch
}
if (Config.suAuth) { SuEvents.notifyPolicyChanged()
authenticate { updateState() }
} else {
updateState()
} }
} }
@@ -39,6 +39,7 @@ import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.topjohnwu.magisk.ui.component.onlyHorizontal import com.topjohnwu.magisk.ui.component.onlyHorizontal
import com.topjohnwu.magisk.ui.component.rememberBiometricAuth
import com.topjohnwu.magisk.ui.component.verticalScrollbar import com.topjohnwu.magisk.ui.component.verticalScrollbar
import com.topjohnwu.magisk.ui.navigation.LocalNavigator import com.topjohnwu.magisk.ui.navigation.LocalNavigator
import com.topjohnwu.magisk.ui.navigation.Route import com.topjohnwu.magisk.ui.navigation.Route
@@ -55,6 +56,7 @@ fun SuperuserScreen(
val uiState by viewModel.uiState.collectAsStateWithLifecycle() val uiState by viewModel.uiState.collectAsStateWithLifecycle()
val scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior() val scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior()
val navigator = LocalNavigator.current val navigator = LocalNavigator.current
val requireAuth = rememberBiometricAuth()
DisposableEffect(onRegisterFab) { DisposableEffect(onRegisterFab) {
onRegisterFab?.invoke { navigator.push(Route.SuperuserGrant) } onRegisterFab?.invoke { navigator.push(Route.SuperuserGrant) }
@@ -162,7 +164,11 @@ fun SuperuserScreen(
val isLast = item == uiState.policies.lastOrNull() val isLast = item == uiState.policies.lastOrNull()
PolicyCard( PolicyCard(
item = item, item = item,
onToggle = { viewModel.togglePolicy(item) }, onToggle = {
requireAuth {
viewModel.togglePolicy(item)
}
},
onDetail = { navigator.push(Route.SuperuserDetail(item.policy.uid)) }, onDetail = { navigator.push(Route.SuperuserDetail(item.policy.uid)) },
modifier = if (isLast && contentFocusRequester != null) { modifier = if (isLast && contentFocusRequester != null) {
Modifier.focusRequester(contentFocusRequester) Modifier.focusRequester(contentFocusRequester)
@@ -44,8 +44,6 @@ class SuperuserViewModel(
private val db: PolicyDao private val db: PolicyDao
) : AsyncLoadViewModel() { ) : AsyncLoadViewModel() {
var authenticate: (onSuccess: () -> Unit) -> Unit = { it() }
init { init {
@OptIn(FlowPreview::class) @OptIn(FlowPreview::class)
viewModelScope.launch { viewModelScope.launch {
@@ -163,25 +161,17 @@ class SuperuserViewModel(
} }
fun updatePolicy(item: PolicyItem, newPolicy: Int) { fun updatePolicy(item: PolicyItem, newPolicy: Int) {
fun updateState() { viewModelScope.launch {
viewModelScope.launch { item.policy.policy = newPolicy
item.policy.policy = newPolicy db.update(item.policy)
db.update(item.policy) _uiState.update { state ->
_uiState.update { state -> state.copy(
state.copy( policies = state.policies.map {
policies = state.policies.map { if (it.policy.uid == item.policy.uid) it.copy(policyValue = newPolicy) else it
if (it.policy.uid == item.policy.uid) it.copy(policyValue = newPolicy) else it }
} )
)
}
} }
} }
if (Config.suAuth) {
authenticate { updateState() }
} else {
updateState()
}
} }
fun togglePolicy(item: PolicyItem) { fun togglePolicy(item: PolicyItem) {