Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

AppControl: Show tags for recently active apps #646

Merged
merged 2 commits into from
Sep 24, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package eu.darken.sdmse.common

open class ModeUnavailableException(
message: String? = null,
cause: Throwable? = null
) : IllegalStateException(message, cause)
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import android.content.pm.SharedLibraryInfo
import android.graphics.drawable.Drawable
import android.os.Process
import dagger.hilt.android.qualifiers.ApplicationContext
import eu.darken.sdmse.common.ModeUnavailableException
import eu.darken.sdmse.common.coroutine.AppScope
import eu.darken.sdmse.common.coroutine.DispatcherProvider
import eu.darken.sdmse.common.debug.logging.Logging.Priority.*
Expand Down Expand Up @@ -41,7 +42,6 @@ import eu.darken.sdmse.common.shizuku.service.runModuleAction
import eu.darken.sdmse.common.user.UserHandle2
import eu.darken.sdmse.common.user.UserManager2
import kotlinx.coroutines.*
import okio.IOException
import javax.inject.Inject
import javax.inject.Singleton

Expand Down Expand Up @@ -246,30 +246,38 @@ class PkgOps @Inject constructor(
return
}

throw IOException("No matching mode found")
throw ModeUnavailableException("Mode $mode is unavailable")
} catch (e: Exception) {
log(TAG, WARN) { "changePackageState($id, enabled=$enabled, mode=$mode) failed: $e" }
if (e is ModeUnavailableException) {
log(TAG, DEBUG) { "changePackageState(...): $mode unavailable for $id" }
} else {
log(TAG, WARN) { "changePackageState($id, enabled=$enabled, mode=$mode) failed: $e" }
}
throw PkgOpsException(message = "changePackageState($id, $enabled, $mode) failed", cause = e)
}
}

suspend fun clearCache(installId: Installed.InstallId, mode: Mode = Mode.AUTO) {
log(TAG) { "clearCache($installId, $mode)" }
suspend fun clearCache(id: Installed.InstallId, mode: Mode = Mode.AUTO) {
log(TAG) { "clearCache($id, $mode)" }
try {
if (mode == Mode.NORMAL) throw PkgOpsException("clearCache($installId) does not support mode=NORMAL")
if (mode == Mode.NORMAL) throw PkgOpsException("clearCache($id) does not support mode=NORMAL")

if (mode == Mode.ADB) throw PkgOpsException("clearCache($installId) does not support mode=ADB")
if (mode == Mode.ADB) throw PkgOpsException("clearCache($id) does not support mode=ADB")

if (rootManager.canUseRootNow() && (mode == Mode.AUTO || mode == Mode.ROOT)) {
log(TAG) { "clearCache($installId, $mode->ROOT)" }
rootOps { it.clearCache(installId) }
log(TAG) { "clearCache($id, $mode->ROOT)" }
rootOps { it.clearCache(id) }
return
}

throw IOException("No matching mode found")
throw ModeUnavailableException("Mode $mode is unavailable")
} catch (e: Exception) {
log(TAG, WARN) { "clearCache($installId,$mode) failed: ${e.asLog()}" }
throw PkgOpsException(message = "clearCache($installId, $mode) failed", cause = e)
if (e is ModeUnavailableException) {
log(TAG, DEBUG) { "clearCache(...): $mode unavailable for $id" }
} else {
log(TAG, WARN) { "clearCache($id,$mode) failed: ${e.asLog()}" }
}
throw PkgOpsException(message = "clearCache($id, $mode) failed", cause = e)
}
}

Expand All @@ -290,9 +298,13 @@ class PkgOps @Inject constructor(
return
}

throw IOException("No matching mode found")
throw ModeUnavailableException("Mode $mode is unavailable")
} catch (e: Exception) {
log(TAG, WARN) { "trimCaches($desiredBytes, $storageId,$mode) failed: ${e.asLog()}" }
if (e is ModeUnavailableException) {
log(TAG, DEBUG) { "trimCaches(...): $mode unavailable" }
} else {
log(TAG, WARN) { "trimCaches($desiredBytes, $storageId,$mode) failed: ${e.asLog()}" }
}
throw PkgOpsException(message = "trimCaches($desiredBytes, $storageId, $mode) failed", cause = e)
}
}
Expand Down Expand Up @@ -320,9 +332,13 @@ class PkgOps @Inject constructor(
return secondsSinceLastUse?.let { it < PULSE_PERIOD_SECONDS } ?: false
}

throw IOException("No matching mode found")
throw ModeUnavailableException("Mode $mode is unavailable")
} catch (e: Exception) {
log(TAG, WARN) { "isRunning($id,$mode) failed: ${e.asLog()}" }
if (e is ModeUnavailableException) {
log(TAG, DEBUG) { "isRunning(...): $mode unavailable for $id" }
} else {
log(TAG, WARN) { "isRunning($id,$mode) failed: ${e.asLog()}" }
}
throw PkgOpsException(message = "isRunning($id, $mode) failed", cause = e)
}
}
Expand All @@ -343,9 +359,13 @@ class PkgOps @Inject constructor(

}

throw IOException("No matching mode found")
throw ModeUnavailableException("Mode $mode is unavailable")
} catch (e: Exception) {
log(TAG, WARN) { "grantPermission($id, $permission, $mode) failed: ${e.asLog()}" }
if (e is ModeUnavailableException) {
log(TAG, DEBUG) { "grantPermission(...): $mode unavailable for $id" }
} else {
log(TAG, WARN) { "grantPermission($id, $permission, $mode) failed: ${e.asLog()}" }
}
throw PkgOpsException(message = "grantPermission($id, $permission, $mode) failed", cause = e)
}
}
Expand All @@ -371,9 +391,13 @@ class PkgOps @Inject constructor(

}

throw IOException("No matching mode found")
throw ModeUnavailableException("Mode $mode is unavailable")
} catch (e: Exception) {
log(TAG) { "setAppOps($id, $key, $value, $mode) failed: ${e.asLog()}" }
if (e is ModeUnavailableException) {
log(TAG, DEBUG) { "setAppOps(...): $mode unavailable for $id" }
} else {
log(TAG, WARN) { "setAppOps($id, $key, $value, $mode) failed: ${e.asLog()}" }
}
throw PkgOpsException(message = "setAppOps($id, $key, $value $mode) failed", cause = e)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import eu.darken.rxshell.cmd.Cmd
import eu.darken.sdmse.common.debug.Bugs
import eu.darken.sdmse.common.debug.logging.Logging.Priority.ERROR
import eu.darken.sdmse.common.debug.logging.Logging.Priority.VERBOSE
import eu.darken.sdmse.common.debug.logging.asLog
import eu.darken.sdmse.common.debug.logging.log
import eu.darken.sdmse.common.debug.logging.logTag
import eu.darken.sdmse.common.ipc.IpcHostModule
Expand All @@ -33,6 +34,9 @@ class PkgOpsHost @Inject constructor(
private val pm: PackageManager
get() = context.packageManager

private val am: ActivityManager
get() = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager

override fun getUserNameForUID(uid: Int): String? = try {
libcoreTool.getNameForUid(uid)
} catch (e: Exception) {
Expand All @@ -48,10 +52,19 @@ class PkgOpsHost @Inject constructor(
}

override fun isRunning(packageName: String): Boolean = try {
val result = runBlocking {
sharedShell.useRes {
Cmd.builder("pidof $packageName").execute(it)
}.exitCode == Cmd.ExitCode.OK
val result = try {
val runningAppProcesses = am.runningAppProcesses
?.flatMap { it.pkgList.toList() }
?.distinct()
?: emptyList()
runningAppProcesses.any { it == packageName }
} catch (e: Exception) {
log(TAG, ERROR) { "isRunning($packageName): runningAppProcesses failed due to ${e.asLog()} " }
runBlocking {
sharedShell.useRes {
Cmd.builder("pidof $packageName").execute(it)
}.exitCode == Cmd.ExitCode.OK
}
}
log(TAG, VERBOSE) { "isRunning(packageName=$packageName)=$result" }
result
Expand Down
40 changes: 36 additions & 4 deletions app/src/main/java/eu/darken/sdmse/appcontrol/core/AppControl.kt
Original file line number Diff line number Diff line change
Expand Up @@ -16,19 +16,25 @@ import eu.darken.sdmse.common.debug.logging.Logging.Priority.*
import eu.darken.sdmse.common.debug.logging.asLog
import eu.darken.sdmse.common.debug.logging.log
import eu.darken.sdmse.common.debug.logging.logTag
import eu.darken.sdmse.common.flow.replayingShare
import eu.darken.sdmse.common.pkgs.Pkg
import eu.darken.sdmse.common.pkgs.PkgRepo
import eu.darken.sdmse.common.pkgs.currentPkgs
import eu.darken.sdmse.common.pkgs.features.Installed
import eu.darken.sdmse.common.pkgs.isEnabled
import eu.darken.sdmse.common.pkgs.pkgops.PkgOps
import eu.darken.sdmse.common.progress.*
import eu.darken.sdmse.common.root.RootManager
import eu.darken.sdmse.common.sharedresource.SharedResource
import eu.darken.sdmse.common.shizuku.ShizukuManager
import eu.darken.sdmse.common.user.UserManager2
import eu.darken.sdmse.main.core.SDMTool
import eu.darken.sdmse.setup.usagestats.UsageStatsSetupModule
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import javax.inject.Inject
Expand All @@ -38,10 +44,13 @@ import javax.inject.Singleton
class AppControl @Inject constructor(
@AppScope private val appScope: CoroutineScope,
private val pkgRepo: PkgRepo,
private val rootManager: RootManager,
private val userManager: UserManager2,
private val componentToggler: ComponentToggler,
private val uninstaller: Uninstaller,
private val pkgOps: PkgOps,
usageStatsSetupModule: UsageStatsSetupModule,
rootManager: RootManager,
shizukuManager: ShizukuManager,
) : SDMTool, Progress.Client {

override val sharedResource = SharedResource.createKeepAlive(TAG, appScope)
Expand All @@ -53,10 +62,24 @@ class AppControl @Inject constructor(
}

private val internalData = MutableStateFlow(null as Data?)
val data: Flow<Data?> = internalData

override val type: SDMTool.Type = SDMTool.Type.APPCONTROL

val state: Flow<State> = combine(
usageStatsSetupModule.state,
rootManager.useRoot,
shizukuManager.useShizuku,
internalData,
progress,
) { usageState, useRoot, useShizuku, data, progress ->
State(
data = data,
progress = progress,
isActiveInfoAvailable = usageState.isComplete || useRoot || useShizuku,
isAppToggleAvailable = useRoot || useShizuku,
)
}.replayingShare(appScope)

private val jobLock = Mutex()
override suspend fun submit(task: SDMTool.Task): SDMTool.Task.Result = jobLock.withLock {
task as AppControlTask
Expand Down Expand Up @@ -90,7 +113,7 @@ class AppControl @Inject constructor(
.map { it.toAppInfo() }

internalData.value = Data(
apps = appInfos,
apps = appInfos
)

return AppControlScanTask.Result(
Expand Down Expand Up @@ -204,11 +227,20 @@ class AppControl @Inject constructor(
}

private suspend fun Installed.toAppInfo(): AppInfo {
val determineActive = state.first().isActiveInfoAvailable
return AppInfo(
pkg = this
pkg = this,
isActive = if (determineActive) pkgOps.isRunning(installId) else null,
)
}

data class State(
val isActiveInfoAvailable: Boolean,
val isAppToggleAvailable: Boolean,
val data: Data?,
val progress: Progress.Data?,
)

data class Data(
val apps: Collection<AppInfo>,
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import eu.darken.sdmse.common.pkgs.features.Installed

data class AppInfo(
val pkg: Installed,
val isActive: Boolean?,
) {
val label: CaString
get() = pkg.label ?: pkg.packageName.toCaString()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ data class FilterSettings(
@Json(name = "SYSTEM") SYSTEM,
@Json(name = "ENABLED") ENABLED,
@Json(name = "DISABLED") DISABLED,
@Json(name = "ACTIVE") ACTIVE,
;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,7 @@ class AppControlListFragment : Fragment3(R.layout.appcontrol_list_fragment) {
tagFilterSystemSwitch.setOnClickListener { vm.toggleTag(FilterSettings.Tag.SYSTEM) }
tagFilterEnabledSwitch.setOnClickListener { vm.toggleTag(FilterSettings.Tag.ENABLED) }
tagFilterDisabledSwitch.setOnClickListener { vm.toggleTag(FilterSettings.Tag.DISABLED) }
tagFilterActiveSwitch.setOnClickListener { vm.toggleTag(FilterSettings.Tag.ACTIVE) }
}

vm.state.observe2(ui) { state ->
Expand Down Expand Up @@ -252,6 +253,11 @@ class AppControlListFragment : Fragment3(R.layout.appcontrol_list_fragment) {
tagFilterEnabledSwitch.setChecked2(listFilter.tags.contains(FilterSettings.Tag.ENABLED), animate = false)
tagFilterDisabledSwitch.setChecked2(listFilter.tags.contains(FilterSettings.Tag.DISABLED), animate = false)

tagFilterActiveSwitch.apply {
setChecked2(listFilter.tags.contains(FilterSettings.Tag.ACTIVE), animate = false)
isEnabled = state.hasActiveInfo
}

if (state.appInfos != null) {
toolbar.subtitle = getQuantityString2(
eu.darken.sdmse.common.R.plurals.result_x_items, state.appInfos.size
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ class AppControlListRowVH(parent: ViewGroup) :

tagSystem.tagSystem.isInvisible = !appInfo.pkg.isSystemApp
tagDisabled.tagDisabled.isInvisible = appInfo.pkg.isEnabled
tagActive.tagActive.isInvisible = !(appInfo.isActive ?: false)
tagContainer.isGone = tagContainer.children.none { it.isVisible }

itemView.setOnClickListener { item.onItemClicked(appInfo) }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,9 @@ class AppControlListViewModel @Inject constructor(
) : ViewModel3(dispatcherProvider) {

init {
appControl.data
appControl.state
.take(1)
.filter { it == null }
.filter { it.data == null }
.onEach { appControl.submit(AppControlScanTask()) }
.launchInViewModel()
}
Expand Down Expand Up @@ -121,25 +121,21 @@ class AppControlListViewModel @Inject constructor(
}

val state = currentDisplayOptions.flatMapLatest { displayOptions ->
combineTransform(
appControl.data,
appControl.progress,
rootManager.useRoot,
shizukuManager.useShizuku,
) { data, progress, rootAvailable, shizukuAvailable ->
appControl.state.transformLatest { state ->
val initialState = State(
appInfos = null,
progressWorker = progress,
progressWorker = state.progress,
progressUI = Progress.DEFAULT_STATE,
options = displayOptions,
allowAppToggleActions = rootAvailable || shizukuAvailable,
allowAppToggleActions = state.isAppToggleAvailable,
hasActiveInfo = state.isActiveInfoAvailable,
)
emit(initialState)

val queryNormalized = displayOptions.searchQuery.lowercase()
val listFilter = displayOptions.listFilter
val listSort = displayOptions.listSort
val appInfos = data?.apps
val appInfos = state.data?.apps
?.filter { appInfo ->
if (queryNormalized.isEmpty()) return@filter true

Expand All @@ -154,6 +150,7 @@ class AppControlListViewModel @Inject constructor(
if (listFilter.tags.contains(FilterSettings.Tag.SYSTEM) && !it.pkg.isSystemApp) return@filter false
if (listFilter.tags.contains(FilterSettings.Tag.ENABLED) && !it.pkg.isEnabled) return@filter false
if (listFilter.tags.contains(FilterSettings.Tag.DISABLED) && it.pkg.isEnabled) return@filter false
if (listFilter.tags.contains(FilterSettings.Tag.ACTIVE) && it.isActive == false) return@filter false

return@filter true
}
Expand Down Expand Up @@ -250,6 +247,12 @@ class AppControlListViewModel @Inject constructor(
} else {
old.tags.plus(tag).minus(FilterSettings.Tag.ENABLED)
}

FilterSettings.Tag.ACTIVE -> if (existing) {
old.tags.minus(tag)
} else {
old.tags.plus(tag)
}
}
old.copy(tags = newTags)
}
Expand Down Expand Up @@ -293,6 +296,7 @@ class AppControlListViewModel @Inject constructor(
val progressUI: Progress.Data?,
val options: DisplayOptions,
val allowAppToggleActions: Boolean,
val hasActiveInfo: Boolean = false,
) {
val progress: Progress.Data?
get() = progressWorker ?: progressUI
Expand Down
Loading
Loading