app: optimize Compose performance and code quality

Eliminate recomposition bottlenecks in TerminalScreen by invalidating
strictly inside the draw phase via drawBehind, decoupling the
TerminalEmulator lifecycle to ViewModels, and replacing Handler with
Coroutines Dispatchers.Main.immediate in TerminalProcess. Commands still
start only after the terminal has been sized to its viewport.

Stabilize Compose data models (PolicyItem, AppProcessInfo, ProcessInfo,
SuGrantAppInfo, SuGrantAppState) as @Immutable data classes with
read-only val properties, decoupling Android Drawable dependencies into
an on-demand async AppIcon component.

Drop the remain field from SuPolicy as timed grants no longer exist, and
always write until=0. This lets SuperuserViewModel rebuild policies from
the immutable PolicyItem without persisting an expired row. Apply policy
edits to the UI state first and persist them in order, so quick
consecutive toggles cannot overwrite each other and reloads or deletes
cannot interleave with them. Remove the MagiskDB.Literal helper, which
no longer has any users.

Implement dynamic adaptive bottom padding in SuperuserScreen and
ModuleScreen according to FAB positioning (isFabAtBottom),
deduplicate sort and filter controls into AppSortFilterActions,
modernize storage permission handling using ActivityResultContracts,
and replace BaseViewModel.showSnackbar with showToast. Keep the delayed
reboot after fixing the environment from being cancelled when leaving
HomeScreen.

Assisted-by: Gemini 4 Argon
Assisted-by: Claude Opus 5.5
This commit is contained in:
topjohnwu
2026-10-24 13:01:45 -07:00
committed by John Wu
parent bb533df6e0
commit b575a63970
30 changed files with 696 additions and 575 deletions
@@ -14,11 +14,11 @@ abstract class BaseViewModel : ViewModel() {
private val _navEvents = MutableSharedFlow<Route>(extraBufferCapacity = 1) private val _navEvents = MutableSharedFlow<Route>(extraBufferCapacity = 1)
val navEvents: SharedFlow<Route> = _navEvents val navEvents: SharedFlow<Route> = _navEvents
fun showSnackbar(@StringRes resId: Int) { fun showToast(@StringRes resId: Int) {
AppContext.toast(resId, Toast.LENGTH_SHORT) AppContext.toast(resId, Toast.LENGTH_SHORT)
} }
fun showSnackbar(msg: String) { fun showToast(msg: String) {
AppContext.toast(msg, Toast.LENGTH_SHORT) AppContext.toast(msg, Toast.LENGTH_SHORT)
} }
@@ -1,8 +1,9 @@
package com.topjohnwu.magisk.terminal package com.topjohnwu.magisk.terminal
import android.os.Handler
import android.os.Looper
import com.topjohnwu.superuser.Shell import com.topjohnwu.superuser.Shell
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import timber.log.Timber import timber.log.Timber
private val busyboxPath: String by lazy { private val busyboxPath: String by lazy {
@@ -10,17 +11,17 @@ private val busyboxPath: String by lazy {
?: "/data/adb/magisk/busybox" ?: "/data/adb/magisk/busybox"
} }
private val mainHandler = Handler(Looper.getMainLooper()) private val terminalScope = CoroutineScope(Dispatchers.Main.immediate)
fun TerminalEmulator.appendOnMain(bytes: ByteArray, len: Int) { fun TerminalEmulator.appendOnMain(bytes: ByteArray, len: Int) {
mainHandler.post { terminalScope.launch {
append(bytes, len) append(bytes, len)
onScreenUpdate?.invoke() onScreenUpdate?.invoke()
} }
} }
fun TerminalEmulator.appendLineOnMain(line: String) { fun TerminalEmulator.appendLineOnMain(line: String) {
mainHandler.post { terminalScope.launch {
val clear = if (inPlaceNewlines > 0) { val clear = if (inPlaceNewlines > 0) {
"\r\u001b[${inPlaceNewlines}A\u001b[J" "\r\u001b[${inPlaceNewlines}A\u001b[J"
} else { } else {
@@ -43,14 +44,13 @@ fun TerminalEmulator.appendLineOnMain(line: String) {
/** /**
* Run a command as root inside a PTY (via busybox script). * Run a command as root inside a PTY (via busybox script).
* Reads raw bytes from the process and feeds them to the terminal emulator. * 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. * 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 { return try {
val cols = emulator.mColumns val wrappedCmd = "export TERM=xterm-256color; stty cols $columns rows $rows 2>/dev/null; $command"
val rows = emulator.mRows
val wrappedCmd = "export TERM=xterm-256color; stty cols $cols rows $rows 2>/dev/null; $command"
val escapedCmd = wrappedCmd.replace("'", "'\\''") val escapedCmd = wrappedCmd.replace("'", "'\\''")
val process = ProcessBuilder( val process = ProcessBuilder(
@@ -231,7 +231,9 @@ fun MainScreen(
) { page -> ) { page ->
val isCurrentPage = pagerState.currentPage == page val isCurrentPage = pagerState.currentPage == page
val childOwner = rememberNavigationEventDispatcherOwner(enabled = isCurrentPage) val childOwner = rememberNavigationEventDispatcherOwner(enabled = isCurrentPage)
CompositionLocalProvider(LocalNavigationEventDispatcherOwner provides childOwner) { CompositionLocalProvider(
LocalNavigationEventDispatcherOwner provides childOwner,
) {
val tab = visibleTabs[page] val tab = visibleTabs[page]
Box( Box(
modifier = Modifier modifier = Modifier
@@ -285,6 +287,7 @@ fun MainScreen(
SuperuserScreen( SuperuserScreen(
viewModel = vm, viewModel = vm,
onRegisterFab = { superuserFabAction = it }, onRegisterFab = { superuserFabAction = it },
isFabAtBottom = isBar,
contentFocusRequester = superuserContentFocusRequester, contentFocusRequester = superuserContentFocusRequester,
) )
} }
@@ -304,6 +307,7 @@ fun MainScreen(
ModuleScreen( ModuleScreen(
viewModel = vm, viewModel = vm,
onRegisterFab = { moduleFabAction = it }, onRegisterFab = { moduleFabAction = it },
isFabAtBottom = isBar,
contentFocusRequester = moduleContentFocusRequester, contentFocusRequester = moduleContentFocusRequester,
) )
} }
@@ -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<String, CachedIcon>(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,
)
}
}
@@ -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
}
)
}
}
}
@@ -1,14 +1,18 @@
package com.topjohnwu.magisk.ui.component package com.topjohnwu.magisk.ui.component
import android.Manifest.permission.WRITE_EXTERNAL_STORAGE import android.Manifest.permission.WRITE_EXTERNAL_STORAGE
import android.content.pm.PackageManager
import android.os.Build
import android.widget.Toast import android.widget.Toast
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalContext
import androidx.core.content.ContextCompat
import com.topjohnwu.magisk.core.R import com.topjohnwu.magisk.core.R
import com.topjohnwu.magisk.core.base.IActivityExtension
import com.topjohnwu.magisk.core.ktx.toast import com.topjohnwu.magisk.core.ktx.toast
@Composable @Composable
@@ -16,14 +20,24 @@ fun rememberExternalStoragePermissionLauncher(onGranted: () -> Unit): () -> Unit
val context = LocalContext.current val context = LocalContext.current
val currentOnGranted by rememberUpdatedState(onGranted) 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 (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R ||
if (granted) { ContextCompat.checkSelfPermission(context, WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
currentOnGranted() ) {
} else { currentOnGranted()
context.toast(R.string.external_rw_permission_denied, Toast.LENGTH_SHORT) } else {
} launcher.launch(WRITE_EXTERNAL_STORAGE)
} }
} }
} }
@@ -163,20 +163,21 @@ fun rememberScrollbarAdapter(state: ScrollableState): ScrollbarStateAdapter {
@Composable @Composable
fun rememberTerminalScrollbarAdapter( fun rememberTerminalScrollbarAdapter(
activeTranscriptRows: Int, activeTranscriptRowsProvider: () -> Int,
topRow: Int, topRowProvider: () -> Int,
visibleRows: Int, visibleRows: Int,
onScrollToRow: (Int) -> Unit onScrollToRow: (Int) -> Unit
): ScrollbarStateAdapter { ): ScrollbarStateAdapter {
val currentOnScroll = rememberUpdatedState(onScrollToRow) val currentOnScroll = rememberUpdatedState(onScrollToRow)
return remember(activeTranscriptRows, topRow, visibleRows) { return remember(visibleRows) {
object : ScrollbarStateAdapter { object : ScrollbarStateAdapter {
override val isScrollable: Boolean override val isScrollable: Boolean
get() = activeTranscriptRows > 0 get() = activeTranscriptRowsProvider() > 0
override val thumbRatio: Float override val thumbRatio: Float
get() { get() {
val totalRows = activeTranscriptRows + visibleRows val activeRows = activeTranscriptRowsProvider()
val totalRows = activeRows + visibleRows
return if (totalRows > 0) { return if (totalRows > 0) {
(visibleRows.toFloat() / totalRows.toFloat()).coerceIn(0.08f, 1f) (visibleRows.toFloat() / totalRows.toFloat()).coerceIn(0.08f, 1f)
} else 1f } else 1f
@@ -184,14 +185,16 @@ fun rememberTerminalScrollbarAdapter(
override val offsetRatio: Float override val offsetRatio: Float
get() { get() {
return if (activeTranscriptRows > 0) { val activeRows = activeTranscriptRowsProvider()
((activeTranscriptRows + topRow).toFloat() / activeTranscriptRows.toFloat()).coerceIn(0f, 1f) return if (activeRows > 0) {
((activeRows + topRowProvider()).toFloat() / activeRows.toFloat()).coerceIn(0f, 1f)
} else 0f } else 0f
} }
override suspend fun scrollTo(fraction: Float) { override suspend fun scrollTo(fraction: Float) {
if (activeTranscriptRows > 0) { val activeRows = activeTranscriptRowsProvider()
val target = (-activeTranscriptRows * (1f - fraction.coerceIn(0f, 1f))).roundToInt().coerceIn(-activeTranscriptRows, 0) if (activeRows > 0) {
val target = (-activeRows * (1f - fraction.coerceIn(0f, 1f))).roundToInt().coerceIn(-activeRows, 0)
currentOnScroll.value(target) currentOnScroll.value(target)
} }
} }
@@ -201,19 +204,20 @@ fun rememberTerminalScrollbarAdapter(
@Composable @Composable
fun rememberTerminalHorizontalScrollbarAdapter( fun rememberTerminalHorizontalScrollbarAdapter(
scrollX: Float, scrollXProvider: () -> Float,
maxScrollX: Float, maxScrollXProvider: () -> Float,
viewportWidth: Float, viewportWidth: Float,
onScrollToX: (Float) -> Unit, onScrollToX: (Float) -> Unit,
): ScrollbarStateAdapter { ): ScrollbarStateAdapter {
val currentOnScroll = rememberUpdatedState(onScrollToX) val currentOnScroll = rememberUpdatedState(onScrollToX)
return remember(scrollX, maxScrollX, viewportWidth) { return remember(viewportWidth) {
object : ScrollbarStateAdapter { object : ScrollbarStateAdapter {
override val isScrollable: Boolean override val isScrollable: Boolean
get() = maxScrollX > 0f get() = maxScrollXProvider() > 0f
override val thumbRatio: Float override val thumbRatio: Float
get() { get() {
val maxScrollX = maxScrollXProvider()
val totalWidth = viewportWidth + maxScrollX val totalWidth = viewportWidth + maxScrollX
return if (totalWidth > 0f) { return if (totalWidth > 0f) {
(viewportWidth / totalWidth).coerceIn(0.08f, 1f) (viewportWidth / totalWidth).coerceIn(0.08f, 1f)
@@ -222,12 +226,14 @@ fun rememberTerminalHorizontalScrollbarAdapter(
override val offsetRatio: Float override val offsetRatio: Float
get() { get() {
val maxScrollX = maxScrollXProvider()
return if (maxScrollX > 0f) { return if (maxScrollX > 0f) {
(scrollX / maxScrollX).coerceIn(0f, 1f) (scrollXProvider() / maxScrollX).coerceIn(0f, 1f)
} else 0f } else 0f
} }
override suspend fun scrollTo(fraction: Float) { override suspend fun scrollTo(fraction: Float) {
val maxScrollX = maxScrollXProvider()
if (maxScrollX > 0f) { if (maxScrollX > 0f) {
currentOnScroll.value(fraction.coerceIn(0f, 1f) * maxScrollX) currentOnScroll.value(fraction.coerceIn(0f, 1f) * maxScrollX)
} }
@@ -279,8 +285,8 @@ fun Modifier.verticalScrollbar(
} }
fun Modifier.terminalScrollbar( fun Modifier.terminalScrollbar(
activeTranscriptRows: Int, activeTranscriptRowsProvider: () -> Int,
topRow: Int, topRowProvider: () -> Int,
visibleRows: Int, visibleRows: Int,
onScrollToRow: (Int) -> Unit, onScrollToRow: (Int) -> Unit,
isScrollInProgress: Boolean = false, isScrollInProgress: Boolean = false,
@@ -288,8 +294,8 @@ fun Modifier.terminalScrollbar(
thumbColor: Color? = null, thumbColor: Color? = null,
): Modifier = composed { ): Modifier = composed {
val adapter = rememberTerminalScrollbarAdapter( val adapter = rememberTerminalScrollbarAdapter(
activeTranscriptRows = activeTranscriptRows, activeTranscriptRowsProvider = activeTranscriptRowsProvider,
topRow = topRow, topRowProvider = topRowProvider,
visibleRows = visibleRows, visibleRows = visibleRows,
onScrollToRow = onScrollToRow onScrollToRow = onScrollToRow
) )
@@ -302,8 +308,8 @@ fun Modifier.terminalScrollbar(
} }
fun Modifier.terminalHorizontalScrollbar( fun Modifier.terminalHorizontalScrollbar(
scrollX: Float, scrollXProvider: () -> Float,
maxScrollX: Float, maxScrollXProvider: () -> Float,
viewportWidth: Float, viewportWidth: Float,
onScrollToX: (Float) -> Unit, onScrollToX: (Float) -> Unit,
isScrollInProgress: Boolean = false, isScrollInProgress: Boolean = false,
@@ -311,8 +317,8 @@ fun Modifier.terminalHorizontalScrollbar(
thumbColor: Color? = null, thumbColor: Color? = null,
): Modifier = composed { ): Modifier = composed {
val adapter = rememberTerminalHorizontalScrollbarAdapter( val adapter = rememberTerminalHorizontalScrollbarAdapter(
scrollX = scrollX, scrollXProvider = scrollXProvider,
maxScrollX = maxScrollX, maxScrollXProvider = maxScrollXProvider,
viewportWidth = viewportWidth, viewportWidth = viewportWidth,
onScrollToX = onScrollToX, onScrollToX = onScrollToX,
) )
@@ -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_DISABLED_COMPONENTS
import android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES import android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES
import android.content.pm.ServiceInfo import android.content.pm.ServiceInfo
import android.graphics.drawable.Drawable
import android.os.Process import android.os.Process
import androidx.compose.runtime.Immutable
import com.topjohnwu.magisk.core.ktx.getLabel import com.topjohnwu.magisk.core.ktx.getLabel
import java.util.Locale import java.util.Locale
import java.util.TreeSet import java.util.TreeSet
@@ -32,114 +32,125 @@ const val ISOLATED_MAGIC = "isolated"
const val WEBVIEW_ZYGOTE_MAGIC = "webview_zygote" const val WEBVIEW_ZYGOTE_MAGIC = "webview_zygote"
const val WEBVIEW_ZYGOTE_UID = 1053 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") @SuppressLint("InlinedApi")
class AppProcessInfo( data class AppProcessInfo(
private val info: ApplicationInfo, val packageName: String,
pm: PackageManager, val label: String,
denyList: List<CmdlineListItem>, val isSystemApp: Boolean,
private val labelOverride: String? = null, val isApp: Boolean,
private val processesOverride: Collection<ProcessInfo>? = null, val firstInstallTime: Long,
val lastUpdateTime: Long,
val processes: List<ProcessInfo>,
) : Comparable<AppProcessInfo> { ) : Comparable<AppProcessInfo> {
private val denyList = denyList.filter { override fun compareTo(other: AppProcessInfo): Int = comparator.compare(this, other)
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<out ComponentInfo>?.toProcessList() =
orEmpty().map { createProcess(it.getProcName()) }
private fun Array<ServiceInfo>?.toProcessList(): List<ProcessInfo> {
if (this == null) return emptyList()
val result = mutableListOf<ProcessInfo>()
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<ProcessInfo> {
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<ProcessInfo>(compareBy({ it.name }, { it.isIsolated }))
processSet += packageInfo.activities.toProcessList()
processSet += packageInfo.services.toProcessList()
processSet += packageInfo.receivers.toProcessList()
processSet += packageInfo.providers.toProcessList()
return processSet
}
companion object { companion object {
operator fun invoke(
info: ApplicationInfo,
pm: PackageManager,
denyList: List<CmdlineListItem>,
): 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<out ComponentInfo>?.toProcessList() =
orEmpty().map { createProcess(it.getProcName()) }
fun Array<ServiceInfo>?.toServiceProcessList(): List<ProcessInfo> {
if (this == null) return emptyList()
val result = mutableListOf<ProcessInfo>()
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<ProcessInfo>(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( fun webViewZygote(
pm: PackageManager, pm: PackageManager,
denyList: List<CmdlineListItem>, denyList: List<CmdlineListItem>,
label: String, label: String,
): AppProcessInfo { ): AppProcessInfo {
val info = ApplicationInfo().apply {
packageName = WEBVIEW_ZYGOTE_MAGIC
uid = WEBVIEW_ZYGOTE_UID
}
val enabled = denyList.any { val enabled = denyList.any {
it.packageName == WEBVIEW_ZYGOTE_MAGIC && it.packageName == WEBVIEW_ZYGOTE_MAGIC &&
it.process == WEBVIEW_ZYGOTE_MAGIC it.process == WEBVIEW_ZYGOTE_MAGIC
} }
return AppProcessInfo( return AppProcessInfo(
info, packageName = WEBVIEW_ZYGOTE_MAGIC,
pm, label = label,
denyList, isSystemApp = false,
labelOverride = label, isApp = true,
processesOverride = listOf( firstInstallTime = 0L,
lastUpdateTime = 0L,
processes = listOf(
ProcessInfo(WEBVIEW_ZYGOTE_MAGIC, WEBVIEW_ZYGOTE_MAGIC, enabled) ProcessInfo(WEBVIEW_ZYGOTE_MAGIC, WEBVIEW_ZYGOTE_MAGIC, enabled)
), ),
) )
@@ -147,15 +158,7 @@ class AppProcessInfo(
private val comparator = compareBy<AppProcessInfo>( private val comparator = compareBy<AppProcessInfo>(
{ it.label.lowercase(Locale.ROOT) }, { 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
}
@@ -72,7 +72,8 @@ import androidx.compose.ui.state.ToggleableState
import androidx.compose.ui.unit.DpOffset import androidx.compose.ui.unit.DpOffset
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.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.ui.component.verticalScrollbar
import com.topjohnwu.magisk.core.R as CoreR import com.topjohnwu.magisk.core.R as CoreR
@@ -91,9 +92,6 @@ fun DenyListScreen(
val sortBy by viewModel.sortBy.collectAsStateWithLifecycle() val sortBy by viewModel.sortBy.collectAsStateWithLifecycle()
val sortReverse by viewModel.sortReverse.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) val searchBackState = rememberNavigationEventState(currentInfo = NavigationEventInfo.None)
NavigationBackHandler( NavigationBackHandler(
state = searchBackState, state = searchBackState,
@@ -126,89 +124,16 @@ fun DenyListScreen(
} }
}, },
actions = { actions = {
Box { AppSortFilterActions(
IconButton( sortBy = sortBy,
onClick = { showSortMenu = true }, sortReverse = sortReverse,
) { onSortByChanged = { viewModel.setSortBy(it) },
Icon( onToggleSortReverse = { viewModel.toggleSortReverse() },
imageVector = Icons.AutoMirrored.Filled.Sort, showSystem = showSystem,
contentDescription = stringResource(CoreR.string.menu_sort), showOS = showOS,
) onShowSystemChanged = { viewModel.setShowSystem(it) },
} onShowOSChanged = { viewModel.setShowOS(it) },
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 scrollBehavior = scrollBehavior
) )
@@ -347,8 +272,8 @@ private fun DenyAppCard(
.padding(14.dp), .padding(14.dp),
verticalAlignment = Alignment.CenterVertically verticalAlignment = Alignment.CenterVertically
) { ) {
Image( AppIcon(
painter = rememberDrawablePainter(app.info.iconImage), packageName = app.info.packageName,
contentDescription = app.info.label, contentDescription = app.info.label,
modifier = Modifier.size(40.dp) modifier = Modifier.size(40.dp)
) )
@@ -1,10 +1,12 @@
package com.topjohnwu.magisk.ui.deny package com.topjohnwu.magisk.ui.deny
import android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES import android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES
import androidx.compose.runtime.Immutable
import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewModelScope
import com.topjohnwu.magisk.arch.AsyncLoadViewModel import com.topjohnwu.magisk.arch.AsyncLoadViewModel
import com.topjohnwu.magisk.core.AppContext import com.topjohnwu.magisk.core.AppContext
import com.topjohnwu.magisk.core.ktx.concurrentMap import com.topjohnwu.magisk.core.ktx.concurrentMap
import com.topjohnwu.magisk.ui.component.AppSortBy
import com.topjohnwu.superuser.Shell import com.topjohnwu.superuser.Shell
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.MutableStateFlow
@@ -19,8 +21,7 @@ import kotlinx.coroutines.flow.toCollection
import kotlinx.coroutines.flow.update import kotlinx.coroutines.flow.update
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
enum class SortBy { NAME, PACKAGE_NAME, INSTALL_TIME, UPDATE_TIME } @Immutable
data class DenyProcessState( data class DenyProcessState(
val process: ProcessInfo, val process: ProcessInfo,
val isEnabled: Boolean = process.isEnabled, val isEnabled: Boolean = process.isEnabled,
@@ -29,6 +30,7 @@ data class DenyProcessState(
if (process.isIsolated) "(isolated) ${process.name}*" else process.name if (process.isIsolated) "(isolated) ${process.name}*" else process.name
} }
@Immutable
data class DenyAppState( data class DenyAppState(
val info: AppProcessInfo, val info: AppProcessInfo,
val processes: List<DenyProcessState> = info.processes.map { DenyProcessState(it) }, val processes: List<DenyProcessState> = info.processes.map { DenyProcessState(it) },
@@ -66,8 +68,8 @@ class DenyListViewModel : AsyncLoadViewModel() {
private val _showOS = MutableStateFlow(false) private val _showOS = MutableStateFlow(false)
val showOS: StateFlow<Boolean> = _showOS.asStateFlow() val showOS: StateFlow<Boolean> = _showOS.asStateFlow()
private val _sortBy = MutableStateFlow(SortBy.NAME) private val _sortBy = MutableStateFlow(AppSortBy.NAME)
val sortBy: StateFlow<SortBy> = _sortBy.asStateFlow() val sortBy: StateFlow<AppSortBy> = _sortBy.asStateFlow()
private val _sortReverse = MutableStateFlow(false) private val _sortReverse = MutableStateFlow(false)
val sortReverse: StateFlow<Boolean> = _sortReverse.asStateFlow() val sortReverse: StateFlow<Boolean> = _sortReverse.asStateFlow()
@@ -80,14 +82,14 @@ class DenyListViewModel : AsyncLoadViewModel() {
val q = args[1] as String val q = args[1] as String
val showSys = args[2] as Boolean val showSys = args[2] as Boolean
val showOS = args[3] 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 reverse = args[5] as Boolean
val filtered = apps.filter { app -> val filtered = apps.filter { app ->
val passFilter = app.isChecked || val passFilter = app.isChecked ||
app.initiallyChecked || app.initiallyChecked ||
((showSys || !app.info.isSystemApp()) && ((showSys || !app.info.isSystemApp) &&
((showSys && showOS) || app.info.isApp())) ((showSys && showOS) || app.info.isApp))
val passQuery = q.isBlank() || val passQuery = q.isBlank() ||
app.info.label.contains(q, true) || app.info.label.contains(q, true) ||
app.info.packageName.contains(q, true) || app.info.packageName.contains(q, true) ||
@@ -96,10 +98,10 @@ class DenyListViewModel : AsyncLoadViewModel() {
} }
val secondary: Comparator<DenyAppState> = when (sort) { val secondary: Comparator<DenyAppState> = when (sort) {
SortBy.NAME -> compareBy(String.CASE_INSENSITIVE_ORDER) { it.info.label } AppSortBy.NAME -> compareBy(String.CASE_INSENSITIVE_ORDER) { it.info.label }
SortBy.PACKAGE_NAME -> compareBy(String.CASE_INSENSITIVE_ORDER) { it.info.packageName } AppSortBy.PACKAGE_NAME -> compareBy(String.CASE_INSENSITIVE_ORDER) { it.info.packageName }
SortBy.INSTALL_TIME -> compareByDescending { it.info.firstInstallTime } AppSortBy.INSTALL_TIME -> compareByDescending { it.info.firstInstallTime }
SortBy.UPDATE_TIME -> compareByDescending { it.info.lastUpdateTime } AppSortBy.UPDATE_TIME -> compareByDescending { it.info.lastUpdateTime }
} }
val comparator = compareBy<DenyAppState> { !it.initiallyChecked } val comparator = compareBy<DenyAppState> { !it.initiallyChecked }
.then(if (reverse) secondary.reversed() else secondary) .then(if (reverse) secondary.reversed() else secondary)
@@ -112,7 +114,7 @@ class DenyListViewModel : AsyncLoadViewModel() {
if (!v) _showOS.value = false if (!v) _showOS.value = false
} }
fun setShowOS(v: Boolean) { _showOS.value = v } 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 toggleSortReverse() { _sortReverse.value = !_sortReverse.value }
fun toggleExpanded(app: DenyAppState) { fun toggleExpanded(app: DenyAppState) {
@@ -118,10 +118,11 @@ fun FlashScreen(
} }
) { padding -> ) { padding ->
TerminalScreen( TerminalScreen(
emulator = viewModel.emulator,
modifier = Modifier modifier = Modifier
.fillMaxSize() .fillMaxSize()
.padding(padding), .padding(padding),
onEmulatorCreated = { viewModel.onEmulatorCreated(it) }, onResized = viewModel::onTerminalResized,
) )
} }
} }
@@ -50,19 +50,26 @@ class FlashViewModel : BaseViewModel() {
var flashUri: Uri? = null var flashUri: Uri? = null
var usbDevice: String? = null var usbDevice: String? = null
private var emulator: TerminalEmulator? = null val emulator = TerminalEmulator(
private val emulatorReady = CompletableDeferred<TerminalEmulator>() columns = 256,
rows = 40,
cellWidthPixels = 0,
cellHeightPixels = 0,
transcriptRows = null,
)
fun onEmulatorCreated(emu: TerminalEmulator) { private val terminalReady = CompletableDeferred<Unit>()
emulator = emu
emulatorReady.complete(emu) /** Called by the UI once the terminal has been sized to its viewport. */
fun onTerminalResized() {
terminalReady.complete(Unit)
} }
private val logItems = mutableListOf<String>().synchronized() private val logItems = mutableListOf<String>().synchronized()
private val outItems = object : CallbackList<String>() { private val outItems = object : CallbackList<String>() {
override fun onAddElement(e: String?) { override fun onAddElement(e: String?) {
e ?: return e ?: return
emulator?.appendLineOnMain(e) emulator.appendLineOnMain(e)
if (!e.startsWith('\r')) { if (!e.startsWith('\r')) {
logItems.add(e) logItems.add(e)
} }
@@ -77,11 +84,10 @@ class FlashViewModel : BaseViewModel() {
val usb = usbDevice val usb = usbDevice
viewModelScope.launch { viewModelScope.launch {
val emu = emulatorReady.await()
when (action) { when (action) {
Const.Value.FLASH_ZIP -> { Const.Value.FLASH_ZIP -> {
uri ?: return@launch uri ?: return@launch
flashZip(emu, uri) flashZip(emulator, uri)
} }
Const.Value.UNINSTALL -> { Const.Value.UNINSTALL -> {
_showReboot.value = false _showReboot.value = false
@@ -158,9 +164,13 @@ class FlashViewModel : BaseViewModel() {
val (dir, zipFile, displayName) = prepResult 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) { val success = withContext(Dispatchers.IO) {
runSuCommand( runSuCommand(
emu, emu, columns, rows,
"echo '- Installing $displayName'; " + "echo '- Installing $displayName'; " +
"sh $dir/update-binary dummy 1 '${zipFile.absolutePath}'; " + "sh $dir/update-binary dummy 1 '${zipFile.absolutePath}'; " +
"EXIT=\$?; " + "EXIT=\$?; " +
@@ -180,8 +190,8 @@ class FlashViewModel : BaseViewModel() {
) )
val file = MediaStoreUtils.getFile(name) val file = MediaStoreUtils.getFile(name)
file.uri.outputStream().bufferedWriter().use { writer -> file.uri.outputStream().bufferedWriter().use { writer ->
val transcript = emulator?.screen?.transcriptText val transcript = emulator.screen.transcriptText
if (flashAction == Const.Value.FLASH_ZIP && transcript != null) { if (flashAction == Const.Value.FLASH_ZIP) {
writer.write(transcript) writer.write(transcript)
} else { } else {
synchronized(logItems) { synchronized(logItems) {
@@ -192,7 +202,7 @@ class FlashViewModel : BaseViewModel() {
} }
} }
} }
showSnackbar(file.toString()) showToast(file.toString())
} }
} }
@@ -1,8 +1,6 @@
package com.topjohnwu.magisk.ui.home package com.topjohnwu.magisk.ui.home
import android.os.Build import android.os.Build
import android.os.Handler
import android.os.Looper
import android.os.PowerManager import android.os.PowerManager
import android.widget.Toast import android.widget.Toast
import androidx.compose.foundation.background 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.install.InstallViewModel
import com.topjohnwu.magisk.ui.navigation.LocalNavigator import com.topjohnwu.magisk.ui.navigation.LocalNavigator
import com.topjohnwu.magisk.ui.navigation.Route import com.topjohnwu.magisk.ui.navigation.Route
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File import java.io.File
import com.topjohnwu.magisk.core.R as CoreR import com.topjohnwu.magisk.core.R as CoreR
@@ -193,9 +194,11 @@ fun HomeScreen(
Toast.LENGTH_LONG Toast.LENGTH_LONG
) )
if (success) { if (success) {
@Suppress("DEPRECATION") // The reboot toast has been shown; don't let leaving this screen cancel it
Handler(Looper.getMainLooper()) withContext(NonCancellable) {
.postDelayed({ reboot() }, 5000) delay(5000)
reboot()
}
} }
} }
} }
@@ -123,8 +123,8 @@ class HomeViewModel(
fun onManagerPressed() { fun onManagerPressed() {
when (_uiState.value.appState) { when (_uiState.value.appState) {
State.LOADING -> showSnackbar(CoreR.string.loading) State.LOADING -> showToast(CoreR.string.loading)
State.INVALID -> showSnackbar(CoreR.string.no_connection) State.INVALID -> showToast(CoreR.string.no_connection)
else -> _uiState.update { it.copy(showManagerInstall = true) } else -> _uiState.update { it.copy(showManagerInstall = true) }
} }
} }
@@ -93,18 +93,18 @@ class LogViewModel(
ProcessBuilder("logcat", "-d").start() ProcessBuilder("logcat", "-d").start()
.inputStream.reader().use { it.copyTo(file) } .inputStream.reader().use { it.copyTo(file) }
} }
showSnackbar(logFile.toString()) showToast(logFile.toString())
} }
} }
fun clearMagiskLog() = repo.clearMagiskLogs { fun clearMagiskLog() = repo.clearMagiskLogs {
showSnackbar(R.string.logs_cleared) showToast(R.string.logs_cleared)
startLoading() startLoading()
} }
fun clearLog() = viewModelScope.launch { fun clearLog() = viewModelScope.launch {
repo.clearLogs() repo.clearLogs()
showSnackbar(R.string.logs_cleared) showToast(R.string.logs_cleared)
startLoading() startLoading()
} }
} }
@@ -103,10 +103,11 @@ fun ActionScreen(
} }
) { padding -> ) { padding ->
TerminalScreen( TerminalScreen(
emulator = viewModel.emulator,
modifier = Modifier modifier = Modifier
.fillMaxSize() .fillMaxSize()
.padding(padding), .padding(padding),
onEmulatorCreated = { viewModel.onEmulatorCreated(it) }, onResized = viewModel::onTerminalResized,
) )
} }
} }
@@ -28,21 +28,30 @@ class ActionViewModel : BaseViewModel() {
var actionId: String = "" var actionId: String = ""
var actionName: String = "" var actionName: String = ""
private var emulator: TerminalEmulator? = null val emulator = TerminalEmulator(
private val emulatorReady = CompletableDeferred<TerminalEmulator>() columns = 256,
rows = 40,
cellWidthPixels = 0,
cellHeightPixels = 0,
transcriptRows = null,
)
fun onEmulatorCreated(emu: TerminalEmulator) { private val terminalReady = CompletableDeferred<Unit>()
emulator = emu
emulatorReady.complete(emu) /** Called by the UI once the terminal has been sized to its viewport. */
fun onTerminalResized() {
terminalReady.complete(Unit)
} }
fun startRunAction() { fun startRunAction() {
viewModelScope.launch { 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) { val success = withContext(Dispatchers.IO) {
runSuCommand( runSuCommand(
emu, emulator, columns, rows,
"cd /data/adb/modules/$actionId && sh ./action.sh" "cd /data/adb/modules/$actionId && sh ./action.sh"
) )
} }
@@ -59,12 +68,10 @@ class ActionViewModel : BaseViewModel() {
) )
val file = MediaStoreUtils.getFile(name) val file = MediaStoreUtils.getFile(name)
file.uri.outputStream().bufferedWriter().use { writer -> file.uri.outputStream().bufferedWriter().use { writer ->
val transcript = emulator?.screen?.transcriptText val transcript = emulator.screen.transcriptText
if (transcript != null) { writer.write(transcript)
writer.write(transcript)
}
} }
showSnackbar(file.toString()) showToast(file.toString())
} }
} }
} }
@@ -92,6 +92,7 @@ import com.topjohnwu.magisk.core.R as CoreR
@Composable @Composable
fun ModuleScreen( fun ModuleScreen(
viewModel: ModuleViewModel, viewModel: ModuleViewModel,
isFabAtBottom: Boolean,
modifier: Modifier = Modifier, modifier: Modifier = Modifier,
onRegisterFab: (((() -> Unit)?) -> Unit)? = null, onRegisterFab: (((() -> Unit)?) -> Unit)? = null,
contentFocusRequester: FocusRequester? = null, contentFocusRequester: FocusRequester? = null,
@@ -220,6 +221,9 @@ fun ModuleScreen(
return@Scaffold 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() val gridState = rememberLazyStaggeredGridState()
// Staggered, as cards expand; 360dp leaves room for the action buttons row // Staggered, as cards expand; 360dp leaves room for the action buttons row
LazyVerticalStaggeredGrid( LazyVerticalStaggeredGrid(
@@ -234,14 +238,14 @@ fun ModuleScreen(
gridState, gridState,
contentPadding = PaddingValues( contentPadding = PaddingValues(
top = padding.calculateTopPadding() + 4.dp, top = padding.calculateTopPadding() + 4.dp,
bottom = padding.calculateBottomPadding() + 80.dp, bottom = scrollbarBottomPadding,
), ),
), ),
contentPadding = PaddingValues( contentPadding = PaddingValues(
start = 12.dp, start = 12.dp,
top = padding.calculateTopPadding() + 16.dp, top = padding.calculateTopPadding() + 16.dp,
end = 12.dp, end = 12.dp,
bottom = padding.calculateBottomPadding() + 92.dp, bottom = listBottomPadding,
), ),
verticalItemSpacing = 8.dp, verticalItemSpacing = 8.dp,
horizontalArrangement = Arrangement.spacedBy(8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp),
@@ -183,7 +183,7 @@ class SettingsViewModel : BaseViewModel() {
) )
} }
if (isMismatch) { if (isMismatch) {
showSnackbar(CoreR.string.reboot_apply_change) showToast(CoreR.string.reboot_apply_change)
} }
} }
@@ -1,7 +1,5 @@
package com.topjohnwu.magisk.ui.superuser 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.Row
import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth 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.semantics.semantics
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp 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 import com.topjohnwu.magisk.core.R as CoreR
@Composable @Composable
@@ -50,9 +48,8 @@ internal fun SharedUidBadge(modifier: Modifier = Modifier) {
@Composable @Composable
fun SuperuserAppListItem( fun SuperuserAppListItem(
icon: Drawable,
title: String,
packageName: String, packageName: String,
title: String,
isSharedUid: Boolean, isSharedUid: Boolean,
modifier: Modifier = Modifier, modifier: Modifier = Modifier,
contentDescription: String? = null, contentDescription: String? = null,
@@ -61,8 +58,8 @@ fun SuperuserAppListItem(
ListItem( ListItem(
modifier = modifier, modifier = modifier,
leadingContent = { leadingContent = {
Image( AppIcon(
painter = rememberDrawablePainter(icon), packageName = packageName,
contentDescription = null, contentDescription = null,
modifier = Modifier.size(40.dp) modifier = Modifier.size(40.dp)
) )
@@ -94,9 +91,8 @@ fun SuperuserAppListItem(
@Composable @Composable
fun SuperuserAppCard( fun SuperuserAppCard(
icon: Drawable,
title: String,
packageName: String, packageName: String,
title: String,
isSharedUid: Boolean, isSharedUid: Boolean,
modifier: Modifier = Modifier, modifier: Modifier = Modifier,
onClick: (() -> Unit)? = null, onClick: (() -> Unit)? = null,
@@ -110,9 +106,8 @@ fun SuperuserAppCard(
) { ) {
val itemContent = @Composable { val itemContent = @Composable {
SuperuserAppListItem( SuperuserAppListItem(
icon = icon,
title = title,
packageName = packageName, packageName = packageName,
title = title,
isSharedUid = isSharedUid, isSharedUid = isSharedUid,
contentDescription = contentDescription, contentDescription = contentDescription,
trailingContent = trailingContent, trailingContent = trailingContent,
@@ -38,6 +38,7 @@ import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier 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.res.stringResource
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.google.accompanist.drawablepainter.rememberDrawablePainter
import com.topjohnwu.magisk.core.Config 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.ConfirmResult
import com.topjohnwu.magisk.ui.component.SettingsSwitch import com.topjohnwu.magisk.ui.component.SettingsSwitch
import com.topjohnwu.magisk.ui.component.rememberBiometricAuth import com.topjohnwu.magisk.ui.component.rememberBiometricAuth
import com.topjohnwu.magisk.ui.component.rememberConfirmDialog import com.topjohnwu.magisk.ui.component.rememberConfirmDialog
import com.topjohnwu.magisk.ui.component.verticalScrollbar import com.topjohnwu.magisk.ui.component.verticalScrollbar
import com.topjohnwu.magisk.ui.navigation.LocalNavigator
import com.topjohnwu.magisk.ui.navigation.Route
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import com.topjohnwu.magisk.core.R as CoreR import com.topjohnwu.magisk.core.R as CoreR
@@ -64,8 +67,22 @@ fun SuperuserDetailScreen(
modifier: Modifier = Modifier, modifier: Modifier = Modifier,
) { ) {
val uiState by viewModel.uiState.collectAsStateWithLifecycle() 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() 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 scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior()
val scrollState = rememberScrollState() val scrollState = rememberScrollState()
val scope = rememberCoroutineScope() val scope = rememberCoroutineScope()
@@ -135,8 +152,8 @@ fun SuperuserDetailScreen(
modifier = Modifier.padding(18.dp), modifier = Modifier.padding(18.dp),
verticalAlignment = Alignment.CenterVertically verticalAlignment = Alignment.CenterVertically
) { ) {
Image( AppIcon(
painter = rememberDrawablePainter(item.icon), packageName = item.packageName,
contentDescription = item.appName, contentDescription = item.appName,
modifier = Modifier.size(48.dp) modifier = Modifier.size(48.dp)
) )
@@ -160,7 +177,7 @@ fun SuperuserDetailScreen(
color = MaterialTheme.colorScheme.onSurfaceVariant color = MaterialTheme.colorScheme.onSurfaceVariant
) )
Text( Text(
text = "UID: ${item.policy.uid}", text = "UID: ${item.uid}",
style = MaterialTheme.typography.bodyMedium, style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant 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<PolicyItem> = emptyList()
}
@@ -17,15 +17,10 @@ import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.grid.rememberLazyGridState import androidx.compose.foundation.lazy.grid.rememberLazyGridState
import androidx.compose.material.icons.Icons import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack 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.Close
import androidx.compose.material.icons.filled.Search import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.Tune
import androidx.compose.material3.Checkbox import androidx.compose.material3.Checkbox
import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton import androidx.compose.material3.IconButton
@@ -39,9 +34,6 @@ import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.navigationevent.NavigationEventInfo import androidx.navigationevent.NavigationEventInfo
import androidx.navigationevent.compose.NavigationBackHandler import androidx.navigationevent.compose.NavigationBackHandler
import androidx.navigationevent.compose.rememberNavigationEventState import androidx.navigationevent.compose.rememberNavigationEventState
@@ -50,9 +42,9 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.nestedscroll.nestedScroll import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.DpOffset
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.topjohnwu.magisk.ui.component.AppSortFilterActions
import com.topjohnwu.magisk.ui.component.rememberBiometricAuth import com.topjohnwu.magisk.ui.component.rememberBiometricAuth
import com.topjohnwu.magisk.ui.component.verticalScrollbar import com.topjohnwu.magisk.ui.component.verticalScrollbar
import com.topjohnwu.magisk.core.R as CoreR import com.topjohnwu.magisk.core.R as CoreR
@@ -73,8 +65,6 @@ fun SuperuserGrantScreen(
val sortBy by viewModel.sortBy.collectAsStateWithLifecycle() val sortBy by viewModel.sortBy.collectAsStateWithLifecycle()
val sortReverse by viewModel.sortReverse.collectAsStateWithLifecycle() val sortReverse by viewModel.sortReverse.collectAsStateWithLifecycle()
var showSortMenu by remember { mutableStateOf(false) }
var showFilterMenu by remember { mutableStateOf(false) }
val requireAuth = rememberBiometricAuth() val requireAuth = rememberBiometricAuth()
val searchBackState = rememberNavigationEventState(currentInfo = NavigationEventInfo.None) val searchBackState = rememberNavigationEventState(currentInfo = NavigationEventInfo.None)
@@ -109,85 +99,16 @@ fun SuperuserGrantScreen(
} }
}, },
actions = { actions = {
Box { AppSortFilterActions(
IconButton(onClick = { showSortMenu = true }) { sortBy = sortBy,
Icon( sortReverse = sortReverse,
imageVector = Icons.AutoMirrored.Filled.Sort, onSortByChanged = { viewModel.setSortBy(it) },
contentDescription = stringResource(CoreR.string.menu_sort), onToggleSortReverse = { viewModel.toggleSortReverse() },
) showSystem = showSystem,
} showOS = showOS,
DropdownMenu( onShowSystemChanged = { viewModel.setShowSystem(it) },
expanded = showSortMenu, onShowOSChanged = { viewModel.setShowOS(it) },
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 scrollBehavior = scrollBehavior
) )
@@ -299,9 +220,8 @@ private fun SuGrantAppCard(
modifier: Modifier = Modifier modifier: Modifier = Modifier
) { ) {
SuperuserAppCard( SuperuserAppCard(
icon = app.info.icon,
title = app.info.label,
packageName = app.info.packageName, packageName = app.info.packageName,
title = app.info.label,
isSharedUid = app.info.isSharedUid, isSharedUid = app.info.isSharedUid,
checked = app.isGranted, checked = app.isGranted,
onCheckedChange = { onToggle() }, onCheckedChange = { onToggle() },
@@ -2,8 +2,8 @@ package com.topjohnwu.magisk.ui.superuser
import android.content.pm.ApplicationInfo import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES import android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES
import android.graphics.drawable.Drawable
import android.os.Process import android.os.Process
import androidx.compose.runtime.Immutable
import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewModelScope
import com.topjohnwu.magisk.arch.AsyncLoadViewModel import com.topjohnwu.magisk.arch.AsyncLoadViewModel
import com.topjohnwu.magisk.core.AppContext 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.ktx.getLabel
import com.topjohnwu.magisk.core.model.su.SuPolicy import com.topjohnwu.magisk.core.model.su.SuPolicy
import com.topjohnwu.magisk.core.su.SuEvents import com.topjohnwu.magisk.core.su.SuEvents
import com.topjohnwu.magisk.ui.component.AppSortBy
import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.MutableStateFlow
@@ -31,12 +32,10 @@ import kotlinx.coroutines.withContext
import timber.log.Timber import timber.log.Timber
import java.util.Locale import java.util.Locale
enum class SortBy { NAME, PACKAGE_NAME, INSTALL_TIME, UPDATE_TIME } @Immutable
data class SuGrantAppInfo( data class SuGrantAppInfo(
val label: String, val label: String,
val packageName: String, val packageName: String,
val icon: Drawable,
val uid: Int, val uid: Int,
val isSystemApp: Boolean, val isSystemApp: Boolean,
val isApp: Boolean, val isApp: Boolean,
@@ -53,6 +52,7 @@ data class SuGrantAppInfo(
} }
} }
@Immutable
data class SuGrantAppState( data class SuGrantAppState(
val info: SuGrantAppInfo, val info: SuGrantAppInfo,
val isGranted: Boolean, val isGranted: Boolean,
@@ -77,8 +77,8 @@ class SuperuserGrantViewModel(
private val _showOS = MutableStateFlow(false) private val _showOS = MutableStateFlow(false)
val showOS: StateFlow<Boolean> = _showOS.asStateFlow() val showOS: StateFlow<Boolean> = _showOS.asStateFlow()
private val _sortBy = MutableStateFlow(SortBy.NAME) private val _sortBy = MutableStateFlow(AppSortBy.NAME)
val sortBy: StateFlow<SortBy> = _sortBy.asStateFlow() val sortBy: StateFlow<AppSortBy> = _sortBy.asStateFlow()
private val _sortReverse = MutableStateFlow(false) private val _sortReverse = MutableStateFlow(false)
val sortReverse: StateFlow<Boolean> = _sortReverse.asStateFlow() val sortReverse: StateFlow<Boolean> = _sortReverse.asStateFlow()
@@ -91,7 +91,7 @@ class SuperuserGrantViewModel(
val q = args[1] as String val q = args[1] as String
val showSys = args[2] as Boolean val showSys = args[2] as Boolean
val showOS = args[3] 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 reverse = args[5] as Boolean
val filtered = apps.filter { app -> val filtered = apps.filter { app ->
@@ -108,13 +108,13 @@ class SuperuserGrantViewModel(
} }
val secondary: Comparator<SuGrantAppState> = when (sort) { val secondary: Comparator<SuGrantAppState> = when (sort) {
SortBy.NAME -> compareBy<SuGrantAppState, String>(String.CASE_INSENSITIVE_ORDER) { it.info.label } AppSortBy.NAME -> compareBy<SuGrantAppState, String>(String.CASE_INSENSITIVE_ORDER) { it.info.label }
.thenBy { it.info.packageName } .thenBy { it.info.packageName }
SortBy.PACKAGE_NAME -> compareBy(String.CASE_INSENSITIVE_ORDER) { it.info.packageName } AppSortBy.PACKAGE_NAME -> compareBy(String.CASE_INSENSITIVE_ORDER) { it.info.packageName }
SortBy.INSTALL_TIME -> compareByDescending<SuGrantAppState> { it.info.firstInstallTime } AppSortBy.INSTALL_TIME -> compareByDescending<SuGrantAppState> { it.info.firstInstallTime }
.thenBy(String.CASE_INSENSITIVE_ORDER) { it.info.label } .thenBy(String.CASE_INSENSITIVE_ORDER) { it.info.label }
.thenBy { it.info.packageName } .thenBy { it.info.packageName }
SortBy.UPDATE_TIME -> compareByDescending<SuGrantAppState> { it.info.lastUpdateTime } AppSortBy.UPDATE_TIME -> compareByDescending<SuGrantAppState> { it.info.lastUpdateTime }
.thenBy(String.CASE_INSENSITIVE_ORDER) { it.info.label } .thenBy(String.CASE_INSENSITIVE_ORDER) { it.info.label }
.thenBy { it.info.packageName } .thenBy { it.info.packageName }
} }
@@ -129,7 +129,7 @@ class SuperuserGrantViewModel(
if (!v) _showOS.value = false if (!v) _showOS.value = false
} }
fun setShowOS(v: Boolean) { _showOS.value = v } 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 toggleSortReverse() { _sortReverse.value = !_sortReverse.value }
fun toggleGrant(app: SuGrantAppState) { fun toggleGrant(app: SuGrantAppState) {
@@ -150,7 +150,6 @@ class SuperuserGrantViewModel(
val existing = policyDB.fetch(app.info.uid) val existing = policyDB.fetch(app.info.uid)
val suPolicy = existing ?: SuPolicy(app.info.uid) val suPolicy = existing ?: SuPolicy(app.info.uid)
suPolicy.policy = if (Config.suRestrict) SuPolicy.RESTRICT else SuPolicy.ALLOW suPolicy.policy = if (Config.suRestrict) SuPolicy.RESTRICT else SuPolicy.ALLOW
suPolicy.remain = 0L
policyDB.update(suPolicy) policyDB.update(suPolicy)
} else { } else {
policyDB.delete(app.info.uid) policyDB.delete(app.info.uid)
@@ -220,13 +219,11 @@ class SuperuserGrantViewModel(
} }
val isSharedUid = pkg?.sharedUserId != null val isSharedUid = pkg?.sharedUserId != null
val label = appInfo.getLabel(pm) val label = appInfo.getLabel(pm)
val icon = runCatching { appInfo.loadIcon(pm) }.getOrDefault(pm.defaultActivityIcon)
val isSystemApp = (appInfo.flags and ApplicationInfo.FLAG_SYSTEM) != 0 val isSystemApp = (appInfo.flags and ApplicationInfo.FLAG_SYSTEM) != 0
val isApp = Process.isApplicationUid(appInfo.uid) val isApp = Process.isApplicationUid(appInfo.uid)
val suAppInfo = SuGrantAppInfo( val suAppInfo = SuGrantAppInfo(
label = label, label = label,
packageName = appInfo.packageName, packageName = appInfo.packageName,
icon = icon,
uid = appInfo.uid, uid = appInfo.uid,
isSystemApp = isSystemApp, isSystemApp = isSystemApp,
isApp = isApp, isApp = isApp,
@@ -49,6 +49,7 @@ import com.topjohnwu.magisk.core.R as CoreR
@Composable @Composable
fun SuperuserScreen( fun SuperuserScreen(
viewModel: SuperuserViewModel, viewModel: SuperuserViewModel,
isFabAtBottom: Boolean,
modifier: Modifier = Modifier, modifier: Modifier = Modifier,
onRegisterFab: (((() -> Unit)?) -> Unit)? = null, onRegisterFab: (((() -> Unit)?) -> Unit)? = null,
contentFocusRequester: FocusRequester? = null, contentFocusRequester: FocusRequester? = null,
@@ -131,6 +132,9 @@ fun SuperuserScreen(
return@Scaffold 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() val gridState = rememberLazyGridState()
LazyVerticalGrid( LazyVerticalGrid(
columns = GridCells.Adaptive(320.dp), columns = GridCells.Adaptive(320.dp),
@@ -144,21 +148,21 @@ fun SuperuserScreen(
gridState, gridState,
contentPadding = PaddingValues( contentPadding = PaddingValues(
top = padding.calculateTopPadding() + 4.dp, top = padding.calculateTopPadding() + 4.dp,
bottom = padding.calculateBottomPadding() + 80.dp, bottom = scrollbarBottomPadding,
), ),
), ),
contentPadding = PaddingValues( contentPadding = PaddingValues(
start = 12.dp, start = 12.dp,
top = padding.calculateTopPadding() + 16.dp, top = padding.calculateTopPadding() + 16.dp,
end = 12.dp, end = 12.dp,
bottom = padding.calculateBottomPadding() + 92.dp, bottom = listBottomPadding,
), ),
verticalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp),
) { ) {
items( items(
items = uiState.policies, items = uiState.policies,
key = { "${it.policy.uid}_${it.packageName}" }, key = { "${it.uid}_${it.packageName}" },
contentType = { "PolicyCard" } contentType = { "PolicyCard" }
) { item -> ) { item ->
val isLast = item == uiState.policies.lastOrNull() val isLast = item == uiState.policies.lastOrNull()
@@ -169,7 +173,7 @@ fun SuperuserScreen(
viewModel.togglePolicy(item) viewModel.togglePolicy(item)
} }
}, },
onDetail = { navigator.push(Route.SuperuserDetail(item.policy.uid)) }, onDetail = { navigator.push(Route.SuperuserDetail(item.uid)) },
modifier = if (isLast && contentFocusRequester != null) { modifier = if (isLast && contentFocusRequester != null) {
Modifier.focusRequester(contentFocusRequester) Modifier.focusRequester(contentFocusRequester)
} else Modifier, } else Modifier,
@@ -187,9 +191,8 @@ private fun PolicyCard(
modifier: Modifier = Modifier modifier: Modifier = Modifier
) { ) {
SuperuserAppCard( SuperuserAppCard(
icon = item.icon,
title = item.title,
packageName = item.packageName, packageName = item.packageName,
title = item.title,
isSharedUid = item.isSharedUid, isSharedUid = item.isSharedUid,
onClick = onDetail, onClick = onDetail,
contentDescription = item.appName, contentDescription = item.appName,
@@ -2,8 +2,9 @@ package com.topjohnwu.magisk.ui.superuser
import android.content.pm.PackageManager import android.content.pm.PackageManager
import android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES import android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES
import android.graphics.drawable.Drawable
import android.os.Process import android.os.Process
import androidx.annotation.MainThread
import androidx.compose.runtime.Immutable
import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewModelScope
import com.topjohnwu.magisk.arch.AsyncLoadViewModel import com.topjohnwu.magisk.arch.AsyncLoadViewModel
import com.topjohnwu.magisk.core.AppContext import com.topjohnwu.magisk.core.AppContext
@@ -22,28 +23,37 @@ import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.debounce import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.update import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import java.util.Locale import java.util.Locale
import java.util.concurrent.ConcurrentHashMap
@Immutable
data class PolicyItem( data class PolicyItem(
var policy: SuPolicy, val uid: Int,
val packageName: String, val packageName: String,
val isSharedUid: Boolean,
val icon: Drawable,
val appName: String, val appName: String,
val policyValue: Int = policy.policy, val isSharedUid: Boolean,
val notification: Boolean = policy.notification, val policyValue: Int,
val logging: Boolean = policy.logging, val notification: Boolean,
val logging: Boolean,
) { ) {
val title get() = appName val title: String get() = appName
val isEnabled get() = policyValue >= SuPolicy.ALLOW val isEnabled: Boolean get() = policyValue >= SuPolicy.ALLOW
val isRestricted get() = policyValue == SuPolicy.RESTRICT val isRestricted: Boolean get() = policyValue == SuPolicy.RESTRICT
} }
class SuperuserViewModel( class SuperuserViewModel(
private val db: PolicyDao private val db: PolicyDao
) : AsyncLoadViewModel() { ) : 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<Int, SuPolicy>()
init { init {
@OptIn(FlowPreview::class) @OptIn(FlowPreview::class)
viewModelScope.launch { viewModelScope.launch {
@@ -66,47 +76,58 @@ class SuperuserViewModel(
return return
} }
_uiState.update { it.copy(loading = true) } _uiState.update { it.copy(loading = true) }
withContext(Dispatchers.IO) { writeLock.withLock {
db.deleteOutdated() val loaded = withContext(Dispatchers.IO) {
db.delete(AppContext.applicationInfo.uid) db.deleteOutdated()
val policies = ArrayList<PolicyItem>() db.delete(AppContext.applicationInfo.uid)
val pm = AppContext.packageManager val policies = ArrayList<PolicyItem>()
for (policy in db.fetchAll()) { val pm = AppContext.packageManager
val pkgs = for (policy in db.fetchAll()) {
if (policy.uid == Process.SYSTEM_UID) arrayOf("android") val pkgs =
else pm.getPackagesForUid(PolicyDao.denormalizeUid(policy.uid)) if (policy.uid == Process.SYSTEM_UID) arrayOf("android")
if (pkgs == null) { else pm.getPackagesForUid(PolicyDao.denormalizeUid(policy.uid))
db.delete(policy.uid) if (pkgs == null) {
continue 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
} }
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()) { policies.sortWith(compareBy(
db.delete(policy.uid) { it.appName.lowercase(Locale.ROOT) },
continue { 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) } _uiState.update { it.copy(suRestrict = Config.suRestrict) }
} }
val requiresAuth get() = Config.suAuth
fun performDelete(item: PolicyItem, onDeleted: () -> Unit = {}) { fun performDelete(item: PolicyItem, onDeleted: () -> Unit = {}) {
viewModelScope.launch { viewModelScope.launch {
db.delete(item.policy.uid) writeLock.withLock {
_uiState.update { state -> db.delete(item.uid)
state.copy(policies = state.policies.filter { it.policy.uid != item.policy.uid }) pendingWrites.remove(item.uid)
_uiState.update { state ->
state.copy(policies = state.policies.filter { it.uid != item.uid })
}
} }
onDeleted() onDeleted()
} }
} }
fun updateNotify(item: PolicyItem) { /**
val newNotification = !item.notification * Apply [transform] to the latest state of every item with [uid], then persist the result.
item.policy.notification = newNotification * Deriving each change from the current state (instead of the item captured by the UI) and
viewModelScope.launch { * writing in order ensures quick consecutive edits cannot overwrite each other.
db.update(item.policy) */
_uiState.update { state -> @MainThread
state.copy( private fun updateItem(uid: Int, transform: (PolicyItem) -> PolicyItem): PolicyItem? {
policies = state.policies.map { // All state updates happen on the main thread, so this update is never retried
if (it.policy.uid == item.policy.uid) it.copy(notification = newNotification) else it var updated: PolicyItem? = null
} _uiState.update { state ->
) state.copy(
} policies = state.policies.map {
val res = if (newNotification) R.string.su_snack_notif_on else R.string.su_snack_notif_off if (it.uid == uid) transform(it).also { new -> updated = new } else it
showSnackbar(AppContext.getString(res, item.appName)) }
)
} }
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) { fun updateLogging(item: PolicyItem) {
val newLogging = !item.logging val updated = updateItem(item.uid) { it.copy(logging = !it.logging) } ?: return
item.policy.logging = newLogging val res = if (updated.logging) R.string.su_snack_log_on else R.string.su_snack_log_off
viewModelScope.launch { showToast(AppContext.getString(res, item.appName))
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
}
)
}
}
} }
fun togglePolicy(item: PolicyItem) { fun togglePolicy(item: PolicyItem) {
val newPolicy = if (item.isEnabled) SuPolicy.DENY else SuPolicy.ALLOW updateItem(item.uid) {
updatePolicy(item, newPolicy) it.copy(policyValue = if (it.isEnabled) SuPolicy.DENY else SuPolicy.ALLOW)
}
} }
fun toggleRestrict(item: PolicyItem) { fun toggleRestrict(item: PolicyItem) {
val newPolicy = if (item.isRestricted) SuPolicy.ALLOW else SuPolicy.RESTRICT updateItem(item.uid) {
updatePolicy(item, newPolicy) it.copy(policyValue = if (it.isRestricted) SuPolicy.ALLOW else SuPolicy.RESTRICT)
}
} }
} }
@@ -9,13 +9,17 @@ import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clipToBounds import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.draw.drawBehind import androidx.compose.ui.draw.drawBehind
@@ -34,20 +38,40 @@ private const val MIN_TERMINAL_COLUMNS = 256
@Composable @Composable
fun TerminalScreen( fun TerminalScreen(
emulator: TerminalEmulator,
modifier: Modifier = Modifier, modifier: Modifier = Modifier,
onEmulatorCreated: (TerminalEmulator) -> Unit = {}, onResized: () -> Unit = {},
) { ) {
val currentOnResized by rememberUpdatedState(onResized)
val density = LocalDensity.current val density = LocalDensity.current
val renderer = remember { val renderer = remember {
val textSizePx = with(density) { 12.sp.toPx().toInt() } val textSizePx = with(density) { 12.sp.toPx().toInt() }
TerminalRenderer(textSizePx, Typeface.MONOSPACE) TerminalRenderer(textSizePx, Typeface.MONOSPACE)
} }
var emulator by remember { mutableStateOf<TerminalEmulator?>(null) } var drawTrigger by remember { mutableLongStateOf(0L) }
var updateTick by remember { mutableIntStateOf(0) }
var topRow by remember { mutableIntStateOf(0) } var topRow by remember { mutableIntStateOf(0) }
var scrollX by remember { mutableFloatStateOf(0f) } var scrollX by remember { mutableFloatStateOf(0f) }
var scrolledToBottom by remember { mutableStateOf(true) } 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) { BoxWithConstraints(modifier = modifier) {
val widthPx = constraints.maxWidth.toFloat() val widthPx = constraints.maxWidth.toFloat()
@@ -57,35 +81,25 @@ fun TerminalScreen(
val rows = max(4, ((heightPx - renderer.fontLineSpacingAndAscent) / renderer.fontLineSpacing).toInt()) val rows = max(4, ((heightPx - renderer.fontLineSpacingAndAscent) / renderer.fontLineSpacing).toInt())
val lineHeight = renderer.fontLineSpacing.toFloat() val lineHeight = renderer.fontLineSpacing.toFloat()
@Suppress("UNUSED_EXPRESSION") fun getMaxScrollX(): Float {
updateTick val contentWidthPx = maxOf(widthPx, (maxUsedColumn + 2) * renderer.fontWidth)
val maxUsedCol = emulator?.maxUsedColumn ?: 0 return maxOf(0f, contentWidthPx - widthPx)
val contentWidthPx = maxOf(widthPx, (maxUsedCol + 2) * renderer.fontWidth) }
val maxScrollX = maxOf(0f, contentWidthPx - widthPx)
LaunchedEffect(cols, rows) { LaunchedEffect(cols, rows) {
val emu = emulator emulator.resize(cols, rows, renderer.fontWidth.toInt(), renderer.fontLineSpacing)
if (emu == null) { currentOnResized()
val newEmu = TerminalEmulator(cols, rows, renderer.fontWidth.toInt(), renderer.fontLineSpacing, null) }
newEmu.onScreenUpdate = {
if (scrolledToBottom) topRow = 0 // Keep scrollX in range when the viewport or content width changes
updateTick++ LaunchedEffect(widthPx) {
} snapshotFlow { getMaxScrollX() }.collect { maxScrollX ->
emulator = newEmu scrollX = scrollX.coerceIn(0f, maxScrollX)
onEmulatorCreated(newEmu)
} else {
emu.resize(cols, rows, renderer.fontWidth.toInt(), renderer.fontLineSpacing)
} }
} }
LaunchedEffect(maxScrollX) {
scrollX = scrollX.coerceIn(0f, maxScrollX)
}
val activeTranscriptRows = emulator?.screen?.activeTranscriptRows ?: 0
val verticalScrollableState = rememberScrollableState { delta -> val verticalScrollableState = rememberScrollableState { delta ->
val emu = emulator ?: return@rememberScrollableState 0f val minTop = -emulator.screen.activeTranscriptRows
val minTop = -emu.screen.activeTranscriptRows
val rowDelta = -(delta / lineHeight).toInt() val rowDelta = -(delta / lineHeight).toInt()
if (rowDelta != 0) { if (rowDelta != 0) {
val newTopRow = (topRow + rowDelta).coerceIn(minTop, 0) val newTopRow = (topRow + rowDelta).coerceIn(minTop, 0)
@@ -96,6 +110,7 @@ fun TerminalScreen(
} }
val horizontalScrollableState = rememberScrollableState { delta -> val horizontalScrollableState = rememberScrollableState { delta ->
val maxScrollX = getMaxScrollX()
val oldScrollX = scrollX val oldScrollX = scrollX
val newScrollX = (scrollX - delta).coerceIn(0f, maxScrollX) val newScrollX = (scrollX - delta).coerceIn(0f, maxScrollX)
scrollX = newScrollX scrollX = newScrollX
@@ -108,8 +123,8 @@ fun TerminalScreen(
.clipToBounds() .clipToBounds()
.background(Color.Black) .background(Color.Black)
.terminalScrollbar( .terminalScrollbar(
activeTranscriptRows = activeTranscriptRows, activeTranscriptRowsProvider = { transcriptRows },
topRow = topRow, topRowProvider = { topRow },
visibleRows = rows, visibleRows = rows,
onScrollToRow = { newRow -> onScrollToRow = { newRow ->
topRow = newRow topRow = newRow
@@ -118,8 +133,8 @@ fun TerminalScreen(
isScrollInProgress = verticalScrollableState.isScrollInProgress, isScrollInProgress = verticalScrollableState.isScrollInProgress,
) )
.terminalHorizontalScrollbar( .terminalHorizontalScrollbar(
scrollX = scrollX, scrollXProvider = { scrollX },
maxScrollX = maxScrollX, maxScrollXProvider = { getMaxScrollX() },
viewportWidth = widthPx, viewportWidth = widthPx,
onScrollToX = { newScrollX -> scrollX = newScrollX }, onScrollToX = { newScrollX -> scrollX = newScrollX },
isScrollInProgress = horizontalScrollableState.isScrollInProgress, isScrollInProgress = horizontalScrollableState.isScrollInProgress,
@@ -133,12 +148,11 @@ fun TerminalScreen(
state = horizontalScrollableState state = horizontalScrollableState
) )
.drawBehind { .drawBehind {
@Suppress("UNUSED_EXPRESSION") if (drawTrigger >= 0L) {
updateTick drawIntoCanvas { canvas ->
val emu = emulator ?: return@drawBehind canvas.nativeCanvas.withTranslation(-scrollX, 0f) {
drawIntoCanvas { canvas -> renderer.render(emulator, this, topRow, -1, -1, -1, -1)
canvas.nativeCanvas.withTranslation(-scrollX, 0f) { }
renderer.render(emu, this, topRow, -1, -1, -1, -1)
} }
} }
} }
@@ -7,10 +7,6 @@ import kotlinx.coroutines.withContext
open class MagiskDB { open class MagiskDB {
class Literal(
val str: String
)
suspend inline fun <R> exec( suspend inline fun <R> exec(
query: String, query: String,
crossinline mapper: (Map<String, String>) -> R crossinline mapper: (Map<String, String>) -> R
@@ -39,7 +35,6 @@ open class MagiskDB {
when (it) { when (it) {
is Boolean -> if (it) "1" else "0" is Boolean -> if (it) "1" else "0"
is Number -> it.toString() is Number -> it.toString()
is Literal -> it.str
else -> "\"$it\"" else -> "\"$it\""
} }
} }
@@ -5,7 +5,7 @@ import com.topjohnwu.magisk.core.AppContext
import com.topjohnwu.magisk.core.Const import com.topjohnwu.magisk.core.Const
import com.topjohnwu.magisk.core.model.su.SuPolicy 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() { class PolicyDao : MagiskDB() {
@@ -45,15 +45,6 @@ class PolicyDao : MagiskDB() {
private fun toPolicy(map: Map<String, String>): SuPolicy? { private fun toPolicy(map: Map<String, String>): SuPolicy? {
val uid = map["uid"]?.toInt() ?: return null val uid = map["uid"]?.toInt() ?: return null
val policy = SuPolicy(uid) 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["policy"]?.toInt()?.let { policy.policy = it }
map["logging"]?.toInt()?.let { policy.logging = it != 0 } map["logging"]?.toInt()?.let { policy.logging = it != 0 }
map["notification"]?.toInt()?.let { policy.notification = it != 0 } map["notification"]?.toInt()?.let { policy.notification = it != 0 }
@@ -1,11 +1,8 @@
package com.topjohnwu.magisk.core.model.su package com.topjohnwu.magisk.core.model.su
import com.topjohnwu.magisk.core.data.magiskdb.MagiskDB
class SuPolicy( class SuPolicy(
var uid: Int, var uid: Int,
var policy: Int = DENY, var policy: Int = DENY,
var remain: Long = -1L,
var logging: Boolean = true, var logging: Boolean = true,
var notification: Boolean = true, var notification: Boolean = true,
) { ) {
@@ -17,15 +14,11 @@ class SuPolicy(
} }
fun toMap(): MutableMap<String, Any> { fun toMap(): MutableMap<String, Any> {
val until = if (remain <= 0) {
remain
} else {
MagiskDB.Literal("(strftime(\"%s\", \"now\") + $remain)")
}
return mutableMapOf( return mutableMapOf(
"uid" to uid, "uid" to uid,
"policy" to policy, "policy" to policy,
"until" to until, // Timed grants are no longer supported; all policies are permanent
"until" to 0,
"logging" to logging, "logging" to logging,
"notification" to notification "notification" to notification
) )
@@ -35,7 +35,6 @@ class SmokeTest : TestCommon {
policy = SuPolicy.ALLOW, policy = SuPolicy.ALLOW,
logging = false, logging = false,
notification = false, notification = false,
remain = 0L
) )
runBlocking { runBlocking {
ServiceLocator.policyDB.update(policy) ServiceLocator.policyDB.update(policy)