More refactoring

Cleanups, move classes to sane locations, etc.
This commit is contained in:
topjohnwu
2020-08-19 02:05:23 -07:00
parent 846bbb4da1
commit 34450cdddd
85 changed files with 365 additions and 522 deletions
@@ -0,0 +1,37 @@
package com.topjohnwu.magisk.ui.flash
import android.view.View
import android.widget.TextView
import androidx.core.view.updateLayoutParams
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.RecyclerView
import com.topjohnwu.magisk.R
import com.topjohnwu.magisk.databinding.ComparableRvItem
import com.topjohnwu.magisk.databinding.LenientRvItem
import kotlin.math.max
class ConsoleItem(val item: String) : ComparableRvItem<ConsoleItem>(), LenientRvItem {
override val layoutRes = R.layout.item_console_md2
private var parentWidth = -1
override fun onBindingBound(binding: ViewDataBinding, recyclerView: RecyclerView) {
if (parentWidth < 0)
parentWidth = (recyclerView.parent as View).width
val view = binding.root as TextView
view.measure(0, 0)
// We want our recyclerView at least as wide as screen
val desiredWidth = max(view.measuredWidth, parentWidth)
view.updateLayoutParams { width = desiredWidth }
if (recyclerView.width < desiredWidth) {
recyclerView.requestLayout()
}
}
override fun contentSameAs(other: ConsoleItem) = itemSameAs(other)
override fun itemSameAs(other: ConsoleItem) = item == other.item
}
@@ -15,9 +15,8 @@ import com.topjohnwu.magisk.core.Const
import com.topjohnwu.magisk.core.tasks.FlashZip
import com.topjohnwu.magisk.core.tasks.MagiskInstaller
import com.topjohnwu.magisk.databinding.RvBindingAdapter
import com.topjohnwu.magisk.events.SnackbarEvent
import com.topjohnwu.magisk.ktx.*
import com.topjohnwu.magisk.model.entity.recycler.ConsoleItem
import com.topjohnwu.magisk.model.events.SnackbarEvent
import com.topjohnwu.magisk.utils.set
import com.topjohnwu.magisk.view.Notifications
import com.topjohnwu.superuser.CallbackList
@@ -0,0 +1,25 @@
package com.topjohnwu.magisk.ui.hide
import android.content.pm.ApplicationInfo
import android.graphics.drawable.Drawable
import com.topjohnwu.magisk.ktx.packageInfo
import com.topjohnwu.magisk.ktx.processes
data class HideAppInfo(
val info: ApplicationInfo,
val name: String,
val icon: Drawable
) {
val processes = info.packageInfo?.processes?.distinct() ?: listOf(info.packageName)
}
data class StatefulProcess(
val name: String,
val packageName: String,
val isHidden: Boolean
)
data class HideAppTarget(
val info: HideAppInfo,
val processes: List<StatefulProcess>
)
@@ -0,0 +1,92 @@
package com.topjohnwu.magisk.ui.hide
import android.view.View
import android.view.ViewGroup
import androidx.databinding.Bindable
import com.topjohnwu.magisk.BR
import com.topjohnwu.magisk.R
import com.topjohnwu.magisk.databinding.ObservableItem
import com.topjohnwu.magisk.ktx.startAnimations
import com.topjohnwu.magisk.utils.addOnPropertyChangedCallback
import com.topjohnwu.magisk.utils.set
import kotlin.math.roundToInt
class HideItem(
val item: HideAppTarget,
viewModel: HideViewModel
) : ObservableItem<HideItem>() {
override val layoutRes = R.layout.item_hide_md2
val packageName = item.info.info.packageName.orEmpty()
val items = item.processes.map { HideProcessItem(it, viewModel) }
@get:Bindable
var isExpanded = false
set(value) = set(value, field, { field = it }, BR.expanded)
var itemsChecked = 0
set(value) = set(value, field, { field = it }, BR.itemsCheckedPercent)
@get:Bindable
val itemsCheckedPercent get() = (itemsChecked.toFloat() / items.size * 100).roundToInt()
private var state: Boolean? = false
set(value) = set(value, field, { field = it }, BR.hiddenState)
@get:Bindable
var hiddenState: Boolean?
get() = state
set(value) = set(value, state, { state = it }, BR.hiddenState) {
if (value == true) {
items.filterNot { it.isHidden }
} else {
items
}.forEach { it.toggle() }
}
init {
items.forEach { it.addOnPropertyChangedCallback(BR.hidden) { recalculateChecked() } }
recalculateChecked()
}
fun toggleExpand(v: View) {
(v.parent as? ViewGroup)?.startAnimations()
isExpanded = !isExpanded
}
private fun recalculateChecked() {
itemsChecked = items.count { it.isHidden }
state = when (itemsChecked) {
0 -> false
items.size -> true
else -> null
}
}
override fun contentSameAs(other: HideItem): Boolean = item == other.item
override fun itemSameAs(other: HideItem): Boolean = item.info == other.item.info
}
class HideProcessItem(
val item: StatefulProcess,
val viewModel: HideViewModel
) : ObservableItem<HideProcessItem>() {
override val layoutRes = R.layout.item_hide_process_md2
@get:Bindable
var isHidden = item.isHidden
set(value) = set(value, field, { field = it }, BR.hidden) {
viewModel.toggleItem(this)
}
fun toggle() {
isHidden = !isHidden
}
override fun contentSameAs(other: HideProcessItem) = item == other.item
override fun itemSameAs(other: HideProcessItem) = item.name == other.item.name
}
@@ -0,0 +1,14 @@
package com.topjohnwu.magisk.ui.hide
class HideTarget(line: String) {
val packageName: String
val process: String
init {
val split = line.split(Regex("\\|"), 2)
packageName = split[0]
process = split.getOrElse(1) { packageName }
}
}
@@ -11,12 +11,6 @@ import com.topjohnwu.magisk.arch.itemBindingOf
import com.topjohnwu.magisk.core.Config
import com.topjohnwu.magisk.core.utils.currentLocale
import com.topjohnwu.magisk.data.repository.MagiskRepository
import com.topjohnwu.magisk.model.entity.HideAppInfo
import com.topjohnwu.magisk.model.entity.HideAppTarget
import com.topjohnwu.magisk.model.entity.HideTarget
import com.topjohnwu.magisk.model.entity.StatefulProcess
import com.topjohnwu.magisk.model.entity.recycler.HideItem
import com.topjohnwu.magisk.model.entity.recycler.HideProcessItem
import com.topjohnwu.magisk.utils.set
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
@@ -0,0 +1,84 @@
package com.topjohnwu.magisk.ui.home
import com.topjohnwu.magisk.R
import com.topjohnwu.magisk.core.Const
import com.topjohnwu.magisk.databinding.RvItem
sealed class DeveloperItem {
abstract val items: List<IconLink>
abstract val name: Int
object Main : DeveloperItem() {
override val items =
listOf(
IconLink.Twitter.Main,
IconLink.Patreon,
IconLink.PayPal.Main,
IconLink.Github
)
override val name get() = R.string.topjohnwu
}
object App : DeveloperItem() {
override val items =
listOf<IconLink>(
IconLink.Twitter.App,
IconLink.PayPal.App
)
override val name get() = R.string.diareuse
}
}
private interface Dev {
val name: String
}
private interface MainDev: Dev {
override val name get() = "topjohnwu"
}
private interface AppDev: Dev {
override val name get() = "diareuse"
}
sealed class IconLink : RvItem() {
abstract val icon: Int
abstract val title: Int
abstract val link: String
override val layoutRes get() = R.layout.item_icon_link
sealed class PayPal : IconLink(), Dev {
override val icon get() = R.drawable.ic_paypal
override val title get() = R.string.paypal
override val link get() = "https://paypal.me/$name"
object App : PayPal(), AppDev
object Main : PayPal(), MainDev
}
object Patreon : IconLink() {
override val icon get() = R.drawable.ic_patreon
override val title get() = R.string.patreon
override val link get() = Const.Url.PATREON_URL
}
sealed class Twitter : IconLink(), Dev {
override val icon get() = R.drawable.ic_twitter
override val title get() = R.string.twitter
override val link get() = "https://twitter.com/$name"
object App : Twitter(), AppDev
object Main : Twitter(), MainDev
}
object Github : IconLink() {
override val icon get() = R.drawable.ic_github
override val title get() = R.string.home_item_source
override val link get() = Const.Url.SOURCE_CODE_URL
}
}
@@ -5,7 +5,7 @@ import android.view.*
import com.topjohnwu.magisk.R
import com.topjohnwu.magisk.arch.BaseUIFragment
import com.topjohnwu.magisk.databinding.FragmentHomeMd2Binding
import com.topjohnwu.magisk.model.events.RebootEvent
import com.topjohnwu.magisk.events.RebootEvent
import com.topjohnwu.superuser.Shell
import org.koin.androidx.viewmodel.ext.android.viewModel
@@ -16,15 +16,14 @@ import com.topjohnwu.magisk.core.download.RemoteFileService
import com.topjohnwu.magisk.core.model.MagiskJson
import com.topjohnwu.magisk.core.model.ManagerJson
import com.topjohnwu.magisk.data.repository.MagiskRepository
import com.topjohnwu.magisk.events.OpenInappLinkEvent
import com.topjohnwu.magisk.events.dialog.EnvFixDialog
import com.topjohnwu.magisk.events.dialog.ManagerInstallDialog
import com.topjohnwu.magisk.events.dialog.UninstallDialog
import com.topjohnwu.magisk.ktx.await
import com.topjohnwu.magisk.ktx.packageName
import com.topjohnwu.magisk.ktx.res
import com.topjohnwu.magisk.model.entity.IconLink
import com.topjohnwu.magisk.model.entity.internal.DownloadSubject.Manager
import com.topjohnwu.magisk.model.events.OpenInappLinkEvent
import com.topjohnwu.magisk.model.events.dialog.EnvFixDialog
import com.topjohnwu.magisk.model.events.dialog.ManagerInstallDialog
import com.topjohnwu.magisk.model.events.dialog.UninstallDialog
import com.topjohnwu.magisk.model.internal.DownloadSubject.Manager
import com.topjohnwu.magisk.utils.set
import com.topjohnwu.superuser.Shell
import kotlinx.coroutines.launch
@@ -5,7 +5,7 @@ import androidx.lifecycle.viewModelScope
import com.topjohnwu.magisk.R
import com.topjohnwu.magisk.arch.BaseUIFragment
import com.topjohnwu.magisk.databinding.FragmentInstallMd2Binding
import com.topjohnwu.magisk.model.events.RequestFileEvent
import com.topjohnwu.magisk.events.RequestFileEvent
import org.koin.androidx.viewmodel.ext.android.viewModel
class InstallFragment : BaseUIFragment<InstallViewModel, FragmentInstallMd2Binding>() {
@@ -11,10 +11,10 @@ import com.topjohnwu.magisk.core.Info
import com.topjohnwu.magisk.core.download.DownloadService
import com.topjohnwu.magisk.core.download.RemoteFileService
import com.topjohnwu.magisk.data.repository.StringRepository
import com.topjohnwu.magisk.model.entity.internal.Configuration
import com.topjohnwu.magisk.model.entity.internal.DownloadSubject
import com.topjohnwu.magisk.model.events.RequestFileEvent
import com.topjohnwu.magisk.model.events.dialog.SecondSlotWarningDialog
import com.topjohnwu.magisk.events.RequestFileEvent
import com.topjohnwu.magisk.events.dialog.SecondSlotWarningDialog
import com.topjohnwu.magisk.model.internal.Configuration
import com.topjohnwu.magisk.model.internal.DownloadSubject
import com.topjohnwu.magisk.utils.Utils
import com.topjohnwu.magisk.utils.set
import com.topjohnwu.superuser.Shell
@@ -0,0 +1,37 @@
package com.topjohnwu.magisk.ui.log
import androidx.databinding.Bindable
import com.topjohnwu.magisk.BR
import com.topjohnwu.magisk.R
import com.topjohnwu.magisk.core.model.su.SuLog
import com.topjohnwu.magisk.databinding.ObservableItem
import com.topjohnwu.magisk.ktx.timeDateFormat
import com.topjohnwu.magisk.ktx.toTime
import com.topjohnwu.magisk.utils.set
class LogRvItem(val item: SuLog) : ObservableItem<LogRvItem>() {
override val layoutRes = R.layout.item_log_access_md2
val date = item.time.toTime(timeDateFormat)
@get:Bindable
var isTop = false
set(value) = set(value, field, { field = it }, BR.top)
@get:Bindable
var isBottom = false
set(value) = set(value, field, { field = it }, BR.bottom)
override fun itemSameAs(other: LogRvItem) = item.appName == other.item.appName
override fun contentSameAs(other: LogRvItem) = item.fromUid == other.item.fromUid &&
item.toUid == other.item.toUid &&
item.fromPid == other.item.fromPid &&
item.packageName == other.item.packageName &&
item.command == other.item.command &&
item.action == other.item.action &&
item.time == other.item.time &&
isTop == other.isTop &&
isBottom == other.isBottom
}
@@ -10,10 +10,9 @@ import com.topjohnwu.magisk.arch.itemBindingOf
import com.topjohnwu.magisk.core.Config
import com.topjohnwu.magisk.core.Const
import com.topjohnwu.magisk.data.repository.LogRepository
import com.topjohnwu.magisk.model.entity.recycler.LogItem
import com.topjohnwu.magisk.model.entity.recycler.TextItem
import com.topjohnwu.magisk.model.events.SnackbarEvent
import com.topjohnwu.magisk.events.SnackbarEvent
import com.topjohnwu.magisk.utils.set
import com.topjohnwu.magisk.view.TextItem
import com.topjohnwu.superuser.Shell
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
@@ -34,8 +33,8 @@ class LogViewModel(
// --- su log
val items = diffListOf<LogItem>()
val itemBinding = itemBindingOf<LogItem> {
val items = diffListOf<LogRvItem>()
val itemBinding = itemBindingOf<LogRvItem> {
it.bindExtra(BR.viewModel, this)
}
@@ -47,7 +46,7 @@ class LogViewModel(
override fun refresh() = viewModelScope.launch {
consoleText = repo.fetchMagiskLogs()
val (suLogs, diff) = withContext(Dispatchers.Default) {
val suLogs = repo.fetchSuLogs().map { LogItem(it) }
val suLogs = repo.fetchSuLogs().map { LogRvItem(it) }
suLogs to items.calculateDiff(suLogs)
}
items.firstOrNull()?.isTop = false
@@ -13,8 +13,8 @@ import com.topjohnwu.magisk.arch.BaseUIFragment
import com.topjohnwu.magisk.arch.ReselectionTarget
import com.topjohnwu.magisk.arch.ViewEvent
import com.topjohnwu.magisk.databinding.FragmentModuleMd2Binding
import com.topjohnwu.magisk.events.InstallExternalModuleEvent
import com.topjohnwu.magisk.ktx.hideKeyboard
import com.topjohnwu.magisk.model.events.InstallExternalModuleEvent
import com.topjohnwu.magisk.ui.MainActivity
import com.topjohnwu.magisk.utils.EndlessRecyclerScrollListener
import com.topjohnwu.magisk.utils.MotionRevealHelper
@@ -0,0 +1,98 @@
package com.topjohnwu.magisk.ui.module
import androidx.databinding.Bindable
import com.topjohnwu.magisk.BR
import com.topjohnwu.magisk.R
import com.topjohnwu.magisk.core.model.module.Module
import com.topjohnwu.magisk.core.model.module.Repo
import com.topjohnwu.magisk.databinding.ComparableRvItem
import com.topjohnwu.magisk.databinding.ObservableItem
import com.topjohnwu.magisk.utils.set
object InstallModule : ComparableRvItem<InstallModule>() {
override val layoutRes = R.layout.item_module_download
override fun contentSameAs(other: InstallModule) = this == other
override fun itemSameAs(other: InstallModule) = this === other
}
class SectionTitle(
val title: Int,
_button: Int = 0,
_icon: Int = 0
) : ObservableItem<SectionTitle>() {
override val layoutRes = R.layout.item_section_md2
@get:Bindable
var button = _button
set(value) = set(value, field, { field = it }, BR.button)
@get:Bindable
var icon = _icon
set(value) = set(value, field, { field = it }, BR.icon)
@get:Bindable
var hasButton = _button != 0 && _icon != 0
set(value) = set(value, field, { field = it }, BR.hasButton)
override fun itemSameAs(other: SectionTitle): Boolean = this === other
override fun contentSameAs(other: SectionTitle): Boolean = this === other
}
sealed class RepoItem(val item: Repo) : ObservableItem<RepoItem>() {
override val layoutRes: Int = R.layout.item_repo_md2
@get:Bindable
var progress = 0
set(value) = set(value, field, { field = it }, BR.progress)
abstract val isUpdate: Boolean
override fun contentSameAs(other: RepoItem): Boolean = item == other.item
override fun itemSameAs(other: RepoItem): Boolean = item.id == other.item.id
class Update(item: Repo) : RepoItem(item) {
override val isUpdate get() = true
}
class Remote(item: Repo) : RepoItem(item) {
override val isUpdate get() = false
}
}
class ModuleItem(val item: Module) : ObservableItem<ModuleItem>() {
override val layoutRes = R.layout.item_module_md2
@get:Bindable
var repo: Repo? = null
set(value) = set(value, field, { field = it }, BR.repo)
@get:Bindable
var isEnabled = item.enable
set(value) = set(value, field, { field = it }, BR.enabled) {
item.enable = value
}
@get:Bindable
var isRemoved = item.remove
set(value) = set(value, field, { field = it }, BR.removed) {
item.remove = value
}
val isUpdated get() = item.updated
val isModified get() = isRemoved || isUpdated
fun delete(viewModel: ModuleViewModel) {
isRemoved = !isRemoved
viewModel.updateActiveState()
}
override fun contentSameAs(other: ModuleItem): Boolean = item.version == other.item.version
&& item.versionCode == other.item.versionCode
&& item.description == other.item.description
&& item.name == other.item.name
override fun itemSameAs(other: ModuleItem): Boolean = item.id == other.item.id
}
@@ -14,16 +14,12 @@ import com.topjohnwu.magisk.core.tasks.RepoUpdater
import com.topjohnwu.magisk.data.database.RepoByNameDao
import com.topjohnwu.magisk.data.database.RepoByUpdatedDao
import com.topjohnwu.magisk.databinding.RvItem
import com.topjohnwu.magisk.events.InstallExternalModuleEvent
import com.topjohnwu.magisk.events.OpenChangelogEvent
import com.topjohnwu.magisk.events.dialog.ModuleInstallDialog
import com.topjohnwu.magisk.ktx.addOnListChangedCallback
import com.topjohnwu.magisk.ktx.reboot
import com.topjohnwu.magisk.model.entity.internal.DownloadSubject
import com.topjohnwu.magisk.model.entity.recycler.InstallModule
import com.topjohnwu.magisk.model.entity.recycler.ModuleItem
import com.topjohnwu.magisk.model.entity.recycler.RepoItem
import com.topjohnwu.magisk.model.entity.recycler.SectionTitle
import com.topjohnwu.magisk.model.events.InstallExternalModuleEvent
import com.topjohnwu.magisk.model.events.OpenChangelogEvent
import com.topjohnwu.magisk.model.events.dialog.ModuleInstallDialog
import com.topjohnwu.magisk.model.internal.DownloadSubject
import com.topjohnwu.magisk.utils.EndlessRecyclerScrollListener
import com.topjohnwu.magisk.utils.set
import kotlinx.coroutines.Dispatchers
@@ -0,0 +1,132 @@
package com.topjohnwu.magisk.ui.safetynet
import android.content.Context
import com.topjohnwu.magisk.R
import com.topjohnwu.magisk.arch.ContextExecutor
import com.topjohnwu.magisk.arch.ViewEventWithScope
import com.topjohnwu.magisk.core.Const
import com.topjohnwu.magisk.data.network.GithubRawServices
import com.topjohnwu.magisk.ktx.DynamicClassLoader
import com.topjohnwu.magisk.ktx.writeTo
import com.topjohnwu.magisk.view.MagiskDialog
import com.topjohnwu.superuser.Shell
import dalvik.system.DexFile
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.json.JSONObject
import org.koin.core.KoinComponent
import org.koin.core.inject
import timber.log.Timber
import java.io.File
import java.io.IOException
import java.lang.reflect.InvocationHandler
@Suppress("DEPRECATION")
class CheckSafetyNetEvent(
private val callback: (SafetyNetResult) -> Unit = {}
) : ViewEventWithScope(), ContextExecutor, KoinComponent, SafetyNetHelper.Callback {
private val svc by inject<GithubRawServices>()
private lateinit var apk: File
private lateinit var dex: File
override fun invoke(context: Context) {
apk = File("${context.filesDir.parent}/snet", "snet.jar")
dex = File(apk.parent, "snet.dex")
scope.launch {
attest(context) {
// Download and retry
withContext(Dispatchers.IO) {
Shell.sh("rm -rf " + apk.parent).exec()
apk.parentFile?.mkdir()
}
download(context, true)
}
}
}
private suspend fun attest(context: Context, onError: suspend (Exception) -> Unit) {
try {
val helper = withContext(Dispatchers.IO) {
val loader = DynamicClassLoader(apk)
val dex = DexFile.loadDex(apk.path, dex.path, 0)
// Scan through the dex and find our helper class
var helperClass: Class<*>? = null
for (className in dex.entries()) {
if (className.startsWith("x.")) {
val cls = loader.loadClass(className)
if (InvocationHandler::class.java.isAssignableFrom(cls)) {
helperClass = cls
break
}
}
}
helperClass ?: throw Exception()
val helper = helperClass
.getMethod("get", Class::class.java, Context::class.java, Any::class.java)
.invoke(
null, SafetyNetHelper::class.java,
context, this@CheckSafetyNetEvent
) as SafetyNetHelper
if (helper.version < Const.SNET_EXT_VER)
throw Exception()
helper
}
helper.attest()
} catch (e: Exception) {
if (e is CancellationException)
throw e
onError(e)
}
}
@Suppress("SameParameterValue")
private fun download(context: Context, askUser: Boolean) {
fun downloadInternal() = scope.launch {
val abort: suspend (Exception) -> Unit = {
Timber.e(it)
callback(SafetyNetResult())
}
try {
withContext(Dispatchers.IO) {
svc.fetchSafetynet().byteStream().writeTo(apk)
}
attest(context, abort)
} catch (e: IOException) {
if (e is CancellationException)
throw e
abort(e)
}
}
if (!askUser) {
downloadInternal()
return
}
MagiskDialog(context)
.applyTitle(R.string.proprietary_title)
.applyMessage(R.string.proprietary_notice)
.cancellable(false)
.applyButton(MagiskDialog.ButtonType.POSITIVE) {
titleRes = R.string.yes
onClick { downloadInternal() }
}
.applyButton(MagiskDialog.ButtonType.NEGATIVE) {
titleRes = android.R.string.cancel
onClick { callback(SafetyNetResult(dismiss = true)) }
}
.reveal()
}
override fun onResponse(response: JSONObject?) {
callback(SafetyNetResult(response))
}
}
@@ -0,0 +1,14 @@
package com.topjohnwu.magisk.ui.safetynet
import org.json.JSONObject
interface SafetyNetHelper {
val version: Int
fun attest()
interface Callback {
fun onResponse(response: JSONObject?)
}
}
@@ -4,7 +4,6 @@ import androidx.databinding.Bindable
import com.topjohnwu.magisk.BR
import com.topjohnwu.magisk.R
import com.topjohnwu.magisk.arch.BaseViewModel
import com.topjohnwu.magisk.model.events.CheckSafetyNetEvent
import com.topjohnwu.magisk.ui.safetynet.SafetyNetState.*
import com.topjohnwu.magisk.utils.set
import org.json.JSONObject
@@ -54,7 +53,7 @@ class SafetynetViewModel : BaseViewModel() {
private fun attest() {
currentState = LOADING
CheckSafetyNetEvent() {
CheckSafetyNetEvent {
resolveResponse(it)
}.publish()
}
@@ -0,0 +1,185 @@
package com.topjohnwu.magisk.ui.settings
import android.content.Context
import android.content.res.Resources
import android.view.View
import androidx.annotation.ArrayRes
import androidx.annotation.CallSuper
import androidx.databinding.Bindable
import com.topjohnwu.magisk.BR
import com.topjohnwu.magisk.R
import com.topjohnwu.magisk.databinding.ObservableItem
import com.topjohnwu.magisk.utils.TransitiveText
import com.topjohnwu.magisk.utils.asTransitive
import com.topjohnwu.magisk.utils.set
import com.topjohnwu.magisk.view.MagiskDialog
import org.koin.core.KoinComponent
import org.koin.core.get
sealed class BaseSettingsItem : ObservableItem<BaseSettingsItem>() {
override val layoutRes get() = R.layout.item_settings
open val icon: Int get() = 0
open val title: TransitiveText get() = TransitiveText.EMPTY
@get:Bindable
open val description: TransitiveText get() = TransitiveText.EMPTY
// ---
open val showSwitch get() = false
@get:Bindable
open val isChecked get() = false
open fun onToggle(view: View, callback: Callback, checked: Boolean) {}
// ---
@get:Bindable
var isEnabled = true
set(value) = set(value, field, { field = it }, BR.enabled)
open fun onPressed(view: View, callback: Callback) {
callback.onItemPressed(view, this)
}
open fun refresh() {}
override fun itemSameAs(other: BaseSettingsItem) = this === other
override fun contentSameAs(other: BaseSettingsItem) = itemSameAs(other)
// ---
interface Callback {
fun onItemPressed(view: View, item: BaseSettingsItem, callback: () -> Unit = {})
fun onItemChanged(view: View, item: BaseSettingsItem)
}
// ---
abstract class Value<T> : BaseSettingsItem() {
/**
* Represents last agreed-upon value by the validation process and the user for current
* child. Be very aware that this shouldn't be **set** unless both sides agreed that _that_
* is the new value.
*
* Annotating [value] as [Bindable] property should raise red flags immediately. If you
* need a [Bindable] property create another one. Seriously.
* */
abstract var value: T
/**
* We don't want this to be accessible to be set from outside the instances. It will
* introduce unwanted bugs!
* */
protected set
protected var callbackVars: Pair<View, Callback>? = null
@CallSuper
override fun onPressed(view: View, callback: Callback) {
callbackVars = view to callback
callback.onItemPressed(view, this) {
onPressed(view)
}
}
abstract fun onPressed(view: View)
protected inline fun <reified T> setV(
new: T, old: T, setter: (T) -> Unit, afterChanged: (T) -> Unit = {}) {
set(new, old, setter, BR.description, BR.checked) {
afterChanged(it)
callbackVars?.let { (view, callback) ->
callbackVars = null
callback.onItemChanged(view, this)
}
}
}
}
abstract class Toggle : Value<Boolean>() {
override val showSwitch get() = true
override val isChecked get() = value
override fun onToggle(view: View, callback: Callback, checked: Boolean) =
set(checked, value, { onPressed(view, callback) }, BR.checked)
override fun onPressed(view: View) {
value = !value
}
}
abstract class Input : Value<String>() {
protected abstract val inputResult: String?
override fun onPressed(view: View) {
MagiskDialog(view.context)
.applyTitle(title.getText(view.resources))
.applyView(getView(view.context))
.applyButton(MagiskDialog.ButtonType.POSITIVE) {
titleRes = android.R.string.ok
onClick {
inputResult?.let { result ->
preventDismiss = false
value = result
it.dismiss()
return@onClick
}
preventDismiss = true
}
}
.applyButton(MagiskDialog.ButtonType.NEGATIVE) {
titleRes = android.R.string.cancel
}
.reveal()
}
abstract fun getView(context: Context): View
}
abstract class Selector : Value<Int>(), KoinComponent {
protected val resources get() = get<Resources>()
@ArrayRes open val entryRes = -1
@ArrayRes open val entryValRes = -1
open val entries get() = resources.getArrayOrEmpty(entryRes)
open val entryValues get() = resources.getArrayOrEmpty(entryValRes)
override val description: TransitiveText
get() = entries.getOrNull(value)?.asTransitive() ?: TransitiveText.EMPTY
private fun Resources.getArrayOrEmpty(id: Int): Array<String> =
runCatching { getStringArray(id) }.getOrDefault(emptyArray())
override fun onPressed(view: View, callback: Callback) {
if (entries.isEmpty() || entryValues.isEmpty()) return
super.onPressed(view, callback)
}
override fun onPressed(view: View) {
MagiskDialog(view.context)
.applyTitle(title.getText(resources))
.applyButton(MagiskDialog.ButtonType.NEGATIVE) {
titleRes = android.R.string.cancel
}
.applyAdapter(entries) {
value = it
}
.reveal()
}
}
abstract class Blank : BaseSettingsItem()
abstract class Section : BaseSettingsItem() {
override val layoutRes = R.layout.item_settings_section
}
}
@@ -19,7 +19,6 @@ import com.topjohnwu.magisk.databinding.DialogSettingsAppNameBinding
import com.topjohnwu.magisk.databinding.DialogSettingsDownloadPathBinding
import com.topjohnwu.magisk.databinding.DialogSettingsUpdateChannelBinding
import com.topjohnwu.magisk.ktx.get
import com.topjohnwu.magisk.model.entity.recycler.SettingsItem
import com.topjohnwu.magisk.utils.Utils
import com.topjohnwu.magisk.utils.asTransitive
import com.topjohnwu.magisk.utils.set
@@ -30,11 +29,11 @@ import java.io.File
// --- Customization
object Customization : SettingsItem.Section() {
object Customization : BaseSettingsItem.Section() {
override val title = R.string.settings_customization.asTransitive()
}
object Language : SettingsItem.Selector() {
object Language : BaseSettingsItem.Selector() {
override var value = -1
set(value) = setV(value, field, { field = it }) {
Config.locale = entryValues[it]
@@ -56,18 +55,18 @@ object Language : SettingsItem.Selector() {
}
}
object Theme : SettingsItem.Blank() {
object Theme : BaseSettingsItem.Blank() {
override val icon = R.drawable.ic_paint
override val title = R.string.section_theme.asTransitive()
}
// --- Manager
object Manager : SettingsItem.Section() {
object Manager : BaseSettingsItem.Section() {
override val title = R.string.manager.asTransitive()
}
object ClearRepoCache : SettingsItem.Blank() {
object ClearRepoCache : BaseSettingsItem.Blank() {
override val title = R.string.settings_clear_cache_title.asTransitive()
override val description = R.string.settings_clear_cache_summary.asTransitive()
@@ -76,7 +75,7 @@ object ClearRepoCache : SettingsItem.Blank() {
}
}
object Hide : SettingsItem.Input() {
object Hide : BaseSettingsItem.Input() {
override val title = R.string.settings_hide_manager_title.asTransitive()
override val description = R.string.settings_hide_manager_summary.asTransitive()
@@ -99,7 +98,7 @@ object Hide : SettingsItem.Input() {
}
object Restore : SettingsItem.Blank() {
object Restore : BaseSettingsItem.Blank() {
override val title = R.string.settings_restore_manager_title.asTransitive()
override val description = R.string.settings_restore_manager_summary.asTransitive()
}
@@ -108,7 +107,7 @@ object Restore : SettingsItem.Blank() {
fun HideOrRestore() =
if (get<Context>().packageName == BuildConfig.APPLICATION_ID) Hide else Restore
object DownloadPath : SettingsItem.Input() {
object DownloadPath : BaseSettingsItem.Input() {
override var value = Config.downloadPath
set(value) = setV(value, field, { field = it }) { Config.downloadPath = it }
@@ -130,7 +129,7 @@ object DownloadPath : SettingsItem.Input() {
.inflate(LayoutInflater.from(context)).also { it.data = this }.root
}
object UpdateChannel : SettingsItem.Selector() {
object UpdateChannel : BaseSettingsItem.Selector() {
override var value = Config.updateChannel
set(value) = setV(value, field, { field = it }) { Config.updateChannel = it }
@@ -142,7 +141,7 @@ object UpdateChannel : SettingsItem.Selector() {
override val entryValRes = R.array.value_array
}
object UpdateChannelUrl : SettingsItem.Input() {
object UpdateChannelUrl : BaseSettingsItem.Input() {
override val title = R.string.settings_update_custom.asTransitive()
override var value = Config.customChannelUrl
set(value) = setV(value, field, { field = it }) { Config.customChannelUrl = it }
@@ -162,7 +161,7 @@ object UpdateChannelUrl : SettingsItem.Input() {
.inflate(LayoutInflater.from(context)).also { it.data = this }.root
}
object UpdateChecker : SettingsItem.Toggle() {
object UpdateChecker : BaseSettingsItem.Toggle() {
override val title = R.string.settings_check_update_title.asTransitive()
override val description = R.string.settings_check_update_summary.asTransitive()
override var value = Config.checkUpdate
@@ -173,12 +172,12 @@ object UpdateChecker : SettingsItem.Toggle() {
}
// check whether is module already installed beforehand?
object SystemlessHosts : SettingsItem.Blank() {
object SystemlessHosts : BaseSettingsItem.Blank() {
override val title = R.string.settings_hosts_title.asTransitive()
override val description = R.string.settings_hosts_summary.asTransitive()
}
object Biometrics : SettingsItem.Toggle() {
object Biometrics : BaseSettingsItem.Toggle() {
override val title = R.string.settings_su_biometric_title.asTransitive()
override var value = Config.suBiometric
set(value) = setV(value, field, { field = it }) { Config.suBiometric = it }
@@ -193,7 +192,7 @@ object Biometrics : SettingsItem.Toggle() {
}
}
object Reauthenticate : SettingsItem.Toggle() {
object Reauthenticate : BaseSettingsItem.Toggle() {
override val title = R.string.settings_su_reauth_title.asTransitive()
override val description = R.string.settings_su_reauth_summary.asTransitive()
override var value = Config.suReAuth
@@ -206,11 +205,11 @@ object Reauthenticate : SettingsItem.Toggle() {
// --- Magisk
object Magisk : SettingsItem.Section() {
object Magisk : BaseSettingsItem.Section() {
override val title = R.string.magisk.asTransitive()
}
object MagiskHide : SettingsItem.Toggle() {
object MagiskHide : BaseSettingsItem.Toggle() {
override val title = R.string.magiskhide.asTransitive()
override val description = R.string.settings_magiskhide_summary.asTransitive()
override var value = Config.magiskHide
@@ -225,11 +224,11 @@ object MagiskHide : SettingsItem.Toggle() {
// --- Superuser
object Superuser : SettingsItem.Section() {
object Superuser : BaseSettingsItem.Section() {
override val title = R.string.superuser.asTransitive()
}
object AccessMode : SettingsItem.Selector() {
object AccessMode : BaseSettingsItem.Selector() {
override val title = R.string.superuser_access.asTransitive()
override val entryRes = R.array.su_access
override val entryValRes = R.array.value_array
@@ -240,7 +239,7 @@ object AccessMode : SettingsItem.Selector() {
}
}
object MultiuserMode : SettingsItem.Selector() {
object MultiuserMode : BaseSettingsItem.Selector() {
override val title = R.string.multiuser_mode.asTransitive()
override val entryRes = R.array.multiuser_mode
override val entryValRes = R.array.value_array
@@ -258,7 +257,7 @@ object MultiuserMode : SettingsItem.Selector() {
}
}
object MountNamespaceMode : SettingsItem.Selector() {
object MountNamespaceMode : BaseSettingsItem.Selector() {
override val title = R.string.mount_namespace_mode.asTransitive()
override val entryRes = R.array.namespace
override val entryValRes = R.array.value_array
@@ -272,7 +271,7 @@ object MountNamespaceMode : SettingsItem.Selector() {
get() = resources.getStringArray(R.array.namespace_summary)[value].asTransitive()
}
object AutomaticResponse : SettingsItem.Selector() {
object AutomaticResponse : BaseSettingsItem.Selector() {
override val title = R.string.auto_response.asTransitive()
override val entryRes = R.array.auto_response
override val entryValRes = R.array.value_array
@@ -283,7 +282,7 @@ object AutomaticResponse : SettingsItem.Selector() {
}
}
object RequestTimeout : SettingsItem.Selector() {
object RequestTimeout : BaseSettingsItem.Selector() {
override val title = R.string.request_timeout.asTransitive()
override val entryRes = R.array.request_timeout
override val entryValRes = R.array.request_timeout_value
@@ -297,7 +296,7 @@ object RequestTimeout : SettingsItem.Selector() {
get() = entryValues.indexOfFirst { it.toInt() == Config.suDefaultTimeout }
}
object SUNotification : SettingsItem.Selector() {
object SUNotification : BaseSettingsItem.Selector() {
override val title = R.string.superuser_notification.asTransitive()
override val entryRes = R.array.su_notification
override val entryValRes = R.array.value_array
@@ -15,11 +15,10 @@ import com.topjohnwu.magisk.core.Info
import com.topjohnwu.magisk.core.download.DownloadService
import com.topjohnwu.magisk.core.utils.PatchAPK
import com.topjohnwu.magisk.data.database.RepoDao
import com.topjohnwu.magisk.model.entity.internal.Configuration
import com.topjohnwu.magisk.model.entity.internal.DownloadSubject
import com.topjohnwu.magisk.model.entity.recycler.SettingsItem
import com.topjohnwu.magisk.model.events.RecreateEvent
import com.topjohnwu.magisk.model.events.dialog.BiometricDialog
import com.topjohnwu.magisk.events.RecreateEvent
import com.topjohnwu.magisk.events.dialog.BiometricDialog
import com.topjohnwu.magisk.model.internal.Configuration
import com.topjohnwu.magisk.model.internal.DownloadSubject
import com.topjohnwu.magisk.utils.Utils
import com.topjohnwu.superuser.Shell
import kotlinx.coroutines.launch
@@ -27,10 +26,10 @@ import org.koin.core.get
class SettingsViewModel(
private val repositoryDao: RepoDao
) : BaseViewModel(), SettingsItem.Callback {
) : BaseViewModel(), BaseSettingsItem.Callback {
val adapter = adapterOf<SettingsItem>()
val itemBinding = itemBindingOf<SettingsItem> { it.bindExtra(BR.callback, this) }
val adapter = adapterOf<BaseSettingsItem>()
val itemBinding = itemBindingOf<BaseSettingsItem> { it.bindExtra(BR.callback, this) }
val items = diffListOf(createItems())
init {
@@ -39,7 +38,7 @@ class SettingsViewModel(
}
}
private fun createItems(): List<SettingsItem> {
private fun createItems(): List<BaseSettingsItem> {
// Customization
val list = mutableListOf(
Customization,
@@ -90,7 +89,7 @@ class SettingsViewModel(
return list
}
override fun onItemPressed(view: View, item: SettingsItem, callback: () -> Unit) = when (item) {
override fun onItemPressed(view: View, item: BaseSettingsItem, callback: () -> Unit) = when (item) {
is DownloadPath -> withExternalRW(callback)
is Biometrics -> authenticate(callback)
is Theme -> SettingsFragmentDirections.actionSettingsFragmentToThemeFragment().publish()
@@ -100,7 +99,7 @@ class SettingsViewModel(
else -> callback()
}
override fun onItemChanged(view: View, item: SettingsItem) = when (item) {
override fun onItemChanged(view: View, item: BaseSettingsItem) = when (item) {
is Language -> RecreateEvent().publish()
is UpdateChannel -> openUrlIfNecessary(view)
is Hide -> PatchAPK.hideManager(view.context, item.value)
@@ -0,0 +1,70 @@
package com.topjohnwu.magisk.ui.superuser
import android.graphics.drawable.Drawable
import androidx.databinding.Bindable
import com.topjohnwu.magisk.BR
import com.topjohnwu.magisk.R
import com.topjohnwu.magisk.core.model.su.SuPolicy
import com.topjohnwu.magisk.databinding.ObservableItem
import com.topjohnwu.magisk.utils.set
class PolicyRvItem(
val item: SuPolicy,
val icon: Drawable,
val viewModel: SuperuserViewModel
) : ObservableItem<PolicyRvItem>() {
override val layoutRes = R.layout.item_policy_md2
@get:Bindable
var isExpanded = false
set(value) = set(value, field, { field = it }, BR.expanded)
// This property hosts the policy state
var policyState = item.policy == SuPolicy.ALLOW
set(value) = set(value, field, { field = it }, BR.enabled)
// This property binds with the UI state
@get:Bindable
var isEnabled
get() = policyState
set(value) = set(value, policyState, { viewModel.togglePolicy(this, it) }, BR.enabled)
@get:Bindable
var shouldNotify = item.notification
set(value) = set(value, field, { field = it }, BR.shouldNotify) {
viewModel.updatePolicy(updatedPolicy, isLogging = false)
}
@get:Bindable
var shouldLog = item.logging
set(value) = set(value, field, { field = it }, BR.shouldLog) {
viewModel.updatePolicy(updatedPolicy, isLogging = true)
}
private val updatedPolicy
get() = item.copy(
policy = if (policyState) SuPolicy.ALLOW else SuPolicy.DENY,
notification = shouldNotify,
logging = shouldLog
)
fun toggleExpand() {
isExpanded = !isExpanded
}
fun toggleNotify() {
shouldNotify = !shouldNotify
}
fun toggleLog() {
shouldLog = !shouldLog
}
fun revoke() {
viewModel.deletePressed(this)
}
override fun contentSameAs(other: PolicyRvItem) = itemSameAs(other)
override fun itemSameAs(other: PolicyRvItem) = item.uid == other.item.uid
}
@@ -0,0 +1,13 @@
package com.topjohnwu.magisk.ui.superuser
import com.topjohnwu.magisk.R
import com.topjohnwu.magisk.databinding.ComparableRvItem
class SpinnerRvItem(val item: String) : ComparableRvItem<SpinnerRvItem>() {
override val layoutRes: Int = R.layout.item_spinner
override fun contentSameAs(other: SpinnerRvItem) = itemSameAs(other)
override fun itemSameAs(other: SpinnerRvItem) = item == other.item
}
@@ -11,16 +11,15 @@ import com.topjohnwu.magisk.arch.adapterOf
import com.topjohnwu.magisk.arch.diffListOf
import com.topjohnwu.magisk.arch.itemBindingOf
import com.topjohnwu.magisk.core.magiskdb.PolicyDao
import com.topjohnwu.magisk.core.model.MagiskPolicy
import com.topjohnwu.magisk.core.model.su.SuPolicy
import com.topjohnwu.magisk.core.utils.BiometricHelper
import com.topjohnwu.magisk.core.utils.currentLocale
import com.topjohnwu.magisk.databinding.ComparableRvItem
import com.topjohnwu.magisk.model.entity.recycler.PolicyItem
import com.topjohnwu.magisk.model.entity.recycler.TappableHeadlineItem
import com.topjohnwu.magisk.model.entity.recycler.TextItem
import com.topjohnwu.magisk.model.events.SnackbarEvent
import com.topjohnwu.magisk.model.events.dialog.BiometricDialog
import com.topjohnwu.magisk.model.events.dialog.SuperuserRevokeDialog
import com.topjohnwu.magisk.events.SnackbarEvent
import com.topjohnwu.magisk.events.dialog.BiometricDialog
import com.topjohnwu.magisk.events.dialog.SuperuserRevokeDialog
import com.topjohnwu.magisk.view.TappableHeadlineItem
import com.topjohnwu.magisk.view.TextItem
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
@@ -34,7 +33,7 @@ class SuperuserViewModel(
private val itemNoData = TextItem(R.string.superuser_policy_none)
private val itemsPolicies = diffListOf<PolicyItem>()
private val itemsPolicies = diffListOf<PolicyRvItem>()
private val itemsHelpers = ObservableArrayList<TextItem>()
val adapter = adapterOf<ComparableRvItem<*>>()
@@ -52,7 +51,7 @@ class SuperuserViewModel(
state = State.LOADING
val (policies, diff) = withContext(Dispatchers.Default) {
val policies = db.fetchAll {
PolicyItem(it, it.applicationInfo.loadIcon(packageManager), this@SuperuserViewModel)
PolicyRvItem(it, it.applicationInfo.loadIcon(packageManager), this@SuperuserViewModel)
}.sortedWith(compareBy(
{ it.item.appName.toLowerCase(currentLocale) },
{ it.item.packageName }
@@ -77,7 +76,7 @@ class SuperuserViewModel(
private fun hidePressed() =
SuperuserFragmentDirections.actionSuperuserFragmentToHideFragment().publish()
fun deletePressed(item: PolicyItem) {
fun deletePressed(item: PolicyRvItem) {
fun updateState() = viewModelScope.launch {
db.delete(item.item.uid)
itemsPolicies.removeAll { it.genericItemSameAs(item) }
@@ -100,7 +99,7 @@ class SuperuserViewModel(
//---
fun updatePolicy(policy: MagiskPolicy, isLogging: Boolean) = viewModelScope.launch {
fun updatePolicy(policy: SuPolicy, isLogging: Boolean) = viewModelScope.launch {
db.update(policy)
val str = when {
isLogging -> when {
@@ -115,16 +114,16 @@ class SuperuserViewModel(
SnackbarEvent(resources.getString(str, policy.appName)).publish()
}
fun togglePolicy(item: PolicyItem, enable: Boolean) {
fun togglePolicy(item: PolicyRvItem, enable: Boolean) {
fun updateState() {
item.policyState = enable
val policy = if (enable) MagiskPolicy.ALLOW else MagiskPolicy.DENY
val policy = if (enable) SuPolicy.ALLOW else SuPolicy.DENY
val app = item.item.copy(policy = policy)
viewModelScope.launch {
db.update(app)
val res = if (app.policy == MagiskPolicy.ALLOW) R.string.su_snack_grant
val res = if (app.policy == SuPolicy.ALLOW) R.string.su_snack_grant
else R.string.su_snack_deny
SnackbarEvent(resources.getString(res).format(item.item.appName)).publish()
}
@@ -13,12 +13,12 @@ import com.topjohnwu.magisk.R
import com.topjohnwu.magisk.arch.BaseViewModel
import com.topjohnwu.magisk.core.Config
import com.topjohnwu.magisk.core.magiskdb.PolicyDao
import com.topjohnwu.magisk.core.model.MagiskPolicy.Companion.ALLOW
import com.topjohnwu.magisk.core.model.MagiskPolicy.Companion.DENY
import com.topjohnwu.magisk.core.model.su.SuPolicy.Companion.ALLOW
import com.topjohnwu.magisk.core.model.su.SuPolicy.Companion.DENY
import com.topjohnwu.magisk.core.su.SuRequestHandler
import com.topjohnwu.magisk.core.utils.BiometricHelper
import com.topjohnwu.magisk.model.entity.recycler.SpinnerRvItem
import com.topjohnwu.magisk.model.events.DieEvent
import com.topjohnwu.magisk.events.DieEvent
import com.topjohnwu.magisk.ui.superuser.SpinnerRvItem
import com.topjohnwu.magisk.utils.set
import com.topjohnwu.superuser.internal.UiThreadHandler
import kotlinx.coroutines.launch
@@ -1,9 +1,9 @@
package com.topjohnwu.magisk.ui.theme
import com.topjohnwu.magisk.arch.BaseViewModel
import com.topjohnwu.magisk.model.entity.recycler.TappableHeadlineItem
import com.topjohnwu.magisk.model.events.RecreateEvent
import com.topjohnwu.magisk.model.events.dialog.DarkThemeDialog
import com.topjohnwu.magisk.events.RecreateEvent
import com.topjohnwu.magisk.events.dialog.DarkThemeDialog
import com.topjohnwu.magisk.view.TappableHeadlineItem
class ThemeViewModel : BaseViewModel(), TappableHeadlineItem.Listener {