app: modernize architecture and state in apk-ng

Refactor apk-ng to adhere to modern Android and Jetpack Compose best
practices:
- Migrate VMFactory to the type-safe AndroidX viewModelFactory DSL.
- Use collectAsStateWithLifecycle across all screen composables to
  pause flow collection when backgrounded.
- Convert PolicyItem, ModuleItem, DenyAppState, and DenyProcessState
  to pure immutable data classes, removing Compose MutableState from
  ViewModels.
- Extract shell operations from UI model classes into ViewModels.
- Bridge Info.isConnected LiveData to coroutine Flow using callbackFlow
  and collect in viewModelScope without modifying :core.
- Consolidate magisk and manager version state into
  HomeViewModel.UiState.
- Add contentType to LazyColumn items for optimal list recycling.
- Restore proper localized string resolution in MainActivityDialogs.

Assisted-by: Gemini 3.7 Flash
This commit is contained in:
topjohnwu
2026-08-20 21:36:49 +00:00
committed by John Wu
parent 3aaf18038a
commit 99a6e2749f
19 changed files with 336 additions and 204 deletions
@@ -1,26 +1,29 @@
package com.topjohnwu.magisk.arch
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import com.topjohnwu.magisk.core.di.ServiceLocator
import com.topjohnwu.magisk.ui.deny.DenyListViewModel
import com.topjohnwu.magisk.ui.flash.FlashViewModel
import com.topjohnwu.magisk.ui.home.HomeViewModel
import com.topjohnwu.magisk.ui.install.InstallViewModel
import com.topjohnwu.magisk.ui.log.LogViewModel
import com.topjohnwu.magisk.ui.module.ActionViewModel
import com.topjohnwu.magisk.ui.module.ModuleViewModel
import com.topjohnwu.magisk.ui.settings.SettingsViewModel
import com.topjohnwu.magisk.ui.superuser.SuperuserViewModel
import com.topjohnwu.magisk.ui.surequest.SuRequestViewModel
object VMFactory : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return when (modelClass) {
HomeViewModel::class.java -> HomeViewModel(ServiceLocator.networkService)
LogViewModel::class.java -> LogViewModel(ServiceLocator.logRepo)
SuperuserViewModel::class.java -> SuperuserViewModel(ServiceLocator.policyDB)
InstallViewModel::class.java ->
InstallViewModel(ServiceLocator.networkService)
SuRequestViewModel::class.java ->
SuRequestViewModel(ServiceLocator.policyDB, ServiceLocator.timeoutPrefs)
else -> modelClass.newInstance()
} as T
}
val VMFactory: ViewModelProvider.Factory = viewModelFactory {
initializer { HomeViewModel(ServiceLocator.networkService) }
initializer { LogViewModel(ServiceLocator.logRepo) }
initializer { SuperuserViewModel(ServiceLocator.policyDB) }
initializer { InstallViewModel(ServiceLocator.networkService) }
initializer { SuRequestViewModel(ServiceLocator.policyDB, ServiceLocator.timeoutPrefs) }
initializer { DenyListViewModel() }
initializer { FlashViewModel() }
initializer { ActionViewModel() }
initializer { ModuleViewModel() }
initializer { SettingsViewModel() }
}
@@ -16,14 +16,15 @@ import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalResources
import androidx.core.content.pm.ShortcutManagerCompat
import androidx.core.net.toUri
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.lifecycle.viewmodel.navigation3.rememberViewModelStoreNavEntryDecorator
@@ -185,9 +186,9 @@ class MainActivity : ComponentActivity(), SplashScreenHost {
)
}
MainActivityDialogs(
showInvalid = showInvalidState.collectAsState().value,
unsupportedMessages = showUnsupported.collectAsState().value,
showShortcut = showShortcutPrompt.collectAsState().value,
showInvalid = showInvalidState.collectAsStateWithLifecycle().value,
unsupportedMessages = showUnsupported.collectAsStateWithLifecycle().value,
showShortcut = showShortcutPrompt.collectAsStateWithLifecycle().value,
onInvalidConfirmed = {
showInvalidState.value = false
handleInvalidStateInstall()
@@ -207,7 +208,7 @@ class MainActivity : ComponentActivity(), SplashScreenHost {
@Composable
private fun HandleFlashIntent(navigator: Navigator) {
val intentVersion by intentState.collectAsState()
val intentVersion by intentState.collectAsStateWithLifecycle()
LaunchedEffect(intentVersion) {
val currentIntent = intent ?: return@LaunchedEffect
if (currentIntent.action == FlashUtils.INTENT_FLASH) {
@@ -303,6 +304,7 @@ private fun MainActivityDialogs(
onShortcutDismissed: () -> Unit,
modifier: Modifier = Modifier
) {
val resources = LocalResources.current
val invalidDialog = rememberConfirmDialog(
onConfirm = onInvalidConfirmed,
onDismiss = {}
@@ -311,9 +313,9 @@ private fun MainActivityDialogs(
LaunchedEffect(showInvalid) {
if (showInvalid) {
invalidDialog.showConfirm(
title = CoreR.string.unsupport_nonroot_stub_title.let { "" },
content = CoreR.string.unsupport_nonroot_stub_msg.let { "" },
confirm = CoreR.string.install.let { "" },
title = resources.getString(CoreR.string.unsupport_nonroot_stub_title),
content = resources.getString(CoreR.string.unsupport_nonroot_stub_msg),
confirm = resources.getString(CoreR.string.install),
)
}
}
@@ -327,9 +329,10 @@ private fun MainActivityDialogs(
val currentUnsupported = unsupportedMessages.getOrNull(currentUnsupportedIndex)
LaunchedEffect(currentUnsupported) {
if (currentUnsupported != null) {
val (titleRes, msgRes) = currentUnsupported
unsupportedDialog.showConfirm(
title = "",
content = "",
title = resources.getString(titleRes),
content = resources.getString(msgRes),
)
}
}
@@ -342,8 +345,8 @@ private fun MainActivityDialogs(
LaunchedEffect(showShortcut) {
if (showShortcut) {
shortcutDialog.showConfirm(
title = "",
content = "",
title = resources.getString(CoreR.string.add_shortcut_title),
content = resources.getString(CoreR.string.add_shortcut_msg),
)
}
}
@@ -48,7 +48,6 @@ import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.TriStateCheckbox
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
@@ -60,6 +59,7 @@ import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.state.ToggleableState
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.google.accompanist.drawablepainter.rememberDrawablePainter
import com.topjohnwu.magisk.ui.component.verticalScrollbar
import com.topjohnwu.magisk.core.R as CoreR
@@ -71,13 +71,13 @@ fun DenyListScreen(
onBack: () -> Unit,
modifier: Modifier = Modifier
) {
val loading by viewModel.loading.collectAsState()
val apps by viewModel.filteredApps.collectAsState()
val query by viewModel.query.collectAsState()
val showSystem by viewModel.showSystem.collectAsState()
val showOS by viewModel.showOS.collectAsState()
val sortBy by viewModel.sortBy.collectAsState()
val sortReverse by viewModel.sortReverse.collectAsState()
val loading by viewModel.loading.collectAsStateWithLifecycle()
val apps by viewModel.filteredApps.collectAsStateWithLifecycle()
val query by viewModel.query.collectAsStateWithLifecycle()
val showSystem by viewModel.showSystem.collectAsStateWithLifecycle()
val showOS by viewModel.showOS.collectAsStateWithLifecycle()
val sortBy by viewModel.sortBy.collectAsStateWithLifecycle()
val sortReverse by viewModel.sortReverse.collectAsStateWithLifecycle()
var showSortMenu by remember { mutableStateOf(false) }
var showFilterMenu by remember { mutableStateOf(false) }
@@ -225,9 +225,15 @@ fun DenyListScreen(
) {
items(
items = apps,
key = { it.info.packageName }
key = { it.info.packageName },
contentType = { "DenyAppCard" }
) { app ->
DenyAppCard(app = app)
DenyAppCard(
app = app,
onToggleExpand = { viewModel.toggleExpanded(app) },
onToggleAll = { viewModel.toggleAll(app) },
onToggleProcess = { proc -> viewModel.toggleProcess(app, proc) }
)
}
}
}
@@ -278,6 +284,9 @@ private fun SearchInput(
@Composable
private fun DenyAppCard(
app: DenyAppState,
onToggleExpand: () -> Unit,
onToggleAll: () -> Unit,
onToggleProcess: (DenyProcessState) -> Unit,
modifier: Modifier = Modifier
) {
Card(
@@ -305,7 +314,7 @@ private fun DenyAppCard(
Row(
modifier = Modifier
.fillMaxWidth()
.clickable { app.isExpanded = !app.isExpanded }
.clickable(onClick = onToggleExpand)
.padding(14.dp),
verticalAlignment = Alignment.CenterVertically
) {
@@ -334,7 +343,7 @@ private fun DenyAppCard(
app.checkedPercent < 1f -> ToggleableState.Indeterminate
else -> ToggleableState.On
},
onClick = { app.toggleAll() }
onClick = onToggleAll
)
}
@@ -345,7 +354,10 @@ private fun DenyAppCard(
.padding(start = 52.dp, bottom = 8.dp)
) {
app.processes.forEach { proc ->
ProcessRow(proc = proc)
ProcessRow(
proc = proc,
onToggle = { onToggleProcess(proc) }
)
}
}
}
@@ -356,13 +368,14 @@ private fun DenyAppCard(
@Composable
private fun ProcessRow(
proc: DenyProcessState,
onToggle: () -> Unit,
modifier: Modifier = Modifier
) {
Row(
modifier = modifier
.fillMaxWidth()
.clip(RoundedCornerShape(12.dp))
.clickable { proc.toggle() }
.clickable(onClick = onToggle)
.padding(horizontal = 12.dp, vertical = 6.dp),
verticalAlignment = Alignment.CenterVertically
) {
@@ -376,7 +389,7 @@ private fun ProcessRow(
Spacer(Modifier.width(8.dp))
Checkbox(
checked = proc.isEnabled,
onCheckedChange = { proc.toggle() }
onCheckedChange = { onToggle() }
)
}
}
@@ -2,9 +2,6 @@ package com.topjohnwu.magisk.ui.deny
import android.annotation.SuppressLint
import android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.viewModelScope
import com.topjohnwu.magisk.arch.AsyncLoadViewModel
import com.topjohnwu.magisk.core.AppContext
@@ -20,10 +17,39 @@ import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.toCollection
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.withContext
enum class SortBy { NAME, PACKAGE_NAME, INSTALL_TIME, UPDATE_TIME }
data class DenyProcessState(
val process: ProcessInfo,
val isEnabled: Boolean = process.isEnabled,
) {
val displayName: String =
if (process.isIsolated) "(isolated) ${process.name}*" else process.name
}
data class DenyAppState(
val info: AppProcessInfo,
val processes: List<DenyProcessState> = info.processes.map { DenyProcessState(it) },
val isExpanded: Boolean = false,
) : Comparable<DenyAppState> {
val itemsChecked: Int get() = processes.count { it.isEnabled }
val isChecked: Boolean get() = itemsChecked > 0
val checkedPercent: Float get() = if (processes.isEmpty()) 0f else itemsChecked.toFloat() / processes.size
override fun compareTo(other: DenyAppState) = comparator.compare(this, other)
companion object {
private val comparator = compareBy<DenyAppState>(
{ it.itemsChecked == 0 },
{ it.info }
)
}
}
class DenyListViewModel : AsyncLoadViewModel() {
private val _loading = MutableStateFlow(true)
@@ -88,6 +114,69 @@ class DenyListViewModel : AsyncLoadViewModel() {
fun setSortBy(s: SortBy) { _sortBy.value = s }
fun toggleSortReverse() { _sortReverse.value = !_sortReverse.value }
fun toggleExpanded(app: DenyAppState) {
_allApps.update { apps ->
apps.map {
if (it.info.packageName == app.info.packageName) it.copy(isExpanded = !it.isExpanded) else it
}
}
}
fun toggleAll(app: DenyAppState) {
val willCheck = !app.isChecked
if (!willCheck) {
Shell.cmd("magisk --denylist rm ${app.info.packageName}").submit()
}
_allApps.update { apps ->
apps.map { currentApp ->
if (currentApp.info.packageName == app.info.packageName) {
val newProcs = currentApp.processes.map { proc ->
if (willCheck) {
if (!proc.isEnabled) {
val (name, pkg) = proc.process
Shell.cmd("magisk --denylist add $pkg '$name'").submit()
}
proc.copy(isEnabled = true)
} else {
if (proc.process.isIsolated && proc.isEnabled) {
val (name, pkg) = proc.process
Shell.cmd("magisk --denylist rm $pkg '$name'").submit()
}
proc.copy(isEnabled = false)
}
}
currentApp.copy(processes = newProcs)
} else {
currentApp
}
}
}
}
fun toggleProcess(app: DenyAppState, proc: DenyProcessState) {
val newEnabled = !proc.isEnabled
val arg = if (newEnabled) "add" else "rm"
val (name, pkg) = proc.process
Shell.cmd("magisk --denylist $arg $pkg '$name'").submit()
_allApps.update { apps ->
apps.map { currentApp ->
if (currentApp.info.packageName == app.info.packageName) {
val newProcs = currentApp.processes.map { currentProc ->
if (currentProc.process.name == proc.process.name && currentProc.process.packageName == proc.process.packageName) {
currentProc.copy(isEnabled = newEnabled)
} else {
currentProc
}
}
currentApp.copy(processes = newProcs)
} else {
currentApp
}
}
}
}
@SuppressLint("InlinedApi")
override suspend fun doLoadWork() {
_loading.value = true
@@ -113,50 +202,3 @@ class DenyListViewModel : AsyncLoadViewModel() {
_loading.value = false
}
}
class DenyAppState(val info: AppProcessInfo) : Comparable<DenyAppState> {
val processes = info.processes.map { DenyProcessState(it) }
var isExpanded by mutableStateOf(false)
val itemsChecked: Int get() = processes.count { it.isEnabled }
val isChecked: Boolean get() = itemsChecked > 0
val checkedPercent: Float get() = if (processes.isEmpty()) 0f else itemsChecked.toFloat() / processes.size
fun toggleAll() {
if (isChecked) {
Shell.cmd("magisk --denylist rm ${info.packageName}").submit()
processes.filter { it.isEnabled }.forEach { proc ->
if (proc.process.isIsolated) {
proc.toggle()
} else {
proc.isEnabled = false
}
}
} else {
processes.filterNot { it.isEnabled }.forEach { it.toggle() }
}
}
override fun compareTo(other: DenyAppState) = comparator.compare(this, other)
companion object {
private val comparator = compareBy<DenyAppState>(
{ it.itemsChecked == 0 },
{ it.info }
)
}
}
class DenyProcessState(val process: ProcessInfo) {
var isEnabled by mutableStateOf(process.isEnabled)
val displayName: String =
if (process.isIsolated) "(isolated) ${process.name}*" else process.name
fun toggle() {
isEnabled = !isEnabled
val arg = if (isEnabled) "add" else "rm"
val (name, pkg) = process
Shell.cmd("magisk --denylist $arg $pkg \'$name\'").submit()
}
}
@@ -21,7 +21,6 @@ import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
@@ -29,6 +28,7 @@ import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.topjohnwu.magisk.R
import com.topjohnwu.magisk.core.Const
import com.topjohnwu.magisk.ui.component.rememberExternalStoragePermissionLauncher
@@ -44,8 +44,8 @@ fun FlashScreen(
onBack: () -> Unit,
modifier: Modifier = Modifier
) {
val flashState by viewModel.flashState.collectAsState()
val showReboot by viewModel.showReboot.collectAsState()
val flashState by viewModel.flashState.collectAsStateWithLifecycle()
val showReboot by viewModel.showReboot.collectAsStateWithLifecycle()
val finished = flashState != FlashViewModel.State.FLASHING
val useTerminal = action == Const.Value.FLASH_ZIP
val saveLog = rememberExternalStoragePermissionLauncher {
@@ -53,7 +53,6 @@ import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.VerticalDivider
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
@@ -69,6 +68,7 @@ import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.core.content.getSystemService
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.topjohnwu.magisk.R
import com.topjohnwu.magisk.core.BuildConfig
import com.topjohnwu.magisk.core.Config
@@ -98,7 +98,7 @@ fun HomeScreen(
installVm: InstallViewModel,
modifier: Modifier = Modifier
) {
val uiState by viewModel.uiState.collectAsState()
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
val context = LocalContext.current
val scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior()
val scope = rememberCoroutineScope()
@@ -268,8 +268,8 @@ fun HomeScreen(
CoreCard(
modifier = Modifier.fillMaxWidth(),
state = viewModel.magiskState,
version = viewModel.magiskInstalledVersion,
state = uiState.magiskState,
version = uiState.magiskInstalledVersion,
onInstallClicked = { showInstallSheet = true }
)
@@ -278,7 +278,7 @@ fun HomeScreen(
AppCard(
modifier = Modifier.fillMaxWidth(),
state = uiState.appState,
version = viewModel.managerInstalledVersion,
version = uiState.managerInstalledVersion,
remoteVersion = uiState.managerRemoteVersion,
progress = uiState.managerProgress,
isHidden = context.packageName != BuildConfig.APP_PACKAGE_NAME,
@@ -4,6 +4,7 @@ import android.content.ActivityNotFoundException
import android.content.Intent
import android.widget.Toast
import androidx.core.net.toUri
import androidx.lifecycle.viewModelScope
import com.topjohnwu.magisk.arch.AsyncLoadViewModel
import com.topjohnwu.magisk.core.AppContext
import com.topjohnwu.magisk.core.BuildConfig
@@ -12,11 +13,13 @@ import com.topjohnwu.magisk.core.Info
import com.topjohnwu.magisk.core.ktx.await
import com.topjohnwu.magisk.core.ktx.toast
import com.topjohnwu.magisk.core.repository.NetworkService
import com.topjohnwu.magisk.utils.asFlow
import com.topjohnwu.superuser.Shell
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import com.topjohnwu.magisk.core.R as CoreR
class HomeViewModel(
@@ -36,37 +39,57 @@ class HomeViewModel(
val showManagerInstall: Boolean = false,
val showHideRestore: Boolean = false,
val envFixCode: Int = 0,
val magiskState: State = computeMagiskState(),
val magiskInstalledVersion: String = computeMagiskInstalledVersion(),
val managerInstalledVersion: String = computeManagerInstalledVersion(),
)
private val _uiState = MutableStateFlow(UiState())
val uiState: StateFlow<UiState> = _uiState.asStateFlow()
val magiskState
get() = when {
val magiskState get() = _uiState.value.magiskState
val magiskInstalledVersion get() = _uiState.value.magiskInstalledVersion
val managerInstalledVersion get() = _uiState.value.managerInstalledVersion
companion object {
private var checkedEnv = false
fun computeMagiskState() = when {
Info.isRooted && Info.env.isUnsupported -> State.OUTDATED
!Info.env.isActive -> State.INVALID
Info.env.versionCode < BuildConfig.APP_VERSION_CODE -> State.OUTDATED
else -> State.UP_TO_DATE
}
val magiskInstalledVersion: String
get() = Info.env.run {
fun computeMagiskInstalledVersion() = Info.env.run {
if (isActive)
"$versionString ($versionCode)" + if (isDebug) " (D)" else ""
else
""
}
val managerInstalledVersion: String
get() = "${BuildConfig.APP_VERSION_NAME} (${BuildConfig.APP_VERSION_CODE})" +
if (BuildConfig.DEBUG) " (D)" else ""
fun computeManagerInstalledVersion() =
"${BuildConfig.APP_VERSION_NAME} (${BuildConfig.APP_VERSION_CODE})" +
if (BuildConfig.DEBUG) " (D)" else ""
}
companion object {
private var checkedEnv = false
init {
viewModelScope.launch {
Info.isConnected.asFlow().collect {
startLoading()
}
}
}
override suspend fun doLoadWork() {
_uiState.update { it.copy(appState = State.LOADING) }
_uiState.update {
it.copy(
appState = State.LOADING,
magiskState = computeMagiskState(),
magiskInstalledVersion = computeMagiskInstalledVersion(),
managerInstalledVersion = computeManagerInstalledVersion(),
)
}
Info.fetchUpdate(svc)?.apply {
val isDebug = Config.updateChannel == Config.Value.DEBUG_CHANNEL
_uiState.update {
@@ -81,17 +104,6 @@ class HomeViewModel(
ensureEnv()
}
private val networkObserver: (Boolean) -> Unit = { startLoading() }
init {
Info.isConnected.observeForever(networkObserver)
}
override fun onCleared() {
super.onCleared()
Info.isConnected.removeObserver(networkObserver)
}
fun onLinkPressed(link: String) {
val intent = Intent(Intent.ACTION_VIEW, link.toUri())
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
@@ -25,7 +25,6 @@ import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
@@ -37,6 +36,7 @@ import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.core.net.toUri
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.topjohnwu.magisk.core.Config
import com.topjohnwu.magisk.core.Info
import com.topjohnwu.magisk.ui.component.ConfirmResult
@@ -53,7 +53,7 @@ fun InstallBottomSheet(
installVm: InstallViewModel,
modifier: Modifier = Modifier
) {
val installUiState by installVm.uiState.collectAsState()
val installUiState by installVm.uiState.collectAsStateWithLifecycle()
var showDownloadDialog by rememberSaveable { mutableStateOf(false) }
val filePicker = rememberLauncherForActivityResult(ActivityResultContracts.GetContent()) { uri ->
uri?.let { installVm.onPatchFileSelected(it) }
@@ -17,7 +17,6 @@ import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import timber.log.Timber
import java.io.File
import java.io.IOException
@@ -57,9 +56,7 @@ class InstallViewModel(svc: NetworkService) : BaseViewModel() {
note
}
}
withContext(Dispatchers.Main) {
_uiState.update { it.copy(notes = noteText) }
}
_uiState.update { it.copy(notes = noteText) }
} catch (e: IOException) {
Timber.e(e)
}
@@ -36,7 +36,6 @@ import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
@@ -56,6 +55,7 @@ import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.google.accompanist.drawablepainter.rememberDrawablePainter
import com.topjohnwu.magisk.core.ktx.timeDateFormat
import com.topjohnwu.magisk.core.ktx.toTime
@@ -70,7 +70,7 @@ fun LogScreen(
viewModel: LogViewModel,
modifier: Modifier = Modifier
) {
val uiState by viewModel.uiState.collectAsState()
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
var selectedTab by rememberSaveable { mutableIntStateOf(0) }
val tabTitles = listOf(
stringResource(CoreR.string.superuser),
@@ -189,7 +189,11 @@ private fun SuLogTab(
contentPadding = PaddingValues(top = 8.dp, bottom = 88.dp),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
items(logs, key = { it.id }) { log ->
items(
items = logs,
key = { it.id },
contentType = { "SuLogCard" }
) { log ->
SuLogCard(log = log)
}
}
@@ -349,7 +353,11 @@ private fun MagiskLogTab(
contentPadding = PaddingValues(top = 8.dp, bottom = 88.dp),
verticalArrangement = Arrangement.spacedBy(6.dp)
) {
items(entries, key = { "${it.timestamp}_${it.pid}_${it.tid}_${it.message.hashCode()}" }) { entry ->
items(
items = entries,
key = { "${it.timestamp}_${it.pid}_${it.tid}_${it.message.hashCode()}" },
contentType = { "MagiskLogCard" }
) { entry ->
MagiskLogCard(entry = entry)
}
}
@@ -12,12 +12,12 @@ import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.topjohnwu.magisk.R
import com.topjohnwu.magisk.ui.component.rememberExternalStoragePermissionLauncher
import com.topjohnwu.magisk.ui.terminal.TerminalScreen
@@ -31,7 +31,7 @@ fun ActionScreen(
onBack: () -> Unit,
modifier: Modifier = Modifier
) {
val actionState by viewModel.actionState.collectAsState()
val actionState by viewModel.actionState.collectAsStateWithLifecycle()
val finished = actionState != ActionViewModel.State.RUNNING
val saveLog = rememberExternalStoragePermissionLauncher {
viewModel.saveLog()
@@ -49,7 +49,6 @@ import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
@@ -69,6 +68,7 @@ import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.topjohnwu.magisk.R
import com.topjohnwu.magisk.core.Info
import com.topjohnwu.magisk.core.di.ServiceLocator
@@ -89,7 +89,7 @@ fun ModuleScreen(
viewModel: ModuleViewModel,
modifier: Modifier = Modifier
) {
val uiState by viewModel.uiState.collectAsState()
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
val scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior()
val colorScheme = MaterialTheme.colorScheme
val context = LocalContext.current
@@ -218,7 +218,11 @@ fun ModuleScreen(
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
item { Spacer(Modifier.height(4.dp)) }
items(uiState.modules, key = { it.module.id }) { item ->
items(
items = uiState.modules,
key = { it.module.id },
contentType = { "ModuleCard" }
) { item ->
ModuleCard(
item = item,
viewModel = viewModel,
@@ -2,13 +2,10 @@ package com.topjohnwu.magisk.ui.module
import android.content.Context
import android.net.Uri
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.viewModelScope
import com.topjohnwu.magisk.arch.AsyncLoadViewModel
import com.topjohnwu.magisk.core.Const
import com.topjohnwu.magisk.core.Info
import com.topjohnwu.magisk.core.R as CoreR
import com.topjohnwu.magisk.core.download.Subject
import com.topjohnwu.magisk.core.model.module.LocalModule
import com.topjohnwu.magisk.core.model.module.OnlineModule
@@ -16,19 +13,29 @@ import com.topjohnwu.magisk.core.utils.TextHolder
import com.topjohnwu.magisk.core.utils.asText
import com.topjohnwu.magisk.ui.flash.FlashUtils
import com.topjohnwu.magisk.ui.navigation.Route
import com.topjohnwu.magisk.utils.asFlow
import com.topjohnwu.magisk.view.Notifications
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.parcelize.Parcelize
import com.topjohnwu.magisk.core.R as CoreR
class ModuleItem(val module: LocalModule) {
data class ModuleItem(
val module: LocalModule,
val isEnabled: Boolean = module.enable,
val isRemoved: Boolean = module.remove,
val showUpdate: Boolean = module.updateInfo != null,
) {
val showNotice: Boolean
val showAction: Boolean
val noticeText: TextHolder
val isUpdated = module.updated
val updateReady get() = module.outdated && !isRemoved && isEnabled
init {
val isZygisk = module.isZygisk
@@ -46,19 +53,13 @@ class ModuleItem(val module: LocalModule) {
else -> CoreR.string.suspend_text_zygisk.asText(CoreR.string.zygisk.asText())
}
}
var isEnabled by mutableStateOf(module.enable)
var isRemoved by mutableStateOf(module.remove)
var showUpdate by mutableStateOf(module.updateInfo != null)
val isUpdated = module.updated
val updateReady get() = module.outdated && !isRemoved && isEnabled
}
@Parcelize
class OnlineModuleSubject(
override val module: OnlineModule,
override val autoLaunch: Boolean,
override val notifyId: Int = Notifications.nextId()
override val notifyId: Int = Notifications.nextId(),
) : Subject.Module() {
override fun pendingIntent(context: Context) = FlashUtils.installIntent(context, file)
}
@@ -73,6 +74,14 @@ class ModuleViewModel : AsyncLoadViewModel() {
private val _uiState = MutableStateFlow(UiState())
val uiState: StateFlow<UiState> = _uiState.asStateFlow()
init {
viewModelScope.launch {
Info.isConnected.asFlow().collect {
startLoading()
}
}
}
override suspend fun doLoadWork() {
_uiState.update { it.copy(loading = true) }
val moduleLoaded = Info.env.isActive &&
@@ -88,23 +97,18 @@ class ModuleViewModel : AsyncLoadViewModel() {
}
}
private val networkObserver: (Boolean) -> Unit = { startLoading() }
init {
Info.isConnected.observeForever(networkObserver)
}
override fun onCleared() {
super.onCleared()
Info.isConnected.removeObserver(networkObserver)
}
private suspend fun loadUpdateInfo() {
withContext(Dispatchers.IO) {
_uiState.value.modules.forEach { item ->
if (item.module.fetch()) {
item.showUpdate = item.module.updateInfo != null
}
_uiState.update { state ->
state.copy(
modules = state.modules.map { item ->
if (item.module.fetch()) {
item.copy(showUpdate = item.module.updateInfo != null)
} else {
item
}
}
)
}
}
}
@@ -118,12 +122,26 @@ class ModuleViewModel : AsyncLoadViewModel() {
}
fun toggleEnabled(item: ModuleItem) {
item.isEnabled = !item.isEnabled
item.module.enable = item.isEnabled
val newEnabled = !item.isEnabled
item.module.enable = newEnabled
_uiState.update { state ->
state.copy(
modules = state.modules.map {
if (it.module.id == item.module.id) it.copy(isEnabled = newEnabled) else it
}
)
}
}
fun toggleRemove(item: ModuleItem) {
item.isRemoved = !item.isRemoved
item.module.remove = item.isRemoved
val newRemoved = !item.isRemoved
item.module.remove = newRemoved
_uiState.update { state ->
state.copy(
modules = state.modules.map {
if (it.module.id == item.module.id) it.copy(isRemoved = newRemoved) else it
}
)
}
}
}
@@ -24,7 +24,6 @@ import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
@@ -38,6 +37,7 @@ import androidx.compose.ui.platform.LocalResources
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.core.content.pm.ShortcutManagerCompat
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.topjohnwu.magisk.core.Config
import com.topjohnwu.magisk.core.Const
import com.topjohnwu.magisk.core.Info
@@ -305,7 +305,7 @@ private fun MagiskSection(
)
// DenyList
val denyListEnabled by viewModel.denyListEnabled.collectAsState()
val denyListEnabled by viewModel.denyListEnabled.collectAsStateWithLifecycle()
SettingsSwitch(
title = stringResource(CoreR.string.settings_denylist_title),
summary = stringResource(CoreR.string.settings_denylist_summary),
@@ -34,7 +34,6 @@ import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
@@ -42,6 +41,7 @@ import androidx.compose.ui.Modifier
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.ui.component.ConfirmResult
import com.topjohnwu.magisk.ui.component.SettingsSwitch
@@ -59,7 +59,7 @@ fun SuperuserDetailScreen(
modifier: Modifier = Modifier,
onAuthenticate: ((onSuccess: () -> Unit) -> Unit)? = null,
) {
val uiState by viewModel.uiState.collectAsState()
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
val items = uiState.policies.filter { it.policy.uid == uid }
val item = items.firstOrNull()
val scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior()
@@ -34,7 +34,6 @@ import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
@@ -45,6 +44,7 @@ import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.google.accompanist.drawablepainter.rememberDrawablePainter
import com.topjohnwu.magisk.ui.component.verticalScrollbar
import com.topjohnwu.magisk.ui.navigation.LocalNavigator
@@ -57,7 +57,7 @@ fun SuperuserScreen(
viewModel: SuperuserViewModel,
modifier: Modifier = Modifier
) {
val uiState by viewModel.uiState.collectAsState()
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
val scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior()
val navigator = LocalNavigator.current
@@ -123,7 +123,11 @@ fun SuperuserScreen(
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
item { Spacer(Modifier.height(4.dp)) }
items(uiState.policies, key = { "${it.policy.uid}_${it.packageName}" }) { item ->
items(
items = uiState.policies,
key = { "${it.policy.uid}_${it.packageName}" },
contentType = { "PolicyCard" }
) { item ->
PolicyCard(
item = item,
onToggle = { viewModel.togglePolicy(item) },
@@ -5,10 +5,6 @@ import android.content.pm.PackageManager
import android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES
import android.graphics.drawable.Drawable
import android.os.Process
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.viewModelScope
import com.topjohnwu.magisk.arch.AsyncLoadViewModel
import com.topjohnwu.magisk.core.AppContext
@@ -20,6 +16,7 @@ import com.topjohnwu.magisk.core.ktx.getLabel
import com.topjohnwu.magisk.core.model.su.SuPolicy
import com.topjohnwu.magisk.core.su.SuEvents
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
@@ -29,19 +26,17 @@ import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.Locale
class PolicyItem(
data class PolicyItem(
val policy: SuPolicy,
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 title get() = appName
var policyValue by mutableIntStateOf(policy.policy)
var notification by mutableStateOf(policy.notification)
var logging by mutableStateOf(policy.logging)
val isEnabled get() = policyValue >= SuPolicy.ALLOW
val isRestricted get() = policyValue == SuPolicy.RESTRICT
}
@@ -53,7 +48,7 @@ class SuperuserViewModel(
var authenticate: (onSuccess: () -> Unit) -> Unit = { it() }
init {
@OptIn(kotlinx.coroutines.FlowPreview::class)
@OptIn(FlowPreview::class)
viewModelScope.launch {
SuEvents.policyChanged.debounce(500).collect { reload() }
}
@@ -96,7 +91,10 @@ class SuperuserViewModel(
packageName = info.packageName,
isSharedUid = info.sharedUserId != null,
icon = info.applicationInfo?.loadIcon(pm) ?: pm.defaultActivityIcon,
appName = info.applicationInfo?.getLabel(pm) ?: info.packageName
appName = info.applicationInfo?.getLabel(pm) ?: info.packageName,
policyValue = policy.policy,
notification = policy.notification,
logging = policy.logging,
)
} catch (_: PackageManager.NameNotFoundException) {
null
@@ -133,27 +131,35 @@ class SuperuserViewModel(
}
fun updateNotify(item: PolicyItem) {
item.notification = !item.notification
item.policy.notification = item.notification
val newNotification = !item.notification
item.policy.notification = newNotification
viewModelScope.launch {
db.update(item.policy)
_uiState.value.policies
.filter { it.policy.uid == item.policy.uid }
.forEach { it.notification = item.notification }
val res = if (item.notification) R.string.su_snack_notif_on else R.string.su_snack_notif_off
_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))
}
}
fun updateLogging(item: PolicyItem) {
item.logging = !item.logging
item.policy.logging = item.logging
val newLogging = !item.logging
item.policy.logging = newLogging
viewModelScope.launch {
db.update(item.policy)
_uiState.value.policies
.filter { it.policy.uid == item.policy.uid }
.forEach { it.logging = item.logging }
val res = if (item.logging) R.string.su_snack_log_on else R.string.su_snack_log_off
_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))
}
}
@@ -162,11 +168,14 @@ class SuperuserViewModel(
fun updateState() {
viewModelScope.launch {
item.policy.policy = newPolicy
item.policyValue = newPolicy
db.update(item.policy)
_uiState.value.policies
.filter { it.policy.uid == item.policy.uid }
.forEach { it.policyValue = newPolicy }
_uiState.update { state ->
state.copy(
policies = state.policies.map {
if (it.policy.uid == item.policy.uid) it.copy(policyValue = newPolicy) else it
}
)
}
val res = if (newPolicy >= SuPolicy.ALLOW) R.string.su_snack_grant else R.string.su_snack_deny
showSnackbar(AppContext.getString(res, item.appName))
}
@@ -26,7 +26,6 @@ import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Slider
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
@@ -42,6 +41,7 @@ import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.google.accompanist.drawablepainter.rememberDrawablePainter
import com.topjohnwu.magisk.core.ktx.toast
import com.topjohnwu.magisk.ui.superuser.SharedUidBadge
@@ -53,7 +53,7 @@ fun SuRequestScreen(
viewModel: SuRequestViewModel,
modifier: Modifier = Modifier
) {
val uiState by viewModel.uiState.collectAsState()
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
if (!uiState.showUi) return
val context = LocalContext.current
@@ -0,0 +1,19 @@
package com.topjohnwu.magisk.utils
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
fun <T> LiveData<T>.asFlow(): Flow<T> = callbackFlow {
val observer = Observer<T> { value ->
if (value != null) {
trySend(value)
}
}
observeForever(observer)
awaitClose {
removeObserver(observer)
}
}