diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/arch/ViewModelFactory.kt b/app/apk/src/main/java/com/topjohnwu/magisk/arch/ViewModelFactory.kt index 8302443bc..dd464d845 100644 --- a/app/apk/src/main/java/com/topjohnwu/magisk/arch/ViewModelFactory.kt +++ b/app/apk/src/main/java/com/topjohnwu/magisk/arch/ViewModelFactory.kt @@ -12,6 +12,7 @@ import com.topjohnwu.magisk.ui.log.LogViewModel import com.topjohnwu.magisk.ui.module.ActionViewModel import com.topjohnwu.magisk.ui.module.ModuleViewModel import com.topjohnwu.magisk.ui.settings.SettingsViewModel +import com.topjohnwu.magisk.ui.superuser.SuperuserGrantViewModel import com.topjohnwu.magisk.ui.superuser.SuperuserViewModel import com.topjohnwu.magisk.ui.surequest.SuRequestViewModel @@ -19,6 +20,7 @@ val VMFactory: ViewModelProvider.Factory = viewModelFactory { initializer { HomeViewModel(ServiceLocator.networkService) } initializer { LogViewModel(ServiceLocator.logRepo) } initializer { SuperuserViewModel(ServiceLocator.policyDB) } + initializer { SuperuserGrantViewModel(ServiceLocator.policyDB) } initializer { InstallViewModel(ServiceLocator.networkService) } initializer { SuRequestViewModel(ServiceLocator.policyDB, ServiceLocator.timeoutPrefs) } initializer { DenyListViewModel() } diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/MainActivity.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/MainActivity.kt index b0751960e..0c328ed8f 100644 --- a/app/apk/src/main/java/com/topjohnwu/magisk/ui/MainActivity.kt +++ b/app/apk/src/main/java/com/topjohnwu/magisk/ui/MainActivity.kt @@ -57,6 +57,8 @@ import com.topjohnwu.magisk.ui.navigation.Navigator import com.topjohnwu.magisk.ui.navigation.Route import com.topjohnwu.magisk.ui.navigation.rememberNavigator import com.topjohnwu.magisk.ui.superuser.SuperuserDetailScreen +import com.topjohnwu.magisk.ui.superuser.SuperuserGrantScreen +import com.topjohnwu.magisk.ui.superuser.SuperuserGrantViewModel import com.topjohnwu.magisk.ui.superuser.SuperuserViewModel import com.topjohnwu.magisk.view.Shortcuts import kotlinx.coroutines.flow.MutableStateFlow @@ -176,6 +178,19 @@ class MainActivity : ComponentActivity(), SplashScreenHost { } ) } + entry { _ -> + val vm: SuperuserGrantViewModel = viewModel(factory = VMFactory) + LaunchedEffect(Unit) { + vm.authenticate = { onSuccess -> + extension.withAuthentication { if (it) onSuccess() } + } + vm.startLoading() + } + SuperuserGrantScreen( + viewModel = vm, + onBack = { navigator.pop() }, + ) + } entry { key -> val vm: ActionViewModel = viewModel(factory = VMFactory) LaunchedEffect(key) { diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/MainScreen.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/MainScreen.kt index 71be675a7..3878dd4ec 100644 --- a/app/apk/src/main/java/com/topjohnwu/magisk/ui/MainScreen.kt +++ b/app/apk/src/main/java/com/topjohnwu/magisk/ui/MainScreen.kt @@ -92,9 +92,13 @@ fun MainScreen( val pagerState = rememberPagerState(initialPage = initialPage, pageCount = { visibleTabs.size }) val fabFocusRequester = remember { FocusRequester() } val navModulesFocusRequester = remember { FocusRequester() } + val navSuperuserFocusRequester = remember { FocusRequester() } val moduleContentFocusRequester = remember { FocusRequester() } + val superuserContentFocusRequester = remember { FocusRequester() } var moduleFabAction by remember { mutableStateOf<(() -> Unit)?>(null) } + var superuserFabAction by remember { mutableStateOf<(() -> Unit)?>(null) } val isModulesTab = visibleTabs.getOrNull(pagerState.currentPage) == Tab.MODULES + val isSuperuserTab = visibleTabs.getOrNull(pagerState.currentPage) == Tab.SUPERUSER Scaffold( modifier = modifier.fillMaxSize(), @@ -103,16 +107,18 @@ fun MainScreen( ShortNavigationBar { visibleTabs.forEachIndexed { index, tab -> val isModulesItem = tab == Tab.MODULES + val isSuperuserItem = tab == Tab.SUPERUSER ShortNavigationBarItem( selected = pagerState.currentPage == index, onClick = { scope.launch { pagerState.animateScrollToPage(index) } }, modifier = Modifier .then( if (isModulesItem) Modifier.focusRequester(navModulesFocusRequester) + else if (isSuperuserItem) Modifier.focusRequester(navSuperuserFocusRequester) else Modifier ) .focusProperties { - if (isModulesTab && isModulesItem) { + if ((isModulesTab && isModulesItem) || (isSuperuserTab && isSuperuserItem)) { up = fabFocusRequester } }, @@ -128,18 +134,22 @@ fun MainScreen( } }, floatingActionButton = { + val showFab = (isModulesTab && moduleFabAction != null) || (isSuperuserTab && superuserFabAction != null) AnimatedVisibility( - visible = isModulesTab && moduleFabAction != null, + visible = showFab, enter = scaleIn() + fadeIn(), exit = scaleOut() + fadeOut(), ) { FloatingActionButton( - onClick = { moduleFabAction?.invoke() }, + onClick = { + if (isModulesTab) moduleFabAction?.invoke() + else if (isSuperuserTab) superuserFabAction?.invoke() + }, modifier = Modifier .focusRequester(fabFocusRequester) .focusProperties { - up = moduleContentFocusRequester - down = navModulesFocusRequester + up = if (isModulesTab) moduleContentFocusRequester else superuserContentFocusRequester + down = if (isModulesTab) navModulesFocusRequester else navSuperuserFocusRequester right = FocusRequester.Cancel }, containerColor = MaterialTheme.colorScheme.primaryContainer, @@ -147,7 +157,10 @@ fun MainScreen( ) { Icon( imageVector = Icons.Default.Add, - contentDescription = stringResource(CoreR.string.module_action_install_external), + contentDescription = stringResource( + if (isModulesTab) CoreR.string.module_action_install_external + else CoreR.string.superuser_grant + ), modifier = Modifier.size(28.dp), ) } @@ -182,7 +195,7 @@ fun MainScreen( cancelFocusChange() } } - if (tab == Tab.MODULES) { + if (tab == Tab.MODULES || tab == Tab.SUPERUSER) { down = fabFocusRequester } } @@ -215,7 +228,12 @@ fun MainScreen( LaunchedEffect(isCurrentPage) { if (isCurrentPage) vm.startLoading() } - SuperuserScreen(vm) + CollectNavEvents(vm, navigator) + SuperuserScreen( + viewModel = vm, + onRegisterFab = { superuserFabAction = it }, + contentFocusRequester = superuserContentFocusRequester, + ) } Tab.LOG -> { val vm: LogViewModel = viewModel(factory = VMFactory) diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/navigation/Routes.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/navigation/Routes.kt index f05bcd033..611649382 100644 --- a/app/apk/src/main/java/com/topjohnwu/magisk/ui/navigation/Routes.kt +++ b/app/apk/src/main/java/com/topjohnwu/magisk/ui/navigation/Routes.kt @@ -25,6 +25,10 @@ sealed interface Route : NavKey, Parcelable { @Serializable data class SuperuserDetail(val uid: Int) : Route + @Parcelize + @Serializable + data object SuperuserGrant : Route + @Parcelize @Serializable data class Action( diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/superuser/SuperuserCard.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/superuser/SuperuserCard.kt new file mode 100644 index 000000000..11654c385 --- /dev/null +++ b/app/apk/src/main/java/com/topjohnwu/magisk/ui/superuser/SuperuserCard.kt @@ -0,0 +1,157 @@ +package com.topjohnwu.magisk.ui.superuser + +import android.graphics.drawable.Drawable +import androidx.compose.foundation.Image +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.Badge +import androidx.compose.material3.Card +import androidx.compose.material3.CardColors +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.ListItem +import androidx.compose.material3.ListItemDefaults +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.Shape +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.role +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import com.google.accompanist.drawablepainter.rememberDrawablePainter +import com.topjohnwu.magisk.core.R as CoreR + +@Composable +internal fun SharedUidBadge(modifier: Modifier = Modifier) { + Badge( + modifier = modifier, + containerColor = MaterialTheme.colorScheme.secondaryContainer, + contentColor = MaterialTheme.colorScheme.onSecondaryContainer, + ) { + Text( + text = stringResource(CoreR.string.shared_uid), + style = MaterialTheme.typography.labelSmall, + fontWeight = FontWeight.SemiBold, + modifier = Modifier.padding(horizontal = 2.dp) + ) + } +} + +@Composable +fun SuperuserAppListItem( + icon: Drawable, + title: String, + packageName: String, + isSharedUid: Boolean, + modifier: Modifier = Modifier, + contentDescription: String? = null, + trailingContent: @Composable (() -> Unit)? = null, +) { + ListItem( + modifier = modifier, + leadingContent = { + Image( + painter = rememberDrawablePainter(icon), + contentDescription = null, + modifier = Modifier.size(40.dp) + ) + }, + headlineContent = { + Row(verticalAlignment = Alignment.CenterVertically) { + Text( + text = title, + style = MaterialTheme.typography.titleMedium, + modifier = Modifier.weight(1f, fill = false), + ) + if (isSharedUid) { + Spacer(Modifier.width(6.dp)) + SharedUidBadge() + } + } + }, + supportingContent = { + Text( + text = packageName, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + }, + trailingContent = trailingContent, + colors = ListItemDefaults.colors(containerColor = Color.Transparent) + ) +} + +@Composable +fun SuperuserAppCard( + icon: Drawable, + title: String, + packageName: String, + isSharedUid: Boolean, + modifier: Modifier = Modifier, + onClick: (() -> Unit)? = null, + checked: Boolean? = null, + onCheckedChange: ((Boolean) -> Unit)? = null, + enabled: Boolean = true, + shape: Shape = RoundedCornerShape(20.dp), + colors: CardColors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainerLow), + contentDescription: String? = null, + trailingContent: @Composable (() -> Unit)? = null, +) { + val itemContent = @Composable { + SuperuserAppListItem( + icon = icon, + title = title, + packageName = packageName, + isSharedUid = isSharedUid, + contentDescription = contentDescription, + trailingContent = trailingContent, + ) + } + + if (checked != null && onCheckedChange != null) { + Surface( + checked = checked, + onCheckedChange = onCheckedChange, + modifier = Modifier + .fillMaxWidth() + .semantics { role = Role.Checkbox } + .then(modifier), + enabled = enabled, + shape = shape, + color = if (enabled) colors.containerColor else colors.disabledContainerColor, + contentColor = if (enabled) colors.contentColor else colors.disabledContentColor, + content = itemContent, + ) + } else if (onClick != null) { + Card( + onClick = onClick, + modifier = Modifier + .fillMaxWidth() + .then(modifier), + enabled = enabled, + shape = shape, + colors = colors, + content = { itemContent() }, + ) + } else { + Card( + modifier = Modifier + .fillMaxWidth() + .then(modifier), + shape = shape, + colors = colors, + content = { itemContent() }, + ) + } +} diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/superuser/SuperuserGrantScreen.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/superuser/SuperuserGrantScreen.kt new file mode 100644 index 000000000..488e2f339 --- /dev/null +++ b/app/apk/src/main/java/com/topjohnwu/magisk/ui/superuser/SuperuserGrantScreen.kt @@ -0,0 +1,286 @@ +package com.topjohnwu.magisk.ui.superuser + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material.icons.automirrored.filled.Sort +import androidx.compose.material.icons.filled.Check +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.Search +import androidx.compose.material.icons.filled.Tune +import androidx.compose.material3.Checkbox +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SearchBarDefaults +import androidx.compose.material3.Text +import androidx.compose.material3.TextField +import androidx.compose.material3.TextFieldDefaults +import androidx.compose.material3.TopAppBar +import androidx.compose.material3.TopAppBarDefaults +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 androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.input.nestedscroll.nestedScroll +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.verticalScrollbar +import com.topjohnwu.magisk.core.R as CoreR + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun SuperuserGrantScreen( + viewModel: SuperuserGrantViewModel, + onBack: () -> Unit, + modifier: Modifier = Modifier, +) { + + val loading by viewModel.loading.collectAsStateWithLifecycle() + val apps by viewModel.filteredApps.collectAsStateWithLifecycle() + val query by viewModel.query.collectAsStateWithLifecycle() + val showSystem by viewModel.showSystem.collectAsStateWithLifecycle() + val showOS by viewModel.showOS.collectAsStateWithLifecycle() + val sortBy by viewModel.sortBy.collectAsStateWithLifecycle() + val sortReverse by viewModel.sortReverse.collectAsStateWithLifecycle() + + var showSortMenu by remember { mutableStateOf(false) } + var showFilterMenu by remember { mutableStateOf(false) } + + val scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior() + Scaffold( + modifier = modifier, + topBar = { + TopAppBar( + title = { Text(stringResource(CoreR.string.superuser_grant)) }, + navigationIcon = { + IconButton(onClick = onBack) { + Icon( + imageVector = Icons.AutoMirrored.Filled.ArrowBack, + contentDescription = stringResource(CoreR.string.back), + ) + } + }, + actions = { + Box { + IconButton(onClick = { showSortMenu = true }) { + Icon( + imageVector = Icons.AutoMirrored.Filled.Sort, + contentDescription = stringResource(CoreR.string.menu_sort), + ) + } + DropdownMenu( + expanded = showSortMenu, + onDismissRequest = { showSortMenu = false } + ) { + val sortOptions = listOf( + CoreR.string.sort_by_name to SortBy.NAME, + CoreR.string.sort_by_package_name to SortBy.PACKAGE_NAME, + CoreR.string.sort_by_install_time to SortBy.INSTALL_TIME, + CoreR.string.sort_by_update_time to SortBy.UPDATE_TIME, + ) + sortOptions.forEach { (resId, sort) -> + DropdownMenuItem( + text = { Text(stringResource(resId)) }, + trailingIcon = if (sortBy == sort) { + { Icon(Icons.Default.Check, contentDescription = null) } + } else null, + onClick = { + viewModel.setSortBy(sort) + showSortMenu = false + } + ) + } + DropdownMenuItem( + text = { Text(stringResource(CoreR.string.sort_reverse)) }, + trailingIcon = if (sortReverse) { + { Icon(Icons.Default.Check, contentDescription = null) } + } else null, + onClick = { + viewModel.toggleSortReverse() + showSortMenu = false + } + ) + } + } + + Box { + IconButton(onClick = { showFilterMenu = true }) { + Icon( + imageVector = Icons.Default.Tune, + contentDescription = stringResource(CoreR.string.hide_filter_hint), + ) + } + DropdownMenu( + expanded = showFilterMenu, + onDismissRequest = { showFilterMenu = false }, + offset = DpOffset(x = (-8).dp, y = 0.dp), + ) { + DropdownMenuItem( + text = { Text(stringResource(CoreR.string.show_system_app)) }, + trailingIcon = if (showSystem) { + { Icon(Icons.Default.Check, contentDescription = null) } + } else null, + onClick = { + viewModel.setShowSystem(!showSystem) + showFilterMenu = false + } + ) + DropdownMenuItem( + text = { Text(stringResource(CoreR.string.show_os_app)) }, + trailingIcon = if (showOS) { + { Icon(Icons.Default.Check, contentDescription = null) } + } else null, + onClick = { + if (!showOS && !showSystem) { + viewModel.setShowSystem(true) + } + viewModel.setShowOS(!showOS) + showFilterMenu = false + } + ) + } + } + }, + scrollBehavior = scrollBehavior + ) + } + ) { padding -> + Column(modifier = Modifier.fillMaxSize().padding(padding)) { + SearchInput( + query = query, + onQueryChange = viewModel::setQuery, + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 6.dp) + ) + + if (loading) { + Box( + modifier = Modifier.fillMaxSize(), + contentAlignment = Alignment.Center + ) { + Column(horizontalAlignment = Alignment.CenterHorizontally) { + Text( + text = stringResource(CoreR.string.loading), + style = MaterialTheme.typography.titleLarge + ) + Spacer(Modifier.height(16.dp)) + CircularProgressIndicator() + } + } + } else { + val listState = rememberLazyListState() + LazyColumn( + state = listState, + modifier = Modifier + .fillMaxSize() + .nestedScroll(scrollBehavior.nestedScrollConnection) + .verticalScrollbar(listState, contentPadding = PaddingValues(vertical = 8.dp)), + contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp), + verticalArrangement = Arrangement.spacedBy(8.dp) + ) { + items( + items = apps, + key = { it.info.packageName }, + contentType = { "SuGrantAppCard" } + ) { app -> + SuGrantAppCard( + app = app, + onToggle = { viewModel.toggleGrant(app) } + ) + } + } + } + } + } +} + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +private fun SearchInput( + query: String, + onQueryChange: (String) -> Unit, + modifier: Modifier = Modifier +) { + TextField( + value = query, + onValueChange = onQueryChange, + modifier = modifier, + placeholder = { Text(stringResource(CoreR.string.hide_filter_hint)) }, + leadingIcon = { + Icon( + imageVector = Icons.Default.Search, + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant + ) + }, + trailingIcon = if (query.isNotEmpty()) { + { + IconButton(onClick = { onQueryChange("") }) { + Icon( + imageVector = Icons.Default.Close, + contentDescription = stringResource(CoreR.string.close), + tint = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + } else null, + shape = SearchBarDefaults.inputFieldShape, + singleLine = true, + colors = TextFieldDefaults.colors( + focusedContainerColor = MaterialTheme.colorScheme.surfaceContainerHigh, + unfocusedContainerColor = MaterialTheme.colorScheme.surfaceContainerHigh, + focusedIndicatorColor = Color.Transparent, + unfocusedIndicatorColor = Color.Transparent, + disabledIndicatorColor = Color.Transparent, + ) + ) +} + +@Composable +private fun SuGrantAppCard( + app: SuGrantAppState, + onToggle: () -> Unit, + modifier: Modifier = Modifier +) { + SuperuserAppCard( + icon = app.info.icon, + title = app.info.label, + packageName = app.info.packageName, + isSharedUid = app.info.isSharedUid, + checked = app.isGranted, + onCheckedChange = { onToggle() }, + contentDescription = app.info.label, + modifier = modifier, + trailingContent = { + Checkbox( + checked = app.isGranted, + onCheckedChange = null + ) + } + ) +} diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/superuser/SuperuserGrantViewModel.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/superuser/SuperuserGrantViewModel.kt new file mode 100644 index 000000000..526185050 --- /dev/null +++ b/app/apk/src/main/java/com/topjohnwu/magisk/ui/superuser/SuperuserGrantViewModel.kt @@ -0,0 +1,273 @@ +package com.topjohnwu.magisk.ui.superuser + +import android.annotation.SuppressLint +import android.content.pm.ApplicationInfo +import android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES +import android.graphics.drawable.Drawable +import androidx.core.os.ProcessCompat +import androidx.lifecycle.viewModelScope +import com.topjohnwu.magisk.arch.AsyncLoadViewModel +import com.topjohnwu.magisk.core.AppContext +import com.topjohnwu.magisk.core.BuildConfig +import com.topjohnwu.magisk.core.Config +import com.topjohnwu.magisk.core.R as CoreR +import com.topjohnwu.magisk.core.data.magiskdb.PolicyDao +import com.topjohnwu.magisk.core.ktx.concurrentMap +import com.topjohnwu.magisk.core.ktx.getLabel +import com.topjohnwu.magisk.core.model.su.SuPolicy +import com.topjohnwu.magisk.core.su.SuEvents +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.SharingStarted +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.filter +import kotlinx.coroutines.flow.stateIn +import kotlinx.coroutines.flow.toCollection +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import timber.log.Timber +import java.util.Locale + +enum class SortBy { NAME, PACKAGE_NAME, INSTALL_TIME, UPDATE_TIME } + +data class SuGrantAppInfo( + val label: String, + val packageName: String, + val icon: Drawable, + val uid: Int, + val isSystemApp: Boolean, + val isApp: Boolean, + val isSharedUid: Boolean, + val firstInstallTime: Long, + val lastUpdateTime: Long, +) { + val isShell: Boolean + get() = packageName == SHELL_PACKAGE || uid == SHELL_UID + + companion object { + const val SHELL_PACKAGE = "com.android.shell" + const val SHELL_UID = 2000 + } +} + +data class SuGrantAppState( + val info: SuGrantAppInfo, + val isGranted: Boolean, + val initiallyGranted: Boolean = isGranted, +) + +class SuperuserGrantViewModel( + private val policyDB: PolicyDao +) : AsyncLoadViewModel() { + + private val _loading = MutableStateFlow(true) + val loading: StateFlow = _loading.asStateFlow() + + private val _allApps = MutableStateFlow>(emptyList()) + + private val _query = MutableStateFlow("") + val query: StateFlow = _query.asStateFlow() + + private val _showSystem = MutableStateFlow(false) + val showSystem: StateFlow = _showSystem.asStateFlow() + + private val _showOS = MutableStateFlow(false) + val showOS: StateFlow = _showOS.asStateFlow() + + private val _sortBy = MutableStateFlow(SortBy.NAME) + val sortBy: StateFlow = _sortBy.asStateFlow() + + private val _sortReverse = MutableStateFlow(false) + val sortReverse: StateFlow = _sortReverse.asStateFlow() + + var authenticate: (onSuccess: () -> Unit) -> Unit = { it() } + + val filteredApps: StateFlow> = combine( + _allApps, _query, _showSystem, _showOS, _sortBy, _sortReverse + ) { args -> + @Suppress("UNCHECKED_CAST") + val apps = args[0] as List + val q = args[1] as String + val showSys = args[2] as Boolean + val showOS = args[3] as Boolean + val sort = args[4] as SortBy + val reverse = args[5] as Boolean + + val filtered = apps.filter { app -> + val passFilter = app.isGranted || + app.initiallyGranted || + app.info.isShell || + ((showSys || !app.info.isSystemApp) && + ((showSys && showOS) || app.info.isApp)) + val passQuery = q.isBlank() || + app.info.label.contains(q, true) || + app.info.packageName.contains(q, true) || + (app.info.isShell && ("adb".startsWith(q.trim(), true) || q.trim().contains("adb", true))) + passFilter && passQuery + } + + val secondary: Comparator = when (sort) { + SortBy.NAME -> compareBy(String.CASE_INSENSITIVE_ORDER) { it.info.label } + .thenBy { it.info.packageName } + SortBy.PACKAGE_NAME -> compareBy(String.CASE_INSENSITIVE_ORDER) { it.info.packageName } + SortBy.INSTALL_TIME -> compareByDescending { it.info.firstInstallTime } + .thenBy(String.CASE_INSENSITIVE_ORDER) { it.info.label } + .thenBy { it.info.packageName } + SortBy.UPDATE_TIME -> compareByDescending { it.info.lastUpdateTime } + .thenBy(String.CASE_INSENSITIVE_ORDER) { it.info.label } + .thenBy { it.info.packageName } + } + val comparator = compareBy { !it.initiallyGranted } + .then(if (reverse) secondary.reversed() else secondary) + filtered.sortedWith(comparator) + }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList()) + + fun setQuery(q: String) { _query.value = q } + fun setShowSystem(v: Boolean) { + _showSystem.value = v + if (!v) _showOS.value = false + } + fun setShowOS(v: Boolean) { _showOS.value = v } + fun setSortBy(s: SortBy) { _sortBy.value = s } + fun toggleSortReverse() { _sortReverse.value = !_sortReverse.value } + + fun 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 + } + } + } + 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() + + val res = if (willGrant) CoreR.string.su_snack_grant else CoreR.string.su_snack_deny + showSnackbar(AppContext.getString(res, app.info.label)) + } + } + + if (Config.suAuth) { + authenticate { updateState() } + } else { + updateState() + } + } + + @SuppressLint("InlinedApi") + override suspend fun doLoadWork() { + if (_allApps.value.isNotEmpty()) return + _loading.value = true + val apps = withContext(Dispatchers.Default) { + val pm = AppContext.packageManager + withContext(Dispatchers.IO) { + policyDB.deleteOutdated() + } + val policies = withContext(Dispatchers.IO) { + policyDB.fetchAll() + }.associateBy { it.uid } + + val myUid = AppContext.applicationInfo.uid + val myPackage = AppContext.packageName + + val installed = runCatching { + pm.getInstalledApplications(MATCH_UNINSTALLED_PACKAGES) + }.getOrElse { emptyList() }.toMutableList() + + if (installed.none { it.packageName == SuGrantAppInfo.SHELL_PACKAGE }) { + runCatching { + pm.getApplicationInfo(SuGrantAppInfo.SHELL_PACKAGE, MATCH_UNINSTALLED_PACKAGES) + }.recoverCatching { + pm.getApplicationInfo(SuGrantAppInfo.SHELL_PACKAGE, 0) + }.recoverCatching { + pm.getPackageInfo(SuGrantAppInfo.SHELL_PACKAGE, MATCH_UNINSTALLED_PACKAGES).applicationInfo!! + }.getOrNull()?.let { installed.add(it) } + } + + installed + .distinctBy { it.packageName } + .asFlow() + .filter { + it.packageName != myPackage && + it.packageName != BuildConfig.APP_PACKAGE_NAME && + it.uid != myUid + } + .concurrentMap { appInfo -> + val pkg = try { + pm.getPackageInfo(appInfo.packageName, MATCH_UNINSTALLED_PACKAGES) + } catch (_: Exception) { + null + } + val isSharedUid = pkg?.sharedUserId != null + val label = appInfo.getLabel(pm) + val icon = runCatching { appInfo.loadIcon(pm) }.getOrDefault(pm.defaultActivityIcon) + val isSystemApp = (appInfo.flags and ApplicationInfo.FLAG_SYSTEM) != 0 + val isApp = ProcessCompat.isApplicationUid(appInfo.uid) + val suAppInfo = SuGrantAppInfo( + label = label, + packageName = appInfo.packageName, + icon = icon, + uid = appInfo.uid, + isSystemApp = isSystemApp, + isApp = isApp, + isSharedUid = isSharedUid, + firstInstallTime = pkg?.firstInstallTime ?: 0L, + lastUpdateTime = pkg?.lastUpdateTime ?: 0L, + ) + val policy = policies[appInfo.uid] + val isGranted = policy != null && policy.policy >= SuPolicy.ALLOW + SuGrantAppState( + info = suAppInfo, + isGranted = isGranted, + initiallyGranted = isGranted, + ) + } + .toCollection(ArrayList(installed.size)) + .apply { + sortWith(compareBy( + { !it.initiallyGranted }, + { it.info.label.lowercase(Locale.ROOT) }, + { it.info.packageName } + )) + } + } + _allApps.value = apps + _loading.value = false + } +} diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/superuser/SuperuserScreen.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/superuser/SuperuserScreen.kt index 9ee1d65f8..9310bc1a7 100644 --- a/app/apk/src/main/java/com/topjohnwu/magisk/ui/superuser/SuperuserScreen.kt +++ b/app/apk/src/main/java/com/topjohnwu/magisk/ui/superuser/SuperuserScreen.kt @@ -1,31 +1,23 @@ package com.topjohnwu.magisk.ui.superuser -import androidx.compose.foundation.Image -import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues -import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size -import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.rememberLazyListState -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material3.Badge -import androidx.compose.material3.Card -import androidx.compose.material3.CardDefaults +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Add import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.Icon -import androidx.compose.material3.ListItem -import androidx.compose.material3.ListItemDefaults import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Switch @@ -33,20 +25,19 @@ import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha -import androidx.compose.ui.draw.clip -import androidx.compose.ui.graphics.Color +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.input.nestedscroll.nestedScroll import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource -import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle -import com.google.accompanist.drawablepainter.rememberDrawablePainter import com.topjohnwu.magisk.ui.component.verticalScrollbar import com.topjohnwu.magisk.ui.navigation.LocalNavigator import com.topjohnwu.magisk.ui.navigation.Route @@ -56,12 +47,21 @@ import com.topjohnwu.magisk.core.R as CoreR @Composable fun SuperuserScreen( viewModel: SuperuserViewModel, - modifier: Modifier = Modifier + modifier: Modifier = Modifier, + onRegisterFab: (((() -> Unit)?) -> Unit)? = null, + contentFocusRequester: FocusRequester? = null, ) { val uiState by viewModel.uiState.collectAsStateWithLifecycle() val scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior() val navigator = LocalNavigator.current + DisposableEffect(onRegisterFab) { + onRegisterFab?.invoke { navigator.push(Route.SuperuserGrant) } + onDispose { + onRegisterFab?.invoke(null) + } + } + Scaffold( modifier = modifier, topBar = { @@ -69,6 +69,22 @@ fun SuperuserScreen( title = { Text(stringResource(CoreR.string.superuser)) }, scrollBehavior = scrollBehavior ) + }, + floatingActionButton = { + if (onRegisterFab == null) { + FloatingActionButton( + onClick = { navigator.push(Route.SuperuserGrant) }, + containerColor = MaterialTheme.colorScheme.primaryContainer, + contentColor = MaterialTheme.colorScheme.onPrimaryContainer, + content = { + Icon( + imageVector = Icons.Default.Add, + contentDescription = stringResource(CoreR.string.superuser_grant), + modifier = Modifier.size(28.dp), + ) + }, + ) + } } ) { padding -> if (uiState.loading) { @@ -119,8 +135,8 @@ fun SuperuserScreen( .fillMaxSize() .nestedScroll(scrollBehavior.nestedScrollConnection) .padding(padding) - .verticalScrollbar(listState, contentPadding = PaddingValues(vertical = 4.dp)), - contentPadding = PaddingValues(horizontal = 12.dp, vertical = 4.dp), + .verticalScrollbar(listState, contentPadding = PaddingValues(top = 4.dp, bottom = 80.dp)), + contentPadding = PaddingValues(start = 12.dp, top = 4.dp, end = 12.dp, bottom = 80.dp), verticalArrangement = Arrangement.spacedBy(8.dp) ) { item { Spacer(Modifier.height(4.dp)) } @@ -129,10 +145,14 @@ fun SuperuserScreen( key = { "${it.policy.uid}_${it.packageName}" }, contentType = { "PolicyCard" } ) { item -> + val isLast = item == uiState.policies.lastOrNull() PolicyCard( item = item, onToggle = { viewModel.togglePolicy(item) }, onDetail = { navigator.push(Route.SuperuserDetail(item.policy.uid)) }, + modifier = if (isLast && contentFocusRequester != null) { + Modifier.focusRequester(contentFocusRequester) + } else Modifier, ) } item { Spacer(Modifier.height(4.dp)) } @@ -147,65 +167,19 @@ private fun PolicyCard( onDetail: () -> Unit, modifier: Modifier = Modifier ) { - Card( + SuperuserAppCard( + icon = item.icon, + title = item.title, + packageName = item.packageName, + isSharedUid = item.isSharedUid, onClick = onDetail, - modifier = modifier - .fillMaxWidth() - .alpha(if (item.isEnabled) 1f else 0.5f), - shape = RoundedCornerShape(20.dp), - colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainerLow) - ) { - ListItem( - leadingContent = { - Image( - painter = rememberDrawablePainter(item.icon), - contentDescription = item.appName, - modifier = Modifier.size(40.dp) - ) - }, - headlineContent = { - Row(verticalAlignment = Alignment.CenterVertically) { - Text( - text = item.title, - style = MaterialTheme.typography.titleMedium, - modifier = Modifier.weight(1f, fill = false), - ) - if (item.isSharedUid) { - Spacer(Modifier.width(6.dp)) - SharedUidBadge() - } - } - }, - supportingContent = { - Text( - text = item.packageName, - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - }, - trailingContent = { - Switch( - checked = item.isEnabled, - onCheckedChange = { onToggle() } - ) - }, - colors = ListItemDefaults.colors(containerColor = Color.Transparent) - ) - } -} - -@Composable -internal fun SharedUidBadge(modifier: Modifier = Modifier) { - Badge( - modifier = modifier, - containerColor = MaterialTheme.colorScheme.secondaryContainer, - contentColor = MaterialTheme.colorScheme.onSecondaryContainer, - ) { - Text( - text = stringResource(CoreR.string.shared_uid), - style = MaterialTheme.typography.labelSmall, - fontWeight = FontWeight.SemiBold, - modifier = Modifier.padding(horizontal = 2.dp) - ) - } + contentDescription = item.appName, + modifier = modifier.alpha(if (item.isEnabled) 1f else 0.5f), + trailingContent = { + Switch( + checked = item.isEnabled, + onCheckedChange = { onToggle() } + ) + } + ) } diff --git a/app/core/src/main/res/values/strings.xml b/app/core/src/main/res/values/strings.xml index e83db2ebb..8cf88a956 100644 --- a/app/core/src/main/res/values/strings.xml +++ b/app/core/src/main/res/values/strings.xml @@ -60,6 +60,7 @@ Prompt Restrict Grant + Grant Superuser Grants full access to your device.\nDeny if you\'re not sure! Forever Once