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(
initialTab = initialTab,
superuserViewModel = superuserVm,
onAuthenticate = { action ->
extension.withAuthentication { if (it) action() }
}
)
}
entry<Route.DenyList> { _ ->
@@ -164,26 +161,15 @@ class MainActivity : ComponentActivity(), SplashScreenHost {
val vm: SuperuserViewModel = viewModel(
viewModelStoreOwner = this@MainActivity, factory = VMFactory
)
LaunchedEffect(Unit) {
vm.authenticate = { onSuccess ->
extension.withAuthentication { if (it) onSuccess() }
}
}
SuperuserDetailScreen(
uid = key.uid,
viewModel = vm,
onBack = { navigator.pop() },
onAuthenticate = { action ->
extension.withAuthentication { if (it) action() }
}
)
}
entry<Route.SuperuserGrant> { _ ->
val vm: SuperuserGrantViewModel = viewModel(factory = VMFactory)
LaunchedEffect(Unit) {
vm.authenticate = { onSuccess ->
extension.withAuthentication { if (it) onSuccess() }
}
vm.startLoading()
}
SuperuserGrantScreen(
@@ -88,7 +88,6 @@ fun MainScreen(
modifier: Modifier = Modifier,
initialTab: Int = Tab.HOME.ordinal,
superuserViewModel: SuperuserViewModel? = null,
onAuthenticate: ((onSuccess: () -> Unit) -> Unit)? = null,
) {
val navigator = LocalNavigator.current
val scope = rememberCoroutineScope()
@@ -279,11 +278,6 @@ fun MainScreen(
} else {
viewModel(factory = VMFactory)
}
LaunchedEffect(onAuthenticate) {
if (onAuthenticate != null) {
vm.authenticate = onAuthenticate
}
}
LaunchedEffect(isCurrentPage) {
if (isCurrentPage) vm.startLoading()
}
@@ -315,11 +309,6 @@ fun MainScreen(
}
Tab.SETTINGS -> {
val vm: SettingsViewModel = viewModel(factory = VMFactory)
LaunchedEffect(onAuthenticate) {
if (onAuthenticate != null) {
vm.authenticate = onAuthenticate
}
}
CollectNavEvents(vm, navigator)
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
import android.os.Build
import android.webkit.URLUtil
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.consumeWindowInsets
@@ -22,7 +22,6 @@ import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
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
@@ -30,17 +29,13 @@ import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.nestedscroll.nestedScroll
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.unit.dp
import androidx.lifecycle.compose.LifecycleResumeEffect
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.MediaStoreUtils
import com.topjohnwu.magisk.ui.ThemeState
import com.topjohnwu.magisk.ui.component.AdaptiveColumns
import com.topjohnwu.magisk.ui.component.MagiskDialog
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.SmallTitle
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.core.R as CoreR
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SettingsScreen(
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 scrollState = rememberScrollState()
Scaffold(
modifier = modifier,
topBar = {
@@ -70,7 +135,6 @@ fun SettingsScreen(
) { padding ->
// Without root, the Magisk and Superuser sections are hidden, so move the
// 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
AdaptiveColumns(
modifier = Modifier
@@ -94,65 +158,118 @@ fun SettingsScreen(
),
spacing = 16.dp,
first = {
Column { CustomizationSection(viewModel = viewModel) }
if (hasRootSections) {
Column { AppSettingsSection() }
Column {
CustomizationSection(
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 = {
if (!hasRootSections) {
Column { AppSettingsSection() }
if (!uiState.hasRootSections) {
Column {
AppSettingsSection(
uiState = uiState,
onUpdateChannelSelected = onUpdateChannelSelected,
onOpenCustomUrlDialog = onOpenCustomUrlDialog,
onToggleDoh = onToggleDoh,
onToggleCheckUpdate = onToggleCheckUpdate,
onOpenDownloadPathDialog = onOpenDownloadPathDialog,
onToggleRandomPackageName = onToggleRandomPackageName,
)
}
}
if (Info.env.isActive) {
Column { MagiskSection(viewModel = viewModel) }
if (uiState.isMagiskInstalled) {
Column {
MagiskSection(
uiState = uiState,
onCreateHosts = onCreateHosts,
onToggleZygisk = onToggleZygisk,
onToggleDenyList = onToggleDenyList,
onNavigateToDenyList = onNavigateToDenyList,
)
}
}
if (Info.showSuperUser) {
Column { SuperuserSection(viewModel = viewModel) }
if (uiState.isSuperUserAvailable) {
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 ---
@Composable
private fun CustomizationSection(
viewModel: SettingsViewModel,
uiState: SettingsUiState,
onOpenSystemLocale: () -> Unit,
onLanguageSelected: (Int) -> Unit,
onColorModeSelected: (Int) -> Unit,
modifier: Modifier = Modifier
) {
val context = LocalContext.current
SmallTitle(text = stringResource(CoreR.string.settings_customization))
Card(
modifier = modifier.fillMaxWidth(),
shape = RoundedCornerShape(20.dp),
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainerLow)
) {
if (LocaleSetting.useLocaleManager) {
val locale = LocaleSetting.instance.appLocale
val summary = locale?.getDisplayName(locale) ?: stringResource(CoreR.string.system_default)
if (uiState.useLocaleManager) {
val appLocale = LocaleSetting.instance.appLocale
SettingsArrow(
title = stringResource(CoreR.string.language),
summary = summary,
onClick = {
context.startActivity(LocaleSetting.localeSettingsIntent)
}
summary = appLocale?.getDisplayName(appLocale)
?: stringResource(CoreR.string.system_default),
onClick = onOpenSystemLocale
)
} 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(
title = stringResource(CoreR.string.language),
items = names.toList(),
selectedIndex = selectedIndex,
onSelectedIndexChange = { index ->
selectedIndex = index
Config.locale = tags[index]
}
items = uiState.availableLanguages,
selectedIndex = uiState.selectedLanguageIndex,
onSelectedIndexChange = onLanguageSelected
)
}
@@ -162,31 +279,12 @@ private fun CustomizationSection(
)
// Color Mode
val isDynamicColorSupported = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S
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)
val colorModes = stringArrayResource(CoreR.array.color_mode).asList()
SettingsDropdown(
title = stringResource(CoreR.string.settings_color_mode),
items = colorModeEntries,
selectedIndex = selectedIndex,
onSelectedIndexChange = { index ->
val newMode = ColorMode.fromUiIndex(index, isDynamicColorSupported)
colorMode = newMode.value
Config.colorMode = newMode.value
ThemeState.colorMode = newMode.value
}
items = if (uiState.isDynamicColorSupported) colorModes else colorModes.drop(3),
selectedIndex = uiState.selectedColorModeIndex,
onSelectedIndexChange = onColorModeSelected
)
}
}
@@ -195,10 +293,15 @@ private fun CustomizationSection(
@Composable
private fun AppSettingsSection(
uiState: SettingsUiState,
onUpdateChannelSelected: (Int) -> Unit,
onOpenCustomUrlDialog: () -> Unit,
onToggleDoh: (Boolean) -> Unit,
onToggleCheckUpdate: (Boolean) -> Unit,
onOpenDownloadPathDialog: () -> Unit,
onToggleRandomPackageName: (Boolean) -> Unit,
modifier: Modifier = Modifier
) {
val resources = LocalResources.current
SmallTitle(text = stringResource(CoreR.string.home_app_title))
Card(
modifier = modifier.fillMaxWidth(),
@@ -206,43 +309,23 @@ private fun AppSettingsSection(
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainerLow)
) {
// 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(
title = stringResource(CoreR.string.settings_update_channel_title),
items = updateChannelEntries,
selectedIndex = updateChannel,
onSelectedIndexChange = { index ->
updateChannel = index
Config.updateChannel = index
Info.resetUpdate()
if (index == Config.Value.CUSTOM_CHANNEL && Config.customChannelUrl.isBlank()) {
showUrlDialog = true
}
}
items = stringArrayResource(CoreR.array.update_channel).asList(),
selectedIndex = uiState.selectedUpdateChannelIndex,
onSelectedIndexChange = onUpdateChannelSelected
)
// Update Channel URL (for custom channel)
if (updateChannel == Config.Value.CUSTOM_CHANNEL) {
if (uiState.isCustomChannel) {
HorizontalDivider(
modifier = Modifier.padding(horizontal = 16.dp),
color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f)
)
if (showUrlDialog) {
UpdateChannelUrlDialog(
onDismiss = { showUrlDialog = false }
)
}
SettingsArrow(
title = stringResource(CoreR.string.settings_update_custom),
summary = Config.customChannelUrl.ifBlank { null },
onClick = { showUrlDialog = true }
summary = uiState.customChannelUrl.ifBlank { null },
onClick = onOpenCustomUrlDialog
)
}
@@ -252,15 +335,11 @@ private fun AppSettingsSection(
)
// DoH Toggle
var doh by remember { mutableStateOf(Config.doh) }
SettingsSwitch(
title = stringResource(CoreR.string.settings_doh_title),
summary = stringResource(CoreR.string.settings_doh_description),
checked = doh,
onCheckedChange = {
doh = it
Config.doh = it
}
checked = uiState.dohEnabled,
onCheckedChange = onToggleDoh
)
HorizontalDivider(
@@ -269,15 +348,11 @@ private fun AppSettingsSection(
)
// Update Checker
var checkUpdate by remember { mutableStateOf(Config.checkUpdate) }
SettingsSwitch(
title = stringResource(CoreR.string.settings_check_update_title),
summary = stringResource(CoreR.string.settings_check_update_summary),
checked = checkUpdate,
onCheckedChange = { newValue ->
checkUpdate = newValue
Config.checkUpdate = newValue
}
checked = uiState.checkUpdateEnabled,
onCheckedChange = onToggleCheckUpdate
)
HorizontalDivider(
@@ -286,18 +361,10 @@ private fun AppSettingsSection(
)
// Download Path
var showDownloadDialog by remember { mutableStateOf(false) }
if (showDownloadDialog) {
DownloadPathDialog(
onDismiss = { showDownloadDialog = false }
)
}
SettingsArrow(
title = stringResource(CoreR.string.settings_download_path_title),
summary = MediaStoreUtils.fullPath(Config.downloadDir),
onClick = {
showDownloadDialog = true
}
summary = uiState.downloadPathDisplay,
onClick = onOpenDownloadPathDialog
)
HorizontalDivider(
@@ -306,15 +373,11 @@ private fun AppSettingsSection(
)
// Random Package Name
var randName by remember { mutableStateOf(Config.randName) }
SettingsSwitch(
title = stringResource(CoreR.string.settings_random_name_title),
summary = stringResource(CoreR.string.settings_random_name_description),
checked = randName,
onCheckedChange = {
randName = it
Config.randName = it
}
checked = uiState.randomPackageNameEnabled,
onCheckedChange = onToggleRandomPackageName
)
}
}
@@ -323,7 +386,11 @@ private fun AppSettingsSection(
@Composable
private fun MagiskSection(
viewModel: SettingsViewModel,
uiState: SettingsUiState,
onCreateHosts: () -> Unit,
onToggleZygisk: (Boolean) -> Unit,
onToggleDenyList: (Boolean) -> Unit,
onNavigateToDenyList: () -> Unit,
modifier: Modifier = Modifier
) {
SmallTitle(text = stringResource(CoreR.string.magisk))
@@ -336,29 +403,24 @@ private fun MagiskSection(
SettingsArrow(
title = stringResource(CoreR.string.settings_hosts_title),
summary = stringResource(CoreR.string.settings_hosts_summary),
onClick = { viewModel.createHosts() }
onClick = onCreateHosts
)
if (Const.Version.atLeast_24_0()) {
if (uiState.isZygiskSupported) {
HorizontalDivider(
modifier = Modifier.padding(horizontal = 16.dp),
color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f)
)
// Zygisk
var zygisk by remember { mutableStateOf(Config.zygisk) }
SettingsSwitch(
title = stringResource(CoreR.string.zygisk),
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
),
checked = zygisk,
onCheckedChange = {
zygisk = it
Config.zygisk = it
viewModel.notifyZygiskChange()
}
checked = uiState.zygiskEnabled,
onCheckedChange = onToggleZygisk
)
HorizontalDivider(
@@ -367,12 +429,11 @@ private fun MagiskSection(
)
// DenyList
val denyListEnabled by viewModel.denyListEnabled.collectAsStateWithLifecycle()
SettingsSwitch(
title = stringResource(CoreR.string.settings_denylist_title),
summary = stringResource(CoreR.string.settings_denylist_summary),
checked = denyListEnabled,
onCheckedChange = { viewModel.toggleDenyList(it) }
checked = uiState.denyListEnabled,
onCheckedChange = onToggleDenyList
)
HorizontalDivider(
@@ -384,7 +445,7 @@ private fun MagiskSection(
SettingsArrow(
title = stringResource(CoreR.string.settings_denylist_config_title),
summary = stringResource(CoreR.string.settings_denylist_config_summary),
onClick = { viewModel.navigateToDenyList() }
onClick = onNavigateToDenyList
)
}
}
@@ -394,86 +455,63 @@ private fun MagiskSection(
@Composable
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
) {
val resources = LocalResources.current
SmallTitle(text = stringResource(CoreR.string.superuser))
Card(
modifier = modifier.fillMaxWidth(),
shape = RoundedCornerShape(20.dp),
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainerLow)
) {
// Authentication
var suAuth by remember { mutableStateOf(Config.suAuth) }
SettingsSwitch(
title = stringResource(CoreR.string.settings_su_auth_title),
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
),
checked = suAuth,
enabled = Info.isDeviceSecure,
onCheckedChange = { newValue ->
viewModel.withAuth {
suAuth = newValue
Config.suAuth = newValue
}
}
checked = uiState.suAuthEnabled,
enabled = uiState.isDeviceSecure,
onCheckedChange = onToggleSuAuth
)
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(
modifier = Modifier.padding(horizontal = 16.dp),
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
val namespaceEntries = remember {
resources.getStringArray(CoreR.array.namespace).toList()
}
val namespaceDescriptions = remember {
resources.getStringArray(CoreR.array.namespace_summary).toList()
}
var mntNamespaceMode by remember { mutableIntStateOf(Config.suMntNamespaceMode) }
val namespaceSummaries = stringArrayResource(CoreR.array.namespace_summary)
SettingsDropdown(
title = stringResource(CoreR.string.mount_namespace_mode),
summary = namespaceDescriptions.getOrElse(mntNamespaceMode) { "" },
items = namespaceEntries,
selectedIndex = mntNamespaceMode,
onSelectedIndexChange = {
mntNamespaceMode = it
Config.suMntNamespaceMode = it
}
summary = namespaceSummaries.getOrElse(uiState.selectedNamespaceModeIndex) { "" },
items = stringArrayResource(CoreR.array.namespace).asList(),
selectedIndex = uiState.selectedNamespaceModeIndex,
onSelectedIndexChange = onNamespaceModeSelected
)
HorizontalDivider(
@@ -482,36 +520,24 @@ private fun SuperuserSection(
)
// SU Notification
val notifEntries = remember {
resources.getStringArray(CoreR.array.su_notification).toList()
}
var suNotification by remember { mutableIntStateOf(Config.suNotification) }
SettingsDropdown(
title = stringResource(CoreR.string.superuser_notification),
items = notifEntries,
selectedIndex = suNotification,
onSelectedIndexChange = {
suNotification = it
Config.suNotification = it
}
items = stringArrayResource(CoreR.array.su_notification).asList(),
selectedIndex = uiState.selectedNotificationModeIndex,
onSelectedIndexChange = onNotificationModeSelected
)
// Restrict (version >= 30.1)
if (Const.Version.atLeast_30_1()) {
if (uiState.isSuRestrictSupported) {
HorizontalDivider(
modifier = Modifier.padding(horizontal = 16.dp),
color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f)
)
var restrict by remember { mutableStateOf(Config.suRestrict) }
SettingsSwitch(
title = stringResource(CoreR.string.settings_su_restrict_title),
summary = stringResource(CoreR.string.settings_su_restrict_summary),
checked = restrict,
onCheckedChange = {
restrict = it
Config.suRestrict = it
}
checked = uiState.suRestrictEnabled,
onCheckedChange = onToggleSuRestrict
)
}
}
@@ -521,20 +547,29 @@ private fun SuperuserSection(
@Composable
private fun UpdateChannelUrlDialog(
initialUrl: String,
onConfirm: (String) -> Unit,
onDismiss: () -> Unit,
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(
modifier = modifier,
onDismissRequest = onDismiss,
title = stringResource(CoreR.string.settings_update_custom_msg),
confirmText = stringResource(android.R.string.ok),
confirmEnabled = isValidUrl,
onConfirm = {
Config.customChannelUrl = url
Info.resetUpdate()
onDismiss()
if (isValidUrl) {
onConfirm(url)
}
},
dismissText = stringResource(android.R.string.cancel),
onDismiss = onDismiss,
@@ -544,6 +579,7 @@ private fun UpdateChannelUrlDialog(
OutlinedTextField(
value = url,
onValueChange = { url = it },
isError = !isValidUrl,
shape = RoundedCornerShape(12.dp),
modifier = Modifier.fillMaxWidth()
)
@@ -553,10 +589,12 @@ private fun UpdateChannelUrlDialog(
@Composable
private fun DownloadPathDialog(
initialPath: String,
onConfirm: (String) -> Unit,
onDismiss: () -> Unit,
modifier: Modifier = Modifier
) {
var path by rememberSaveable { mutableStateOf(Config.downloadDir) }
var path by rememberSaveable(initialPath) { mutableStateOf(initialPath) }
MagiskDialog(
modifier = modifier,
@@ -564,8 +602,7 @@ private fun DownloadPathDialog(
title = stringResource(CoreR.string.settings_download_path_title),
confirmText = stringResource(android.R.string.ok),
onConfirm = {
Config.downloadDir = path
onDismiss()
onConfirm(path.trim())
},
dismissText = stringResource(android.R.string.cancel),
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
import android.os.Build
import android.widget.Toast
import androidx.lifecycle.viewModelScope
import com.topjohnwu.magisk.arch.BaseViewModel
import com.topjohnwu.magisk.core.AppContext
import com.topjohnwu.magisk.core.Config
import com.topjohnwu.magisk.core.Const
import com.topjohnwu.magisk.core.Info
import com.topjohnwu.magisk.core.R
import com.topjohnwu.magisk.core.R as CoreR
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.ui.ThemeState
import com.topjohnwu.magisk.ui.navigation.Route
import com.topjohnwu.superuser.Shell
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
class SettingsViewModel : BaseViewModel() {
private val _denyListEnabled = MutableStateFlow(Config.denyList)
val denyListEnabled: StateFlow<Boolean> = _denyListEnabled.asStateFlow()
private val _uiState = MutableStateFlow(buildInitialState())
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() {
navigateTo(Route.DenyList)
val updateIndex = Config.updateChannelIndex
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() {
viewModelScope.launch {
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) {
_denyListEnabled.value = enabled
_uiState.update { it.copy(denyListEnabled = enabled) }
val cmd = if (enabled) "enable" else "disable"
Shell.cmd("magisk --denylist $cmd").submit { result ->
if (result.isSuccess) {
Config.denyList = enabled
} else {
_denyListEnabled.value = !enabled
_uiState.update { it.copy(denyListEnabled = !enabled) }
}
}
}
fun withAuth(action: () -> Unit) = authenticate(action)
fun navigateToDenyList() {
navigateTo(Route.DenyList)
}
fun notifyZygiskChange() {
if (zygiskMismatch) showSnackbar(R.string.reboot_apply_change)
fun setSuAuth(enabled: Boolean) {
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.lifecycle.compose.collectAsStateWithLifecycle
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.SettingsSwitch
import com.topjohnwu.magisk.ui.component.rememberBiometricAuth
import com.topjohnwu.magisk.ui.component.rememberConfirmDialog
import com.topjohnwu.magisk.ui.component.verticalScrollbar
import kotlinx.coroutines.launch
@@ -60,7 +62,6 @@ fun SuperuserDetailScreen(
viewModel: SuperuserViewModel,
onBack: () -> Unit,
modifier: Modifier = Modifier,
onAuthenticate: ((onSuccess: () -> Unit) -> Unit)? = null,
) {
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
val items = uiState.policies.filter { it.policy.uid == uid }
@@ -68,6 +69,7 @@ fun SuperuserDetailScreen(
val scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior()
val scrollState = rememberScrollState()
val scope = rememberCoroutineScope()
val requireAuth = rememberBiometricAuth()
val revokeDialog = rememberConfirmDialog()
val revokeTitle = stringResource(CoreR.string.su_revoke_title)
val revokeMsg = item?.let { stringResource(CoreR.string.su_revoke_msg, it.appName) } ?: ""
@@ -78,11 +80,6 @@ fun SuperuserDetailScreen(
viewModel.startLoading()
}
}
LaunchedEffect(onAuthenticate) {
if (onAuthenticate != null) {
viewModel.authenticate = onAuthenticate
}
}
Scaffold(
modifier = modifier,
@@ -180,7 +177,11 @@ fun SuperuserDetailScreen(
SettingsSwitch(
title = stringResource(CoreR.string.settings_su_restrict_title),
checked = item.isRestricted,
onCheckedChange = { viewModel.toggleRestrict(item) }
onCheckedChange = {
requireAuth {
viewModel.toggleRestrict(item)
}
}
)
HorizontalDivider(modifier = Modifier.padding(horizontal = 16.dp))
}
@@ -199,8 +200,8 @@ fun SuperuserDetailScreen(
RevokeButton(
onClick = {
if (viewModel.requiresAuth) {
viewModel.authenticate { viewModel.performDelete(item, onBack) }
if (Config.suAuth) {
requireAuth { viewModel.performDelete(item, onBack) }
} else {
scope.launch {
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.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.topjohnwu.magisk.ui.component.rememberBiometricAuth
import com.topjohnwu.magisk.ui.component.verticalScrollbar
import com.topjohnwu.magisk.core.R as CoreR
@@ -74,6 +75,7 @@ fun SuperuserGrantScreen(
var showSortMenu by remember { mutableStateOf(false) }
var showFilterMenu by remember { mutableStateOf(false) }
val requireAuth = rememberBiometricAuth()
val searchBackState = rememberNavigationEventState(currentInfo = NavigationEventInfo.None)
NavigationBackHandler(
@@ -235,7 +237,11 @@ fun SuperuserGrantScreen(
) { app ->
SuGrantAppCard(
app = app,
onToggle = { viewModel.toggleGrant(app) }
onToggle = {
requireAuth {
viewModel.toggleGrant(app)
}
}
)
}
}
@@ -83,8 +83,6 @@ class SuperuserGrantViewModel(
private val _sortReverse = MutableStateFlow(false)
val sortReverse: StateFlow<Boolean> = _sortReverse.asStateFlow()
var authenticate: (onSuccess: () -> Unit) -> Unit = { it() }
val filteredApps: StateFlow<List<SuGrantAppState>> = combine(
_allApps, _query, _showSystem, _showOS, _sortBy, _sortReverse
) { args ->
@@ -136,52 +134,44 @@ class SuperuserGrantViewModel(
fun toggleGrant(app: SuGrantAppState) {
val willGrant = !app.isGranted
fun updateState() {
_allApps.update { apps ->
apps.map { current ->
if (current.info.uid == app.info.uid) {
current.copy(isGranted = willGrant)
} else {
current
}
_allApps.update { apps ->
apps.map { current ->
if (current.info.uid == app.info.uid) {
current.copy(isGranted = willGrant)
} else {
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) {
authenticate { updateState() }
} else {
updateState()
SuEvents.notifyPolicyChanged()
}
}
@@ -39,6 +39,7 @@ import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
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.navigation.LocalNavigator
import com.topjohnwu.magisk.ui.navigation.Route
@@ -55,6 +56,7 @@ fun SuperuserScreen(
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
val scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior()
val navigator = LocalNavigator.current
val requireAuth = rememberBiometricAuth()
DisposableEffect(onRegisterFab) {
onRegisterFab?.invoke { navigator.push(Route.SuperuserGrant) }
@@ -162,7 +164,11 @@ fun SuperuserScreen(
val isLast = item == uiState.policies.lastOrNull()
PolicyCard(
item = item,
onToggle = { viewModel.togglePolicy(item) },
onToggle = {
requireAuth {
viewModel.togglePolicy(item)
}
},
onDetail = { navigator.push(Route.SuperuserDetail(item.policy.uid)) },
modifier = if (isLast && contentFocusRequester != null) {
Modifier.focusRequester(contentFocusRequester)
@@ -44,8 +44,6 @@ class SuperuserViewModel(
private val db: PolicyDao
) : AsyncLoadViewModel() {
var authenticate: (onSuccess: () -> Unit) -> Unit = { it() }
init {
@OptIn(FlowPreview::class)
viewModelScope.launch {
@@ -163,25 +161,17 @@ class SuperuserViewModel(
}
fun updatePolicy(item: PolicyItem, newPolicy: Int) {
fun updateState() {
viewModelScope.launch {
item.policy.policy = newPolicy
db.update(item.policy)
_uiState.update { state ->
state.copy(
policies = state.policies.map {
if (it.policy.uid == item.policy.uid) it.copy(policyValue = newPolicy) else it
}
)
}
viewModelScope.launch {
item.policy.policy = newPolicy
db.update(item.policy)
_uiState.update { state ->
state.copy(
policies = state.policies.map {
if (it.policy.uid == item.policy.uid) it.copy(policyValue = newPolicy) else it
}
)
}
}
if (Config.suAuth) {
authenticate { updateState() }
} else {
updateState()
}
}
fun togglePolicy(item: PolicyItem) {