diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/arch/BaseViewModel.kt b/app/apk/src/main/java/com/topjohnwu/magisk/arch/BaseViewModel.kt index 8cea8ad8a..c9a162c69 100644 --- a/app/apk/src/main/java/com/topjohnwu/magisk/arch/BaseViewModel.kt +++ b/app/apk/src/main/java/com/topjohnwu/magisk/arch/BaseViewModel.kt @@ -14,11 +14,11 @@ abstract class BaseViewModel : ViewModel() { private val _navEvents = MutableSharedFlow(extraBufferCapacity = 1) val navEvents: SharedFlow = _navEvents - fun showSnackbar(@StringRes resId: Int) { + fun showToast(@StringRes resId: Int) { AppContext.toast(resId, Toast.LENGTH_SHORT) } - fun showSnackbar(msg: String) { + fun showToast(msg: String) { AppContext.toast(msg, Toast.LENGTH_SHORT) } diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/terminal/TerminalProcess.kt b/app/apk/src/main/java/com/topjohnwu/magisk/terminal/TerminalProcess.kt index 8f93481c5..0ef246a87 100644 --- a/app/apk/src/main/java/com/topjohnwu/magisk/terminal/TerminalProcess.kt +++ b/app/apk/src/main/java/com/topjohnwu/magisk/terminal/TerminalProcess.kt @@ -1,8 +1,9 @@ package com.topjohnwu.magisk.terminal -import android.os.Handler -import android.os.Looper import com.topjohnwu.superuser.Shell +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch import timber.log.Timber private val busyboxPath: String by lazy { @@ -10,17 +11,17 @@ private val busyboxPath: String by lazy { ?: "/data/adb/magisk/busybox" } -private val mainHandler = Handler(Looper.getMainLooper()) +private val terminalScope = CoroutineScope(Dispatchers.Main.immediate) fun TerminalEmulator.appendOnMain(bytes: ByteArray, len: Int) { - mainHandler.post { + terminalScope.launch { append(bytes, len) onScreenUpdate?.invoke() } } fun TerminalEmulator.appendLineOnMain(line: String) { - mainHandler.post { + terminalScope.launch { val clear = if (inPlaceNewlines > 0) { "\r\u001b[${inPlaceNewlines}A\u001b[J" } else { @@ -43,14 +44,13 @@ fun TerminalEmulator.appendLineOnMain(line: String) { /** * Run a command as root inside a PTY (via busybox script). * Reads raw bytes from the process and feeds them to the terminal emulator. - * Must be called from a background thread. + * Must be called from a background thread. [columns] and [rows] should be read from the + * emulator on the main thread, after the terminal has been sized to its viewport. * Returns true if the process exits with code 0. */ -fun runSuCommand(emulator: TerminalEmulator, command: String): Boolean { +fun runSuCommand(emulator: TerminalEmulator, columns: Int, rows: Int, command: String): Boolean { return try { - val cols = emulator.mColumns - val rows = emulator.mRows - val wrappedCmd = "export TERM=xterm-256color; stty cols $cols rows $rows 2>/dev/null; $command" + val wrappedCmd = "export TERM=xterm-256color; stty cols $columns rows $rows 2>/dev/null; $command" val escapedCmd = wrappedCmd.replace("'", "'\\''") val process = ProcessBuilder( 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 3d57ea538..c5b57d9a8 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 @@ -231,7 +231,9 @@ fun MainScreen( ) { page -> val isCurrentPage = pagerState.currentPage == page val childOwner = rememberNavigationEventDispatcherOwner(enabled = isCurrentPage) - CompositionLocalProvider(LocalNavigationEventDispatcherOwner provides childOwner) { + CompositionLocalProvider( + LocalNavigationEventDispatcherOwner provides childOwner, + ) { val tab = visibleTabs[page] Box( modifier = Modifier @@ -285,6 +287,7 @@ fun MainScreen( SuperuserScreen( viewModel = vm, onRegisterFab = { superuserFabAction = it }, + isFabAtBottom = isBar, contentFocusRequester = superuserContentFocusRequester, ) } @@ -304,6 +307,7 @@ fun MainScreen( ModuleScreen( viewModel = vm, onRegisterFab = { moduleFabAction = it }, + isFabAtBottom = isBar, contentFocusRequester = moduleContentFocusRequester, ) } diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/component/AppIcon.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/component/AppIcon.kt new file mode 100644 index 000000000..ac4f9a86f --- /dev/null +++ b/app/apk/src/main/java/com/topjohnwu/magisk/ui/component/AppIcon.kt @@ -0,0 +1,66 @@ +package com.topjohnwu.magisk.ui.component + +import android.content.Context +import android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES +import android.graphics.drawable.Drawable +import android.util.LruCache +import androidx.compose.foundation.Image +import androidx.compose.foundation.layout.Box +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import com.google.accompanist.drawablepainter.rememberDrawablePainter +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext + +private class CachedIcon(val lastUpdateTime: Long, val drawable: Drawable) + +// Keep recently shown icons so scrolling back through long app lists doesn't reload them +private val iconCache = LruCache(128) + +/** + * Returns the icon of [packageName], reusing the cached one unless the package has been + * updated since it was loaded. + */ +private fun loadAppIcon(context: Context, packageName: String): Drawable { + val pm = context.packageManager + // Lists include apps that are only installed for other users + val info = runCatching { pm.getPackageInfo(packageName, MATCH_UNINSTALLED_PACKAGES) }.getOrNull() + ?: return pm.defaultActivityIcon + iconCache[packageName]?.let { cached -> + if (cached.lastUpdateTime == info.lastUpdateTime) return cached.drawable + } + val icon = info.applicationInfo?.loadIcon(pm) ?: pm.defaultActivityIcon + iconCache.put(packageName, CachedIcon(info.lastUpdateTime, icon)) + return icon +} + +@Composable +fun AppIcon( + packageName: String, + modifier: Modifier = Modifier, + contentDescription: String? = null, +) { + val context = LocalContext.current + // Show the cached icon right away, then make sure it is still up to date + var drawable by remember(packageName) { mutableStateOf(iconCache[packageName]?.drawable) } + LaunchedEffect(packageName) { + drawable = withContext(Dispatchers.IO) { loadAppIcon(context, packageName) } + } + val icon = drawable + if (icon == null) { + // Reserve the space while loading + Box(modifier = modifier) + } else { + Image( + painter = rememberDrawablePainter(icon), + contentDescription = contentDescription, + modifier = modifier, + ) + } +} diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/component/AppSortFilter.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/component/AppSortFilter.kt new file mode 100644 index 000000000..18a239c15 --- /dev/null +++ b/app/apk/src/main/java/com/topjohnwu/magisk/ui/component/AppSortFilter.kt @@ -0,0 +1,120 @@ +package com.topjohnwu.magisk.ui.component + +import androidx.annotation.StringRes +import androidx.compose.foundation.layout.Box +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.Sort +import androidx.compose.material.icons.filled.Check +import androidx.compose.material.icons.filled.Tune +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.Text +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.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.DpOffset +import androidx.compose.ui.unit.dp +import com.topjohnwu.magisk.core.R as CoreR + +enum class AppSortBy(@StringRes val labelRes: Int) { + NAME(CoreR.string.sort_by_name), + PACKAGE_NAME(CoreR.string.sort_by_package_name), + INSTALL_TIME(CoreR.string.sort_by_install_time), + UPDATE_TIME(CoreR.string.sort_by_update_time); +} + +@Composable +fun AppSortFilterActions( + sortBy: AppSortBy, + sortReverse: Boolean, + onSortByChanged: (AppSortBy) -> Unit, + onToggleSortReverse: () -> Unit, + showSystem: Boolean, + showOS: Boolean, + onShowSystemChanged: (Boolean) -> Unit, + onShowOSChanged: (Boolean) -> Unit, + modifier: Modifier = Modifier, +) { + var showSortMenu by remember { mutableStateOf(false) } + var showFilterMenu by remember { mutableStateOf(false) } + + Box(modifier) { + IconButton(onClick = { showSortMenu = true }) { + Icon( + imageVector = Icons.AutoMirrored.Filled.Sort, + contentDescription = stringResource(CoreR.string.menu_sort), + ) + } + DropdownMenu( + expanded = showSortMenu, + onDismissRequest = { showSortMenu = false } + ) { + AppSortBy.entries.forEach { sort -> + DropdownMenuItem( + text = { Text(stringResource(sort.labelRes)) }, + trailingIcon = if (sortBy == sort) { + { Icon(Icons.Default.Check, contentDescription = null) } + } else null, + onClick = { + onSortByChanged(sort) + showSortMenu = false + } + ) + } + DropdownMenuItem( + text = { Text(stringResource(CoreR.string.sort_reverse)) }, + trailingIcon = if (sortReverse) { + { Icon(Icons.Default.Check, contentDescription = null) } + } else null, + onClick = { + onToggleSortReverse() + 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 = { + onShowSystemChanged(!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) { + onShowSystemChanged(true) + } + onShowOSChanged(!showOS) + showFilterMenu = false + } + ) + } + } +} diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/component/Permissions.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/component/Permissions.kt index 33dbb871a..e06054c7d 100644 --- a/app/apk/src/main/java/com/topjohnwu/magisk/ui/component/Permissions.kt +++ b/app/apk/src/main/java/com/topjohnwu/magisk/ui/component/Permissions.kt @@ -1,14 +1,18 @@ package com.topjohnwu.magisk.ui.component import android.Manifest.permission.WRITE_EXTERNAL_STORAGE +import android.content.pm.PackageManager +import android.os.Build import android.widget.Toast +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.platform.LocalContext +import androidx.core.content.ContextCompat import com.topjohnwu.magisk.core.R -import com.topjohnwu.magisk.core.base.IActivityExtension import com.topjohnwu.magisk.core.ktx.toast @Composable @@ -16,14 +20,24 @@ fun rememberExternalStoragePermissionLauncher(onGranted: () -> Unit): () -> Unit val context = LocalContext.current val currentOnGranted by rememberUpdatedState(onGranted) - return remember(context) { + val launcher = rememberLauncherForActivityResult( + contract = ActivityResultContracts.RequestPermission() + ) { granted -> + if (granted) { + currentOnGranted() + } else { + context.toast(R.string.external_rw_permission_denied, Toast.LENGTH_SHORT) + } + } + + return remember(launcher, context) { { - (context as IActivityExtension).withPermission(WRITE_EXTERNAL_STORAGE) { granted -> - if (granted) { - currentOnGranted() - } else { - context.toast(R.string.external_rw_permission_denied, Toast.LENGTH_SHORT) - } + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R || + ContextCompat.checkSelfPermission(context, WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED + ) { + currentOnGranted() + } else { + launcher.launch(WRITE_EXTERNAL_STORAGE) } } } diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/component/Scrollbar.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/component/Scrollbar.kt index 5b08cb1bc..2207a0228 100644 --- a/app/apk/src/main/java/com/topjohnwu/magisk/ui/component/Scrollbar.kt +++ b/app/apk/src/main/java/com/topjohnwu/magisk/ui/component/Scrollbar.kt @@ -163,20 +163,21 @@ fun rememberScrollbarAdapter(state: ScrollableState): ScrollbarStateAdapter { @Composable fun rememberTerminalScrollbarAdapter( - activeTranscriptRows: Int, - topRow: Int, + activeTranscriptRowsProvider: () -> Int, + topRowProvider: () -> Int, visibleRows: Int, onScrollToRow: (Int) -> Unit ): ScrollbarStateAdapter { val currentOnScroll = rememberUpdatedState(onScrollToRow) - return remember(activeTranscriptRows, topRow, visibleRows) { + return remember(visibleRows) { object : ScrollbarStateAdapter { override val isScrollable: Boolean - get() = activeTranscriptRows > 0 + get() = activeTranscriptRowsProvider() > 0 override val thumbRatio: Float get() { - val totalRows = activeTranscriptRows + visibleRows + val activeRows = activeTranscriptRowsProvider() + val totalRows = activeRows + visibleRows return if (totalRows > 0) { (visibleRows.toFloat() / totalRows.toFloat()).coerceIn(0.08f, 1f) } else 1f @@ -184,14 +185,16 @@ fun rememberTerminalScrollbarAdapter( override val offsetRatio: Float get() { - return if (activeTranscriptRows > 0) { - ((activeTranscriptRows + topRow).toFloat() / activeTranscriptRows.toFloat()).coerceIn(0f, 1f) + val activeRows = activeTranscriptRowsProvider() + return if (activeRows > 0) { + ((activeRows + topRowProvider()).toFloat() / activeRows.toFloat()).coerceIn(0f, 1f) } else 0f } override suspend fun scrollTo(fraction: Float) { - if (activeTranscriptRows > 0) { - val target = (-activeTranscriptRows * (1f - fraction.coerceIn(0f, 1f))).roundToInt().coerceIn(-activeTranscriptRows, 0) + val activeRows = activeTranscriptRowsProvider() + if (activeRows > 0) { + val target = (-activeRows * (1f - fraction.coerceIn(0f, 1f))).roundToInt().coerceIn(-activeRows, 0) currentOnScroll.value(target) } } @@ -201,19 +204,20 @@ fun rememberTerminalScrollbarAdapter( @Composable fun rememberTerminalHorizontalScrollbarAdapter( - scrollX: Float, - maxScrollX: Float, + scrollXProvider: () -> Float, + maxScrollXProvider: () -> Float, viewportWidth: Float, onScrollToX: (Float) -> Unit, ): ScrollbarStateAdapter { val currentOnScroll = rememberUpdatedState(onScrollToX) - return remember(scrollX, maxScrollX, viewportWidth) { + return remember(viewportWidth) { object : ScrollbarStateAdapter { override val isScrollable: Boolean - get() = maxScrollX > 0f + get() = maxScrollXProvider() > 0f override val thumbRatio: Float get() { + val maxScrollX = maxScrollXProvider() val totalWidth = viewportWidth + maxScrollX return if (totalWidth > 0f) { (viewportWidth / totalWidth).coerceIn(0.08f, 1f) @@ -222,12 +226,14 @@ fun rememberTerminalHorizontalScrollbarAdapter( override val offsetRatio: Float get() { + val maxScrollX = maxScrollXProvider() return if (maxScrollX > 0f) { - (scrollX / maxScrollX).coerceIn(0f, 1f) + (scrollXProvider() / maxScrollX).coerceIn(0f, 1f) } else 0f } override suspend fun scrollTo(fraction: Float) { + val maxScrollX = maxScrollXProvider() if (maxScrollX > 0f) { currentOnScroll.value(fraction.coerceIn(0f, 1f) * maxScrollX) } @@ -279,8 +285,8 @@ fun Modifier.verticalScrollbar( } fun Modifier.terminalScrollbar( - activeTranscriptRows: Int, - topRow: Int, + activeTranscriptRowsProvider: () -> Int, + topRowProvider: () -> Int, visibleRows: Int, onScrollToRow: (Int) -> Unit, isScrollInProgress: Boolean = false, @@ -288,8 +294,8 @@ fun Modifier.terminalScrollbar( thumbColor: Color? = null, ): Modifier = composed { val adapter = rememberTerminalScrollbarAdapter( - activeTranscriptRows = activeTranscriptRows, - topRow = topRow, + activeTranscriptRowsProvider = activeTranscriptRowsProvider, + topRowProvider = topRowProvider, visibleRows = visibleRows, onScrollToRow = onScrollToRow ) @@ -302,8 +308,8 @@ fun Modifier.terminalScrollbar( } fun Modifier.terminalHorizontalScrollbar( - scrollX: Float, - maxScrollX: Float, + scrollXProvider: () -> Float, + maxScrollXProvider: () -> Float, viewportWidth: Float, onScrollToX: (Float) -> Unit, isScrollInProgress: Boolean = false, @@ -311,8 +317,8 @@ fun Modifier.terminalHorizontalScrollbar( thumbColor: Color? = null, ): Modifier = composed { val adapter = rememberTerminalHorizontalScrollbarAdapter( - scrollX = scrollX, - maxScrollX = maxScrollX, + scrollXProvider = scrollXProvider, + maxScrollXProvider = maxScrollXProvider, viewportWidth = viewportWidth, onScrollToX = onScrollToX, ) diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/deny/AppProcessInfo.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/deny/AppProcessInfo.kt index 5b53ccc4f..7f9728a10 100644 --- a/app/apk/src/main/java/com/topjohnwu/magisk/ui/deny/AppProcessInfo.kt +++ b/app/apk/src/main/java/com/topjohnwu/magisk/ui/deny/AppProcessInfo.kt @@ -11,8 +11,8 @@ import android.content.pm.PackageManager.GET_SERVICES import android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS import android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES import android.content.pm.ServiceInfo -import android.graphics.drawable.Drawable import android.os.Process +import androidx.compose.runtime.Immutable import com.topjohnwu.magisk.core.ktx.getLabel import java.util.Locale import java.util.TreeSet @@ -32,114 +32,125 @@ const val ISOLATED_MAGIC = "isolated" const val WEBVIEW_ZYGOTE_MAGIC = "webview_zygote" const val WEBVIEW_ZYGOTE_UID = 1053 +@Immutable +data class ProcessInfo( + val name: String, + val packageName: String, + val isEnabled: Boolean, +) { + val isIsolated: Boolean = packageName == ISOLATED_MAGIC +} + +@Immutable @SuppressLint("InlinedApi") -class AppProcessInfo( - private val info: ApplicationInfo, - pm: PackageManager, - denyList: List, - private val labelOverride: String? = null, - private val processesOverride: Collection? = null, +data class AppProcessInfo( + val packageName: String, + val label: String, + val isSystemApp: Boolean, + val isApp: Boolean, + val firstInstallTime: Long, + val lastUpdateTime: Long, + val processes: List, ) : Comparable { - private val denyList = denyList.filter { - it.packageName == info.packageName || it.packageName == ISOLATED_MAGIC - } - - val label = labelOverride ?: info.getLabel(pm) - val iconImage: Drawable = runCatching { info.loadIcon(pm) }.getOrDefault(pm.defaultActivityIcon) - val packageName: String get() = info.packageName - var firstInstallTime: Long = 0L - private set - var lastUpdateTime: Long = 0L - private set - val processes = processesOverride ?: fetchProcesses(pm) - - override fun compareTo(other: AppProcessInfo) = comparator.compare(this, other) - - fun isSystemApp() = info.flags and ApplicationInfo.FLAG_SYSTEM != 0 - - fun isApp() = packageName == WEBVIEW_ZYGOTE_MAGIC || Process.isApplicationUid(info.uid) - - private fun createProcess(name: String, pkg: String = info.packageName) = - ProcessInfo(name, pkg, denyList.any { it.process == name && it.packageName == pkg }) - - private fun ComponentInfo.getProcName(): String = processName - ?: applicationInfo.processName - ?: applicationInfo.packageName - - private val ServiceInfo.isIsolated get() = (flags and ServiceInfo.FLAG_ISOLATED_PROCESS) != 0 - private val ServiceInfo.useAppZygote get() = (flags and ServiceInfo.FLAG_USE_APP_ZYGOTE) != 0 - - private fun Array?.toProcessList() = - orEmpty().map { createProcess(it.getProcName()) } - - private fun Array?.toProcessList(): List { - if (this == null) return emptyList() - val result = mutableListOf() - var hasIsolated = false - for (si in this) { - if (si.isIsolated) { - if (si.useAppZygote) { - val proc = info.processName ?: info.packageName - result.add(createProcess("${proc}_zygote")) - } else { - hasIsolated = true - } - } else { - result.add(createProcess(si.getProcName())) - } - } - if (hasIsolated) { - val prefix = "${info.processName ?: info.packageName}:" - val isEnabled = denyList.any { - it.packageName == ISOLATED_MAGIC && it.process.startsWith(prefix) - } - result.add(ProcessInfo(prefix, ISOLATED_MAGIC, isEnabled)) - } - return result - } - - private fun fetchProcesses(pm: PackageManager): Collection { - val flag = MATCH_DISABLED_COMPONENTS or MATCH_UNINSTALLED_PACKAGES or - GET_ACTIVITIES or GET_SERVICES or GET_RECEIVERS or GET_PROVIDERS - val packageInfo = try { - pm.getPackageInfo(info.packageName, flag) - } catch (e: Exception) { - // Exceed binder data transfer limit, parse the package locally - pm.getPackageArchiveInfo(info.sourceDir, flag) ?: return emptyList() - } - - firstInstallTime = packageInfo.firstInstallTime - lastUpdateTime = packageInfo.lastUpdateTime - - val processSet = TreeSet(compareBy({ it.name }, { it.isIsolated })) - processSet += packageInfo.activities.toProcessList() - processSet += packageInfo.services.toProcessList() - processSet += packageInfo.receivers.toProcessList() - processSet += packageInfo.providers.toProcessList() - return processSet - } + override fun compareTo(other: AppProcessInfo): Int = comparator.compare(this, other) companion object { + operator fun invoke( + info: ApplicationInfo, + pm: PackageManager, + denyList: List, + ): AppProcessInfo { + val appDenyList = denyList.filter { + it.packageName == info.packageName || it.packageName == ISOLATED_MAGIC + } + + fun createProcess(name: String, pkg: String = info.packageName) = + ProcessInfo(name, pkg, appDenyList.any { it.process == name && it.packageName == pkg }) + + fun ComponentInfo.getProcName(): String = processName + ?: applicationInfo.processName + ?: applicationInfo.packageName + + fun Array?.toProcessList() = + orEmpty().map { createProcess(it.getProcName()) } + + fun Array?.toServiceProcessList(): List { + if (this == null) return emptyList() + val result = mutableListOf() + var hasIsolated = false + for (si in this) { + val isIsolated = (si.flags and ServiceInfo.FLAG_ISOLATED_PROCESS) != 0 + val useAppZygote = (si.flags and ServiceInfo.FLAG_USE_APP_ZYGOTE) != 0 + if (isIsolated) { + if (useAppZygote) { + val proc = info.processName ?: info.packageName + result.add(createProcess("${proc}_zygote")) + } else { + hasIsolated = true + } + } else { + result.add(createProcess(si.getProcName())) + } + } + if (hasIsolated) { + val prefix = "${info.processName ?: info.packageName}:" + val isEnabled = appDenyList.any { + it.packageName == ISOLATED_MAGIC && it.process.startsWith(prefix) + } + result.add(ProcessInfo(prefix, ISOLATED_MAGIC, isEnabled)) + } + return result + } + + val flag = MATCH_DISABLED_COMPONENTS or MATCH_UNINSTALLED_PACKAGES or + GET_ACTIVITIES or GET_SERVICES or GET_RECEIVERS or GET_PROVIDERS + val packageInfo = try { + pm.getPackageInfo(info.packageName, flag) + } catch (e: Exception) { + // Exceed binder data transfer limit, parse the package locally + pm.getPackageArchiveInfo(info.sourceDir, flag) + } + + val firstInstallTime = packageInfo?.firstInstallTime ?: 0L + val lastUpdateTime = packageInfo?.lastUpdateTime ?: 0L + + val processSet = TreeSet(compareBy({ it.name }, { it.isIsolated })) + if (packageInfo != null) { + processSet += packageInfo.activities.toProcessList() + processSet += packageInfo.services.toServiceProcessList() + processSet += packageInfo.receivers.toProcessList() + processSet += packageInfo.providers.toProcessList() + } + + return AppProcessInfo( + packageName = info.packageName, + label = info.getLabel(pm), + isSystemApp = info.flags and ApplicationInfo.FLAG_SYSTEM != 0, + isApp = Process.isApplicationUid(info.uid), + firstInstallTime = firstInstallTime, + lastUpdateTime = lastUpdateTime, + processes = processSet.toList(), + ) + } + fun webViewZygote( pm: PackageManager, denyList: List, label: String, ): AppProcessInfo { - val info = ApplicationInfo().apply { - packageName = WEBVIEW_ZYGOTE_MAGIC - uid = WEBVIEW_ZYGOTE_UID - } val enabled = denyList.any { it.packageName == WEBVIEW_ZYGOTE_MAGIC && it.process == WEBVIEW_ZYGOTE_MAGIC } return AppProcessInfo( - info, - pm, - denyList, - labelOverride = label, - processesOverride = listOf( + packageName = WEBVIEW_ZYGOTE_MAGIC, + label = label, + isSystemApp = false, + isApp = true, + firstInstallTime = 0L, + lastUpdateTime = 0L, + processes = listOf( ProcessInfo(WEBVIEW_ZYGOTE_MAGIC, WEBVIEW_ZYGOTE_MAGIC, enabled) ), ) @@ -147,15 +158,7 @@ class AppProcessInfo( private val comparator = compareBy( { it.label.lowercase(Locale.ROOT) }, - { it.info.packageName } + { it.packageName } ) } } - -data class ProcessInfo( - val name: String, - val packageName: String, - var isEnabled: Boolean -) { - val isIsolated = packageName == ISOLATED_MAGIC -} diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/deny/DenyListScreen.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/deny/DenyListScreen.kt index 2184499e5..e2e58527d 100644 --- a/app/apk/src/main/java/com/topjohnwu/magisk/ui/deny/DenyListScreen.kt +++ b/app/apk/src/main/java/com/topjohnwu/magisk/ui/deny/DenyListScreen.kt @@ -72,7 +72,8 @@ import androidx.compose.ui.state.ToggleableState import androidx.compose.ui.unit.DpOffset import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle -import com.google.accompanist.drawablepainter.rememberDrawablePainter +import com.topjohnwu.magisk.ui.component.AppIcon +import com.topjohnwu.magisk.ui.component.AppSortFilterActions import com.topjohnwu.magisk.ui.component.verticalScrollbar import com.topjohnwu.magisk.core.R as CoreR @@ -91,9 +92,6 @@ fun DenyListScreen( 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 searchBackState = rememberNavigationEventState(currentInfo = NavigationEventInfo.None) NavigationBackHandler( state = searchBackState, @@ -126,89 +124,16 @@ fun DenyListScreen( } }, 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 - } - ) - } - } + AppSortFilterActions( + sortBy = sortBy, + sortReverse = sortReverse, + onSortByChanged = { viewModel.setSortBy(it) }, + onToggleSortReverse = { viewModel.toggleSortReverse() }, + showSystem = showSystem, + showOS = showOS, + onShowSystemChanged = { viewModel.setShowSystem(it) }, + onShowOSChanged = { viewModel.setShowOS(it) }, + ) }, scrollBehavior = scrollBehavior ) @@ -347,8 +272,8 @@ private fun DenyAppCard( .padding(14.dp), verticalAlignment = Alignment.CenterVertically ) { - Image( - painter = rememberDrawablePainter(app.info.iconImage), + AppIcon( + packageName = app.info.packageName, contentDescription = app.info.label, modifier = Modifier.size(40.dp) ) diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/deny/DenyListViewModel.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/deny/DenyListViewModel.kt index 24220a15c..c74953920 100644 --- a/app/apk/src/main/java/com/topjohnwu/magisk/ui/deny/DenyListViewModel.kt +++ b/app/apk/src/main/java/com/topjohnwu/magisk/ui/deny/DenyListViewModel.kt @@ -1,10 +1,12 @@ package com.topjohnwu.magisk.ui.deny import android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES +import androidx.compose.runtime.Immutable import androidx.lifecycle.viewModelScope import com.topjohnwu.magisk.arch.AsyncLoadViewModel import com.topjohnwu.magisk.core.AppContext import com.topjohnwu.magisk.core.ktx.concurrentMap +import com.topjohnwu.magisk.ui.component.AppSortBy import com.topjohnwu.superuser.Shell import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow @@ -19,8 +21,7 @@ import kotlinx.coroutines.flow.toCollection import kotlinx.coroutines.flow.update import kotlinx.coroutines.withContext -enum class SortBy { NAME, PACKAGE_NAME, INSTALL_TIME, UPDATE_TIME } - +@Immutable data class DenyProcessState( val process: ProcessInfo, val isEnabled: Boolean = process.isEnabled, @@ -29,6 +30,7 @@ data class DenyProcessState( if (process.isIsolated) "(isolated) ${process.name}*" else process.name } +@Immutable data class DenyAppState( val info: AppProcessInfo, val processes: List = info.processes.map { DenyProcessState(it) }, @@ -66,8 +68,8 @@ class DenyListViewModel : AsyncLoadViewModel() { private val _showOS = MutableStateFlow(false) val showOS: StateFlow = _showOS.asStateFlow() - private val _sortBy = MutableStateFlow(SortBy.NAME) - val sortBy: StateFlow = _sortBy.asStateFlow() + private val _sortBy = MutableStateFlow(AppSortBy.NAME) + val sortBy: StateFlow = _sortBy.asStateFlow() private val _sortReverse = MutableStateFlow(false) val sortReverse: StateFlow = _sortReverse.asStateFlow() @@ -80,14 +82,14 @@ class DenyListViewModel : AsyncLoadViewModel() { 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 sort = args[4] as AppSortBy val reverse = args[5] as Boolean val filtered = apps.filter { app -> val passFilter = app.isChecked || app.initiallyChecked || - ((showSys || !app.info.isSystemApp()) && - ((showSys && showOS) || app.info.isApp())) + ((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) || @@ -96,10 +98,10 @@ class DenyListViewModel : AsyncLoadViewModel() { } val secondary: Comparator = when (sort) { - SortBy.NAME -> compareBy(String.CASE_INSENSITIVE_ORDER) { it.info.label } - SortBy.PACKAGE_NAME -> compareBy(String.CASE_INSENSITIVE_ORDER) { it.info.packageName } - SortBy.INSTALL_TIME -> compareByDescending { it.info.firstInstallTime } - SortBy.UPDATE_TIME -> compareByDescending { it.info.lastUpdateTime } + AppSortBy.NAME -> compareBy(String.CASE_INSENSITIVE_ORDER) { it.info.label } + AppSortBy.PACKAGE_NAME -> compareBy(String.CASE_INSENSITIVE_ORDER) { it.info.packageName } + AppSortBy.INSTALL_TIME -> compareByDescending { it.info.firstInstallTime } + AppSortBy.UPDATE_TIME -> compareByDescending { it.info.lastUpdateTime } } val comparator = compareBy { !it.initiallyChecked } .then(if (reverse) secondary.reversed() else secondary) @@ -112,7 +114,7 @@ class DenyListViewModel : AsyncLoadViewModel() { if (!v) _showOS.value = false } fun setShowOS(v: Boolean) { _showOS.value = v } - fun setSortBy(s: SortBy) { _sortBy.value = s } + fun setSortBy(s: AppSortBy) { _sortBy.value = s } fun toggleSortReverse() { _sortReverse.value = !_sortReverse.value } fun toggleExpanded(app: DenyAppState) { diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/flash/FlashScreen.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/flash/FlashScreen.kt index 505af81f2..971fd0f9a 100644 --- a/app/apk/src/main/java/com/topjohnwu/magisk/ui/flash/FlashScreen.kt +++ b/app/apk/src/main/java/com/topjohnwu/magisk/ui/flash/FlashScreen.kt @@ -118,10 +118,11 @@ fun FlashScreen( } ) { padding -> TerminalScreen( + emulator = viewModel.emulator, modifier = Modifier .fillMaxSize() .padding(padding), - onEmulatorCreated = { viewModel.onEmulatorCreated(it) }, + onResized = viewModel::onTerminalResized, ) } } diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/flash/FlashViewModel.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/flash/FlashViewModel.kt index e5ae6c9fc..d23d525f5 100644 --- a/app/apk/src/main/java/com/topjohnwu/magisk/ui/flash/FlashViewModel.kt +++ b/app/apk/src/main/java/com/topjohnwu/magisk/ui/flash/FlashViewModel.kt @@ -50,19 +50,26 @@ class FlashViewModel : BaseViewModel() { var flashUri: Uri? = null var usbDevice: String? = null - private var emulator: TerminalEmulator? = null - private val emulatorReady = CompletableDeferred() + val emulator = TerminalEmulator( + columns = 256, + rows = 40, + cellWidthPixels = 0, + cellHeightPixels = 0, + transcriptRows = null, + ) - fun onEmulatorCreated(emu: TerminalEmulator) { - emulator = emu - emulatorReady.complete(emu) + private val terminalReady = CompletableDeferred() + + /** Called by the UI once the terminal has been sized to its viewport. */ + fun onTerminalResized() { + terminalReady.complete(Unit) } private val logItems = mutableListOf().synchronized() private val outItems = object : CallbackList() { override fun onAddElement(e: String?) { e ?: return - emulator?.appendLineOnMain(e) + emulator.appendLineOnMain(e) if (!e.startsWith('\r')) { logItems.add(e) } @@ -77,11 +84,10 @@ class FlashViewModel : BaseViewModel() { val usb = usbDevice viewModelScope.launch { - val emu = emulatorReady.await() when (action) { Const.Value.FLASH_ZIP -> { uri ?: return@launch - flashZip(emu, uri) + flashZip(emulator, uri) } Const.Value.UNINSTALL -> { _showReboot.value = false @@ -158,9 +164,13 @@ class FlashViewModel : BaseViewModel() { val (dir, zipFile, displayName) = prepResult + // Start the installer with the real terminal size + terminalReady.await() + val columns = emu.mColumns + val rows = emu.mRows val success = withContext(Dispatchers.IO) { runSuCommand( - emu, + emu, columns, rows, "echo '- Installing $displayName'; " + "sh $dir/update-binary dummy 1 '${zipFile.absolutePath}'; " + "EXIT=\$?; " + @@ -180,8 +190,8 @@ class FlashViewModel : BaseViewModel() { ) val file = MediaStoreUtils.getFile(name) file.uri.outputStream().bufferedWriter().use { writer -> - val transcript = emulator?.screen?.transcriptText - if (flashAction == Const.Value.FLASH_ZIP && transcript != null) { + val transcript = emulator.screen.transcriptText + if (flashAction == Const.Value.FLASH_ZIP) { writer.write(transcript) } else { synchronized(logItems) { @@ -192,7 +202,7 @@ class FlashViewModel : BaseViewModel() { } } } - showSnackbar(file.toString()) + showToast(file.toString()) } } diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/home/HomeScreen.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/home/HomeScreen.kt index 9688bfdcc..3cdf35e48 100644 --- a/app/apk/src/main/java/com/topjohnwu/magisk/ui/home/HomeScreen.kt +++ b/app/apk/src/main/java/com/topjohnwu/magisk/ui/home/HomeScreen.kt @@ -1,8 +1,6 @@ package com.topjohnwu.magisk.ui.home import android.os.Build -import android.os.Handler -import android.os.Looper import android.os.PowerManager import android.widget.Toast import androidx.compose.foundation.background @@ -95,7 +93,10 @@ import com.topjohnwu.magisk.ui.install.InstallDialog import com.topjohnwu.magisk.ui.install.InstallViewModel import com.topjohnwu.magisk.ui.navigation.LocalNavigator import com.topjohnwu.magisk.ui.navigation.Route +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.delay import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext import java.io.File import com.topjohnwu.magisk.core.R as CoreR @@ -193,9 +194,11 @@ fun HomeScreen( Toast.LENGTH_LONG ) if (success) { - @Suppress("DEPRECATION") - Handler(Looper.getMainLooper()) - .postDelayed({ reboot() }, 5000) + // The reboot toast has been shown; don't let leaving this screen cancel it + withContext(NonCancellable) { + delay(5000) + reboot() + } } } } diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/home/HomeViewModel.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/home/HomeViewModel.kt index 768edb26a..25ee26a46 100644 --- a/app/apk/src/main/java/com/topjohnwu/magisk/ui/home/HomeViewModel.kt +++ b/app/apk/src/main/java/com/topjohnwu/magisk/ui/home/HomeViewModel.kt @@ -123,8 +123,8 @@ class HomeViewModel( fun onManagerPressed() { when (_uiState.value.appState) { - State.LOADING -> showSnackbar(CoreR.string.loading) - State.INVALID -> showSnackbar(CoreR.string.no_connection) + State.LOADING -> showToast(CoreR.string.loading) + State.INVALID -> showToast(CoreR.string.no_connection) else -> _uiState.update { it.copy(showManagerInstall = true) } } } diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/log/LogViewModel.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/log/LogViewModel.kt index 5c49ae01d..667aff472 100644 --- a/app/apk/src/main/java/com/topjohnwu/magisk/ui/log/LogViewModel.kt +++ b/app/apk/src/main/java/com/topjohnwu/magisk/ui/log/LogViewModel.kt @@ -93,18 +93,18 @@ class LogViewModel( ProcessBuilder("logcat", "-d").start() .inputStream.reader().use { it.copyTo(file) } } - showSnackbar(logFile.toString()) + showToast(logFile.toString()) } } fun clearMagiskLog() = repo.clearMagiskLogs { - showSnackbar(R.string.logs_cleared) + showToast(R.string.logs_cleared) startLoading() } fun clearLog() = viewModelScope.launch { repo.clearLogs() - showSnackbar(R.string.logs_cleared) + showToast(R.string.logs_cleared) startLoading() } } diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/module/ActionScreen.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/module/ActionScreen.kt index 848ba7db4..2b4c2e9cd 100644 --- a/app/apk/src/main/java/com/topjohnwu/magisk/ui/module/ActionScreen.kt +++ b/app/apk/src/main/java/com/topjohnwu/magisk/ui/module/ActionScreen.kt @@ -103,10 +103,11 @@ fun ActionScreen( } ) { padding -> TerminalScreen( + emulator = viewModel.emulator, modifier = Modifier .fillMaxSize() .padding(padding), - onEmulatorCreated = { viewModel.onEmulatorCreated(it) }, + onResized = viewModel::onTerminalResized, ) } } diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/module/ActionViewModel.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/module/ActionViewModel.kt index efd0bbf90..83fa32252 100644 --- a/app/apk/src/main/java/com/topjohnwu/magisk/ui/module/ActionViewModel.kt +++ b/app/apk/src/main/java/com/topjohnwu/magisk/ui/module/ActionViewModel.kt @@ -28,21 +28,30 @@ class ActionViewModel : BaseViewModel() { var actionId: String = "" var actionName: String = "" - private var emulator: TerminalEmulator? = null - private val emulatorReady = CompletableDeferred() + val emulator = TerminalEmulator( + columns = 256, + rows = 40, + cellWidthPixels = 0, + cellHeightPixels = 0, + transcriptRows = null, + ) - fun onEmulatorCreated(emu: TerminalEmulator) { - emulator = emu - emulatorReady.complete(emu) + private val terminalReady = CompletableDeferred() + + /** Called by the UI once the terminal has been sized to its viewport. */ + fun onTerminalResized() { + terminalReady.complete(Unit) } fun startRunAction() { viewModelScope.launch { - val emu = emulatorReady.await() - + // Start the command with the real terminal size + terminalReady.await() + val columns = emulator.mColumns + val rows = emulator.mRows val success = withContext(Dispatchers.IO) { runSuCommand( - emu, + emulator, columns, rows, "cd /data/adb/modules/$actionId && sh ./action.sh" ) } @@ -59,12 +68,10 @@ class ActionViewModel : BaseViewModel() { ) val file = MediaStoreUtils.getFile(name) file.uri.outputStream().bufferedWriter().use { writer -> - val transcript = emulator?.screen?.transcriptText - if (transcript != null) { - writer.write(transcript) - } + val transcript = emulator.screen.transcriptText + writer.write(transcript) } - showSnackbar(file.toString()) + showToast(file.toString()) } } } diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/module/ModuleScreen.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/module/ModuleScreen.kt index 8b82210fa..56bc6ec45 100644 --- a/app/apk/src/main/java/com/topjohnwu/magisk/ui/module/ModuleScreen.kt +++ b/app/apk/src/main/java/com/topjohnwu/magisk/ui/module/ModuleScreen.kt @@ -92,6 +92,7 @@ import com.topjohnwu.magisk.core.R as CoreR @Composable fun ModuleScreen( viewModel: ModuleViewModel, + isFabAtBottom: Boolean, modifier: Modifier = Modifier, onRegisterFab: (((() -> Unit)?) -> Unit)? = null, contentFocusRequester: FocusRequester? = null, @@ -220,6 +221,9 @@ fun ModuleScreen( return@Scaffold } + val listBottomPadding = padding.calculateBottomPadding() + if (isFabAtBottom) 92.dp else 12.dp + val scrollbarBottomPadding = padding.calculateBottomPadding() + if (isFabAtBottom) 80.dp else 12.dp + val gridState = rememberLazyStaggeredGridState() // Staggered, as cards expand; 360dp leaves room for the action buttons row LazyVerticalStaggeredGrid( @@ -234,14 +238,14 @@ fun ModuleScreen( gridState, contentPadding = PaddingValues( top = padding.calculateTopPadding() + 4.dp, - bottom = padding.calculateBottomPadding() + 80.dp, + bottom = scrollbarBottomPadding, ), ), contentPadding = PaddingValues( start = 12.dp, top = padding.calculateTopPadding() + 16.dp, end = 12.dp, - bottom = padding.calculateBottomPadding() + 92.dp, + bottom = listBottomPadding, ), verticalItemSpacing = 8.dp, horizontalArrangement = Arrangement.spacedBy(8.dp), diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/settings/SettingsViewModel.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/settings/SettingsViewModel.kt index 896fc4295..2f2313b58 100644 --- a/app/apk/src/main/java/com/topjohnwu/magisk/ui/settings/SettingsViewModel.kt +++ b/app/apk/src/main/java/com/topjohnwu/magisk/ui/settings/SettingsViewModel.kt @@ -183,7 +183,7 @@ class SettingsViewModel : BaseViewModel() { ) } if (isMismatch) { - showSnackbar(CoreR.string.reboot_apply_change) + showToast(CoreR.string.reboot_apply_change) } } 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 index 11654c385..1de4770a4 100644 --- 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 @@ -1,7 +1,5 @@ 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 @@ -29,7 +27,7 @@ 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.ui.component.AppIcon import com.topjohnwu.magisk.core.R as CoreR @Composable @@ -50,9 +48,8 @@ internal fun SharedUidBadge(modifier: Modifier = Modifier) { @Composable fun SuperuserAppListItem( - icon: Drawable, - title: String, packageName: String, + title: String, isSharedUid: Boolean, modifier: Modifier = Modifier, contentDescription: String? = null, @@ -61,8 +58,8 @@ fun SuperuserAppListItem( ListItem( modifier = modifier, leadingContent = { - Image( - painter = rememberDrawablePainter(icon), + AppIcon( + packageName = packageName, contentDescription = null, modifier = Modifier.size(40.dp) ) @@ -94,9 +91,8 @@ fun SuperuserAppListItem( @Composable fun SuperuserAppCard( - icon: Drawable, - title: String, packageName: String, + title: String, isSharedUid: Boolean, modifier: Modifier = Modifier, onClick: (() -> Unit)? = null, @@ -110,9 +106,8 @@ fun SuperuserAppCard( ) { val itemContent = @Composable { SuperuserAppListItem( - icon = icon, - title = title, packageName = packageName, + title = title, isSharedUid = isSharedUid, contentDescription = contentDescription, trailingContent = trailingContent, diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/superuser/SuperuserDetailScreen.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/superuser/SuperuserDetailScreen.kt index fad16a85c..3b16d0565 100644 --- a/app/apk/src/main/java/com/topjohnwu/magisk/ui/superuser/SuperuserDetailScreen.kt +++ b/app/apk/src/main/java/com/topjohnwu/magisk/ui/superuser/SuperuserDetailScreen.kt @@ -38,6 +38,7 @@ import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier @@ -45,13 +46,15 @@ import androidx.compose.ui.input.nestedscroll.nestedScroll 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.AppIcon 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 com.topjohnwu.magisk.ui.navigation.LocalNavigator +import com.topjohnwu.magisk.ui.navigation.Route import kotlinx.coroutines.launch import com.topjohnwu.magisk.core.R as CoreR @@ -64,8 +67,22 @@ fun SuperuserDetailScreen( modifier: Modifier = Modifier, ) { val uiState by viewModel.uiState.collectAsStateWithLifecycle() - val items = uiState.policies.filter { it.policy.uid == uid } + // After a revoke, the policy is removed from the state while this screen is still + // animating out, so keep showing the last known content instead of a blank page. + val lastItems = remember(uid) { LastItems() } + val currentItems = uiState.policies.filter { it.uid == uid } + val items = currentItems + .also { if (it.isNotEmpty()) lastItems.value = it } + .ifEmpty { lastItems.value } val item = items.firstOrNull() + + // If the policy disappears while this screen is still shown (e.g. the app was uninstalled), + // leave instead of showing stale content. After a revoke, we have already navigated away. + val navigator = LocalNavigator.current + val isGone = !uiState.loading && currentItems.isEmpty() + LaunchedEffect(isGone) { + if (isGone && navigator.current() == Route.SuperuserDetail(uid)) onBack() + } val scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior() val scrollState = rememberScrollState() val scope = rememberCoroutineScope() @@ -135,8 +152,8 @@ fun SuperuserDetailScreen( modifier = Modifier.padding(18.dp), verticalAlignment = Alignment.CenterVertically ) { - Image( - painter = rememberDrawablePainter(item.icon), + AppIcon( + packageName = item.packageName, contentDescription = item.appName, modifier = Modifier.size(48.dp) ) @@ -160,7 +177,7 @@ fun SuperuserDetailScreen( color = MaterialTheme.colorScheme.onSurfaceVariant ) Text( - text = "UID: ${item.policy.uid}", + text = "UID: ${item.uid}", style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant ) @@ -246,3 +263,8 @@ private fun RevokeButton( ) } } + +// Plain holder: updating it must not trigger recomposition +private class LastItems { + var value: List = emptyList() +} 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 index 4d66ede92..d8dd10c13 100644 --- 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 @@ -17,15 +17,10 @@ import androidx.compose.foundation.lazy.grid.items import androidx.compose.foundation.lazy.grid.rememberLazyGridState 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 @@ -39,9 +34,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.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.setValue import androidx.navigationevent.NavigationEventInfo import androidx.navigationevent.compose.NavigationBackHandler import androidx.navigationevent.compose.rememberNavigationEventState @@ -50,9 +42,9 @@ 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.AppSortFilterActions import com.topjohnwu.magisk.ui.component.rememberBiometricAuth import com.topjohnwu.magisk.ui.component.verticalScrollbar import com.topjohnwu.magisk.core.R as CoreR @@ -73,8 +65,6 @@ fun SuperuserGrantScreen( 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 requireAuth = rememberBiometricAuth() val searchBackState = rememberNavigationEventState(currentInfo = NavigationEventInfo.None) @@ -109,85 +99,16 @@ fun SuperuserGrantScreen( } }, 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 - } - ) - } - } + AppSortFilterActions( + sortBy = sortBy, + sortReverse = sortReverse, + onSortByChanged = { viewModel.setSortBy(it) }, + onToggleSortReverse = { viewModel.toggleSortReverse() }, + showSystem = showSystem, + showOS = showOS, + onShowSystemChanged = { viewModel.setShowSystem(it) }, + onShowOSChanged = { viewModel.setShowOS(it) }, + ) }, scrollBehavior = scrollBehavior ) @@ -299,9 +220,8 @@ private fun SuGrantAppCard( modifier: Modifier = Modifier ) { SuperuserAppCard( - icon = app.info.icon, - title = app.info.label, packageName = app.info.packageName, + title = app.info.label, isSharedUid = app.info.isSharedUid, checked = app.isGranted, onCheckedChange = { onToggle() }, 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 index 14551c636..0b20b69e9 100644 --- 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 @@ -2,8 +2,8 @@ package com.topjohnwu.magisk.ui.superuser import android.content.pm.ApplicationInfo import android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES -import android.graphics.drawable.Drawable import android.os.Process +import androidx.compose.runtime.Immutable import androidx.lifecycle.viewModelScope import com.topjohnwu.magisk.arch.AsyncLoadViewModel import com.topjohnwu.magisk.core.AppContext @@ -14,6 +14,7 @@ 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 com.topjohnwu.magisk.ui.component.AppSortBy import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow @@ -31,12 +32,10 @@ import kotlinx.coroutines.withContext import timber.log.Timber import java.util.Locale -enum class SortBy { NAME, PACKAGE_NAME, INSTALL_TIME, UPDATE_TIME } - +@Immutable data class SuGrantAppInfo( val label: String, val packageName: String, - val icon: Drawable, val uid: Int, val isSystemApp: Boolean, val isApp: Boolean, @@ -53,6 +52,7 @@ data class SuGrantAppInfo( } } +@Immutable data class SuGrantAppState( val info: SuGrantAppInfo, val isGranted: Boolean, @@ -77,8 +77,8 @@ class SuperuserGrantViewModel( private val _showOS = MutableStateFlow(false) val showOS: StateFlow = _showOS.asStateFlow() - private val _sortBy = MutableStateFlow(SortBy.NAME) - val sortBy: StateFlow = _sortBy.asStateFlow() + private val _sortBy = MutableStateFlow(AppSortBy.NAME) + val sortBy: StateFlow = _sortBy.asStateFlow() private val _sortReverse = MutableStateFlow(false) val sortReverse: StateFlow = _sortReverse.asStateFlow() @@ -91,7 +91,7 @@ class SuperuserGrantViewModel( 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 sort = args[4] as AppSortBy val reverse = args[5] as Boolean val filtered = apps.filter { app -> @@ -108,13 +108,13 @@ class SuperuserGrantViewModel( } val secondary: Comparator = when (sort) { - SortBy.NAME -> compareBy(String.CASE_INSENSITIVE_ORDER) { it.info.label } + AppSortBy.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 } + AppSortBy.PACKAGE_NAME -> compareBy(String.CASE_INSENSITIVE_ORDER) { it.info.packageName } + AppSortBy.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 } + AppSortBy.UPDATE_TIME -> compareByDescending { it.info.lastUpdateTime } .thenBy(String.CASE_INSENSITIVE_ORDER) { it.info.label } .thenBy { it.info.packageName } } @@ -129,7 +129,7 @@ class SuperuserGrantViewModel( if (!v) _showOS.value = false } fun setShowOS(v: Boolean) { _showOS.value = v } - fun setSortBy(s: SortBy) { _sortBy.value = s } + fun setSortBy(s: AppSortBy) { _sortBy.value = s } fun toggleSortReverse() { _sortReverse.value = !_sortReverse.value } fun toggleGrant(app: SuGrantAppState) { @@ -150,7 +150,6 @@ class SuperuserGrantViewModel( 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) @@ -220,13 +219,11 @@ class SuperuserGrantViewModel( } 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 = Process.isApplicationUid(appInfo.uid) val suAppInfo = SuGrantAppInfo( label = label, packageName = appInfo.packageName, - icon = icon, uid = appInfo.uid, isSystemApp = isSystemApp, isApp = isApp, 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 6c4946c6a..a3c6956b0 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 @@ -49,6 +49,7 @@ import com.topjohnwu.magisk.core.R as CoreR @Composable fun SuperuserScreen( viewModel: SuperuserViewModel, + isFabAtBottom: Boolean, modifier: Modifier = Modifier, onRegisterFab: (((() -> Unit)?) -> Unit)? = null, contentFocusRequester: FocusRequester? = null, @@ -131,6 +132,9 @@ fun SuperuserScreen( return@Scaffold } + val listBottomPadding = padding.calculateBottomPadding() + if (isFabAtBottom) 92.dp else 12.dp + val scrollbarBottomPadding = padding.calculateBottomPadding() + if (isFabAtBottom) 80.dp else 12.dp + val gridState = rememberLazyGridState() LazyVerticalGrid( columns = GridCells.Adaptive(320.dp), @@ -144,21 +148,21 @@ fun SuperuserScreen( gridState, contentPadding = PaddingValues( top = padding.calculateTopPadding() + 4.dp, - bottom = padding.calculateBottomPadding() + 80.dp, + bottom = scrollbarBottomPadding, ), ), contentPadding = PaddingValues( start = 12.dp, top = padding.calculateTopPadding() + 16.dp, end = 12.dp, - bottom = padding.calculateBottomPadding() + 92.dp, + bottom = listBottomPadding, ), verticalArrangement = Arrangement.spacedBy(8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp), ) { items( items = uiState.policies, - key = { "${it.policy.uid}_${it.packageName}" }, + key = { "${it.uid}_${it.packageName}" }, contentType = { "PolicyCard" } ) { item -> val isLast = item == uiState.policies.lastOrNull() @@ -169,7 +173,7 @@ fun SuperuserScreen( viewModel.togglePolicy(item) } }, - onDetail = { navigator.push(Route.SuperuserDetail(item.policy.uid)) }, + onDetail = { navigator.push(Route.SuperuserDetail(item.uid)) }, modifier = if (isLast && contentFocusRequester != null) { Modifier.focusRequester(contentFocusRequester) } else Modifier, @@ -187,9 +191,8 @@ private fun PolicyCard( modifier: Modifier = Modifier ) { SuperuserAppCard( - icon = item.icon, - title = item.title, packageName = item.packageName, + title = item.title, isSharedUid = item.isSharedUid, onClick = onDetail, contentDescription = item.appName, diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/superuser/SuperuserViewModel.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/superuser/SuperuserViewModel.kt index 967cb95e3..146da0e42 100644 --- a/app/apk/src/main/java/com/topjohnwu/magisk/ui/superuser/SuperuserViewModel.kt +++ b/app/apk/src/main/java/com/topjohnwu/magisk/ui/superuser/SuperuserViewModel.kt @@ -2,8 +2,9 @@ package com.topjohnwu.magisk.ui.superuser import android.content.pm.PackageManager import android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES -import android.graphics.drawable.Drawable import android.os.Process +import androidx.annotation.MainThread +import androidx.compose.runtime.Immutable import androidx.lifecycle.viewModelScope import com.topjohnwu.magisk.arch.AsyncLoadViewModel import com.topjohnwu.magisk.core.AppContext @@ -22,28 +23,37 @@ import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.debounce import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext import java.util.Locale +import java.util.concurrent.ConcurrentHashMap +@Immutable data class PolicyItem( - var policy: SuPolicy, + val uid: Int, val packageName: String, - val isSharedUid: Boolean, - val icon: Drawable, val appName: String, - val policyValue: Int = policy.policy, - val notification: Boolean = policy.notification, - val logging: Boolean = policy.logging, + val isSharedUid: Boolean, + val policyValue: Int, + val notification: Boolean, + val logging: Boolean, ) { - val title get() = appName - val isEnabled get() = policyValue >= SuPolicy.ALLOW - val isRestricted get() = policyValue == SuPolicy.RESTRICT + val title: String get() = appName + val isEnabled: Boolean get() = policyValue >= SuPolicy.ALLOW + val isRestricted: Boolean get() = policyValue == SuPolicy.RESTRICT } class SuperuserViewModel( private val db: PolicyDao ) : AsyncLoadViewModel() { + // Serializes database access so writes land in the same order as the UI changes, + // and reloads never interleave with them + private val writeLock = Mutex() + // Edits already applied to the UI state but not yet written to the database + private val pendingWrites = ConcurrentHashMap() + init { @OptIn(FlowPreview::class) viewModelScope.launch { @@ -66,47 +76,58 @@ class SuperuserViewModel( return } _uiState.update { it.copy(loading = true) } - withContext(Dispatchers.IO) { - db.deleteOutdated() - db.delete(AppContext.applicationInfo.uid) - val policies = ArrayList() - val pm = AppContext.packageManager - for (policy in db.fetchAll()) { - val pkgs = - if (policy.uid == Process.SYSTEM_UID) arrayOf("android") - else pm.getPackagesForUid(PolicyDao.denormalizeUid(policy.uid)) - if (pkgs == null) { - db.delete(policy.uid) - continue - } - val map = pkgs.mapNotNull { pkg -> - try { - val info = pm.getPackageInfo(pkg, MATCH_UNINSTALLED_PACKAGES) - PolicyItem( - policy = policy, - packageName = info.packageName, - isSharedUid = info.sharedUserId != null, - icon = info.applicationInfo?.loadIcon(pm) ?: pm.defaultActivityIcon, - appName = info.applicationInfo?.getLabel(pm) ?: info.packageName, - policyValue = policy.policy, - notification = policy.notification, - logging = policy.logging, - ) - } catch (_: PackageManager.NameNotFoundException) { - null + writeLock.withLock { + val loaded = withContext(Dispatchers.IO) { + db.deleteOutdated() + db.delete(AppContext.applicationInfo.uid) + val policies = ArrayList() + val pm = AppContext.packageManager + for (policy in db.fetchAll()) { + val pkgs = + if (policy.uid == Process.SYSTEM_UID) arrayOf("android") + else pm.getPackagesForUid(PolicyDao.denormalizeUid(policy.uid)) + if (pkgs == null) { + db.delete(policy.uid) + continue } + val map = pkgs.mapNotNull { pkg -> + try { + val info = pm.getPackageInfo(pkg, MATCH_UNINSTALLED_PACKAGES) + PolicyItem( + uid = policy.uid, + packageName = info.packageName, + appName = info.applicationInfo?.getLabel(pm) ?: info.packageName, + isSharedUid = info.sharedUserId != null, + policyValue = policy.policy, + notification = policy.notification, + logging = policy.logging, + ) + } catch (_: PackageManager.NameNotFoundException) { + null + } + } + if (map.isEmpty()) { + db.delete(policy.uid) + continue + } + policies.addAll(map) } - if (map.isEmpty()) { - db.delete(policy.uid) - continue + policies.sortWith(compareBy( + { it.appName.lowercase(Locale.ROOT) }, + { it.packageName } + )) + policies + } + // Publish on the main thread, where all edits are applied, so the update below + // never races with them. Keep edits queued behind this reload so they don't revert. + _uiState.update { state -> + val merged = loaded.map { item -> + pendingWrites[item.uid]?.let { + item.copy(policyValue = it.policy, notification = it.notification, logging = it.logging) + } ?: item } - policies.addAll(map) + state.copy(loading = false, policies = merged, suRestrict = Config.suRestrict) } - policies.sortWith(compareBy( - { it.appName.lowercase(Locale.ROOT) }, - { it.packageName } - )) - _uiState.update { it.copy(loading = false, policies = policies, suRestrict = Config.suRestrict) } } } @@ -114,73 +135,78 @@ class SuperuserViewModel( _uiState.update { it.copy(suRestrict = Config.suRestrict) } } - val requiresAuth get() = Config.suAuth - fun performDelete(item: PolicyItem, onDeleted: () -> Unit = {}) { viewModelScope.launch { - db.delete(item.policy.uid) - _uiState.update { state -> - state.copy(policies = state.policies.filter { it.policy.uid != item.policy.uid }) + writeLock.withLock { + db.delete(item.uid) + pendingWrites.remove(item.uid) + _uiState.update { state -> + state.copy(policies = state.policies.filter { it.uid != item.uid }) + } } onDeleted() } } - fun updateNotify(item: PolicyItem) { - val newNotification = !item.notification - item.policy.notification = newNotification - viewModelScope.launch { - db.update(item.policy) - _uiState.update { state -> - state.copy( - policies = state.policies.map { - if (it.policy.uid == item.policy.uid) it.copy(notification = newNotification) else it - } - ) - } - val res = if (newNotification) R.string.su_snack_notif_on else R.string.su_snack_notif_off - showSnackbar(AppContext.getString(res, item.appName)) + /** + * Apply [transform] to the latest state of every item with [uid], then persist the result. + * Deriving each change from the current state (instead of the item captured by the UI) and + * writing in order ensures quick consecutive edits cannot overwrite each other. + */ + @MainThread + private fun updateItem(uid: Int, transform: (PolicyItem) -> PolicyItem): PolicyItem? { + // All state updates happen on the main thread, so this update is never retried + var updated: PolicyItem? = null + _uiState.update { state -> + state.copy( + policies = state.policies.map { + if (it.uid == uid) transform(it).also { new -> updated = new } else it + } + ) } + val item = updated ?: return null + val policy = SuPolicy( + uid = item.uid, + policy = item.policyValue, + notification = item.notification, + logging = item.logging, + ) + pendingWrites[uid] = policy + viewModelScope.launch { + try { + writeLock.withLock { + // Skip if the policy was deleted while this write was queued + if (_uiState.value.policies.any { it.uid == uid }) db.update(policy) + } + } finally { + // Use the original key: db.update() normalizes the uid of the policy object + pendingWrites.remove(uid, policy) + } + } + return item + } + + fun updateNotify(item: PolicyItem) { + val updated = updateItem(item.uid) { it.copy(notification = !it.notification) } ?: return + val res = if (updated.notification) R.string.su_snack_notif_on else R.string.su_snack_notif_off + showToast(AppContext.getString(res, item.appName)) } fun updateLogging(item: PolicyItem) { - val newLogging = !item.logging - item.policy.logging = newLogging - viewModelScope.launch { - db.update(item.policy) - _uiState.update { state -> - state.copy( - policies = state.policies.map { - if (it.policy.uid == item.policy.uid) it.copy(logging = newLogging) else it - } - ) - } - val res = if (newLogging) R.string.su_snack_log_on else R.string.su_snack_log_off - showSnackbar(AppContext.getString(res, item.appName)) - } - } - - fun updatePolicy(item: PolicyItem, newPolicy: Int) { - 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 - } - ) - } - } + val updated = updateItem(item.uid) { it.copy(logging = !it.logging) } ?: return + val res = if (updated.logging) R.string.su_snack_log_on else R.string.su_snack_log_off + showToast(AppContext.getString(res, item.appName)) } fun togglePolicy(item: PolicyItem) { - val newPolicy = if (item.isEnabled) SuPolicy.DENY else SuPolicy.ALLOW - updatePolicy(item, newPolicy) + updateItem(item.uid) { + it.copy(policyValue = if (it.isEnabled) SuPolicy.DENY else SuPolicy.ALLOW) + } } fun toggleRestrict(item: PolicyItem) { - val newPolicy = if (item.isRestricted) SuPolicy.ALLOW else SuPolicy.RESTRICT - updatePolicy(item, newPolicy) + updateItem(item.uid) { + it.copy(policyValue = if (it.isRestricted) SuPolicy.ALLOW else SuPolicy.RESTRICT) + } } } diff --git a/app/apk/src/main/java/com/topjohnwu/magisk/ui/terminal/TerminalScreen.kt b/app/apk/src/main/java/com/topjohnwu/magisk/ui/terminal/TerminalScreen.kt index 73cfff30b..50b8bb0c3 100644 --- a/app/apk/src/main/java/com/topjohnwu/magisk/ui/terminal/TerminalScreen.kt +++ b/app/apk/src/main/java/com/topjohnwu/magisk/ui/terminal/TerminalScreen.kt @@ -9,13 +9,17 @@ import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableFloatStateOf import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableLongStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.setValue +import androidx.compose.runtime.snapshotFlow import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clipToBounds import androidx.compose.ui.draw.drawBehind @@ -34,20 +38,40 @@ private const val MIN_TERMINAL_COLUMNS = 256 @Composable fun TerminalScreen( + emulator: TerminalEmulator, modifier: Modifier = Modifier, - onEmulatorCreated: (TerminalEmulator) -> Unit = {}, + onResized: () -> Unit = {}, ) { + val currentOnResized by rememberUpdatedState(onResized) val density = LocalDensity.current val renderer = remember { val textSizePx = with(density) { 12.sp.toPx().toInt() } TerminalRenderer(textSizePx, Typeface.MONOSPACE) } - var emulator by remember { mutableStateOf(null) } - var updateTick by remember { mutableIntStateOf(0) } + var drawTrigger by remember { mutableLongStateOf(0L) } var topRow by remember { mutableIntStateOf(0) } var scrollX by remember { mutableFloatStateOf(0f) } var scrolledToBottom by remember { mutableStateOf(true) } + // Snapshot copies of emulator fields so scrollbars observe output changes + var transcriptRows by remember { mutableIntStateOf(0) } + var maxUsedColumn by remember { mutableIntStateOf(0) } + + DisposableEffect(emulator) { + fun syncState() { + transcriptRows = emulator.screen.activeTranscriptRows + maxUsedColumn = emulator.maxUsedColumn + } + syncState() + emulator.onScreenUpdate = { + if (scrolledToBottom) topRow = 0 + syncState() + drawTrigger++ + } + onDispose { + emulator.onScreenUpdate = null + } + } BoxWithConstraints(modifier = modifier) { val widthPx = constraints.maxWidth.toFloat() @@ -57,35 +81,25 @@ fun TerminalScreen( val rows = max(4, ((heightPx - renderer.fontLineSpacingAndAscent) / renderer.fontLineSpacing).toInt()) val lineHeight = renderer.fontLineSpacing.toFloat() - @Suppress("UNUSED_EXPRESSION") - updateTick - val maxUsedCol = emulator?.maxUsedColumn ?: 0 - val contentWidthPx = maxOf(widthPx, (maxUsedCol + 2) * renderer.fontWidth) - val maxScrollX = maxOf(0f, contentWidthPx - widthPx) + fun getMaxScrollX(): Float { + val contentWidthPx = maxOf(widthPx, (maxUsedColumn + 2) * renderer.fontWidth) + return maxOf(0f, contentWidthPx - widthPx) + } LaunchedEffect(cols, rows) { - val emu = emulator - if (emu == null) { - val newEmu = TerminalEmulator(cols, rows, renderer.fontWidth.toInt(), renderer.fontLineSpacing, null) - newEmu.onScreenUpdate = { - if (scrolledToBottom) topRow = 0 - updateTick++ - } - emulator = newEmu - onEmulatorCreated(newEmu) - } else { - emu.resize(cols, rows, renderer.fontWidth.toInt(), renderer.fontLineSpacing) + emulator.resize(cols, rows, renderer.fontWidth.toInt(), renderer.fontLineSpacing) + currentOnResized() + } + + // Keep scrollX in range when the viewport or content width changes + LaunchedEffect(widthPx) { + snapshotFlow { getMaxScrollX() }.collect { maxScrollX -> + scrollX = scrollX.coerceIn(0f, maxScrollX) } } - LaunchedEffect(maxScrollX) { - scrollX = scrollX.coerceIn(0f, maxScrollX) - } - - val activeTranscriptRows = emulator?.screen?.activeTranscriptRows ?: 0 val verticalScrollableState = rememberScrollableState { delta -> - val emu = emulator ?: return@rememberScrollableState 0f - val minTop = -emu.screen.activeTranscriptRows + val minTop = -emulator.screen.activeTranscriptRows val rowDelta = -(delta / lineHeight).toInt() if (rowDelta != 0) { val newTopRow = (topRow + rowDelta).coerceIn(minTop, 0) @@ -96,6 +110,7 @@ fun TerminalScreen( } val horizontalScrollableState = rememberScrollableState { delta -> + val maxScrollX = getMaxScrollX() val oldScrollX = scrollX val newScrollX = (scrollX - delta).coerceIn(0f, maxScrollX) scrollX = newScrollX @@ -108,8 +123,8 @@ fun TerminalScreen( .clipToBounds() .background(Color.Black) .terminalScrollbar( - activeTranscriptRows = activeTranscriptRows, - topRow = topRow, + activeTranscriptRowsProvider = { transcriptRows }, + topRowProvider = { topRow }, visibleRows = rows, onScrollToRow = { newRow -> topRow = newRow @@ -118,8 +133,8 @@ fun TerminalScreen( isScrollInProgress = verticalScrollableState.isScrollInProgress, ) .terminalHorizontalScrollbar( - scrollX = scrollX, - maxScrollX = maxScrollX, + scrollXProvider = { scrollX }, + maxScrollXProvider = { getMaxScrollX() }, viewportWidth = widthPx, onScrollToX = { newScrollX -> scrollX = newScrollX }, isScrollInProgress = horizontalScrollableState.isScrollInProgress, @@ -133,12 +148,11 @@ fun TerminalScreen( state = horizontalScrollableState ) .drawBehind { - @Suppress("UNUSED_EXPRESSION") - updateTick - val emu = emulator ?: return@drawBehind - drawIntoCanvas { canvas -> - canvas.nativeCanvas.withTranslation(-scrollX, 0f) { - renderer.render(emu, this, topRow, -1, -1, -1, -1) + if (drawTrigger >= 0L) { + drawIntoCanvas { canvas -> + canvas.nativeCanvas.withTranslation(-scrollX, 0f) { + renderer.render(emulator, this, topRow, -1, -1, -1, -1) + } } } } diff --git a/app/core/src/main/java/com/topjohnwu/magisk/core/data/magiskdb/MagiskDB.kt b/app/core/src/main/java/com/topjohnwu/magisk/core/data/magiskdb/MagiskDB.kt index a8badaf61..6f8c7ef50 100644 --- a/app/core/src/main/java/com/topjohnwu/magisk/core/data/magiskdb/MagiskDB.kt +++ b/app/core/src/main/java/com/topjohnwu/magisk/core/data/magiskdb/MagiskDB.kt @@ -7,10 +7,6 @@ import kotlinx.coroutines.withContext open class MagiskDB { - class Literal( - val str: String - ) - suspend inline fun exec( query: String, crossinline mapper: (Map) -> R @@ -39,7 +35,6 @@ open class MagiskDB { when (it) { is Boolean -> if (it) "1" else "0" is Number -> it.toString() - is Literal -> it.str else -> "\"$it\"" } } diff --git a/app/core/src/main/java/com/topjohnwu/magisk/core/data/magiskdb/PolicyDao.kt b/app/core/src/main/java/com/topjohnwu/magisk/core/data/magiskdb/PolicyDao.kt index b7df76edb..40bfc1944 100644 --- a/app/core/src/main/java/com/topjohnwu/magisk/core/data/magiskdb/PolicyDao.kt +++ b/app/core/src/main/java/com/topjohnwu/magisk/core/data/magiskdb/PolicyDao.kt @@ -5,7 +5,7 @@ import com.topjohnwu.magisk.core.AppContext import com.topjohnwu.magisk.core.Const import com.topjohnwu.magisk.core.model.su.SuPolicy -private const val SELECT_QUERY = "SELECT (until - strftime(\"%s\", \"now\")) AS remain, *" +private const val SELECT_QUERY = "SELECT *" class PolicyDao : MagiskDB() { @@ -45,15 +45,6 @@ class PolicyDao : MagiskDB() { private fun toPolicy(map: Map): SuPolicy? { val uid = map["uid"]?.toInt() ?: return null val policy = SuPolicy(uid) - - map["until"]?.toLong()?.let { until -> - if (until <= 0) { - policy.remain = until - } else { - map["remain"]?.toLong()?.let { policy.remain = it } - } - } - map["policy"]?.toInt()?.let { policy.policy = it } map["logging"]?.toInt()?.let { policy.logging = it != 0 } map["notification"]?.toInt()?.let { policy.notification = it != 0 } diff --git a/app/core/src/main/java/com/topjohnwu/magisk/core/model/su/SuPolicy.kt b/app/core/src/main/java/com/topjohnwu/magisk/core/model/su/SuPolicy.kt index ce08df516..b7fbf1fb7 100644 --- a/app/core/src/main/java/com/topjohnwu/magisk/core/model/su/SuPolicy.kt +++ b/app/core/src/main/java/com/topjohnwu/magisk/core/model/su/SuPolicy.kt @@ -1,11 +1,8 @@ package com.topjohnwu.magisk.core.model.su -import com.topjohnwu.magisk.core.data.magiskdb.MagiskDB - class SuPolicy( var uid: Int, var policy: Int = DENY, - var remain: Long = -1L, var logging: Boolean = true, var notification: Boolean = true, ) { @@ -17,15 +14,11 @@ class SuPolicy( } fun toMap(): MutableMap { - val until = if (remain <= 0) { - remain - } else { - MagiskDB.Literal("(strftime(\"%s\", \"now\") + $remain)") - } return mutableMapOf( "uid" to uid, "policy" to policy, - "until" to until, + // Timed grants are no longer supported; all policies are permanent + "until" to 0, "logging" to logging, "notification" to notification ) diff --git a/app/core/src/main/java/com/topjohnwu/magisk/test/SmokeTest.kt b/app/core/src/main/java/com/topjohnwu/magisk/test/SmokeTest.kt index 38285a7bc..fc9642085 100644 --- a/app/core/src/main/java/com/topjohnwu/magisk/test/SmokeTest.kt +++ b/app/core/src/main/java/com/topjohnwu/magisk/test/SmokeTest.kt @@ -35,7 +35,6 @@ class SmokeTest : TestCommon { policy = SuPolicy.ALLOW, logging = false, notification = false, - remain = 0L ) runBlocking { ServiceLocator.policyDB.update(policy)