forked from starifly/NekoBoxForAndroid
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAppManagerActivity.kt
More file actions
422 lines (371 loc) · 16.3 KB
/
Copy pathAppManagerActivity.kt
File metadata and controls
422 lines (371 loc) · 16.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
package io.nekohasekai.sagernet.ui
import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.text.TextUtils
import android.util.SparseBooleanArray
import android.view.KeyEvent
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import androidx.annotation.UiThread
import androidx.core.util.contains
import androidx.core.util.set
import androidx.core.view.ViewCompat
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.snackbar.Snackbar
import me.zhanghai.android.fastscroll.FastScrollerBuilder
import me.zhanghai.android.fastscroll.PopupTextProvider
import io.nekohasekai.sagernet.BuildConfig
import io.nekohasekai.sagernet.R
import io.nekohasekai.sagernet.SagerNet
import io.nekohasekai.sagernet.database.DataStore
import io.nekohasekai.sagernet.databinding.LayoutAppsBinding
import io.nekohasekai.sagernet.databinding.LayoutAppsItemBinding
import io.nekohasekai.sagernet.ktx.Logs
import io.nekohasekai.sagernet.ktx.app
import io.nekohasekai.sagernet.ktx.crossFadeFrom
import io.nekohasekai.sagernet.ktx.onMainDispatcher
import io.nekohasekai.sagernet.ktx.runOnDefaultDispatcher
import io.nekohasekai.sagernet.utils.PackageCache
import io.nekohasekai.sagernet.widget.ListListener
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import moe.matsuri.nb4a.utils.NGUtil
import kotlin.coroutines.coroutineContext
class AppManagerActivity : ThemedActivity() {
companion object {
@SuppressLint("StaticFieldLeak")
private var instance: AppManagerActivity? = null
private const val SWITCH = "switch"
private val cachedApps
get() = PackageCache.installedPackages.toMutableMap().apply {
remove(BuildConfig.APPLICATION_ID)
}
}
private class ProxiedApp(
private val pm: PackageManager, private val appInfo: ApplicationInfo,
val packageName: String,
) {
val name: CharSequence = appInfo.loadLabel(pm) // cached for sorting
val icon: Drawable get() = appInfo.loadIcon(pm)
val uid get() = appInfo.uid
val sys get() = (appInfo.flags and ApplicationInfo.FLAG_SYSTEM) != 0
}
private inner class AppViewHolder(val binding: LayoutAppsItemBinding) : RecyclerView.ViewHolder(
binding.root
),
View.OnClickListener {
private lateinit var item: ProxiedApp
init {
binding.root.setOnClickListener(this)
}
fun bind(app: ProxiedApp) {
item = app
binding.itemicon.setImageDrawable(app.icon)
binding.title.text = app.name
binding.desc.text = "${app.packageName} (${app.uid})"
binding.itemcheck.isChecked = isProxiedApp(app)
}
fun handlePayload(payloads: List<String>) {
if (payloads.contains(SWITCH)) binding.itemcheck.isChecked = isProxiedApp(item)
}
override fun onClick(v: View?) {
if (isProxiedApp(item)) proxiedUids.delete(item.uid) else proxiedUids[item.uid] = true
DataStore.individual = apps.filter { isProxiedApp(it) }
.joinToString("\n") { it.packageName }
appsAdapter.notifyItemRangeChanged(0, appsAdapter.itemCount, SWITCH)
}
}
private inner class AppsAdapter : RecyclerView.Adapter<AppViewHolder>(),
PopupTextProvider {
var filteredApps = apps
suspend fun reload() {
PackageCache.reload()
apps = cachedApps.mapNotNull { (packageName, packageInfo) ->
coroutineContext[Job]!!.ensureActive()
packageInfo.applicationInfo?.let { ProxiedApp(packageManager, it, packageName) }
}.sortedWith(compareBy({ !isProxiedApp(it) }, { it.name.toString() }))
}
override fun onBindViewHolder(holder: AppViewHolder, position: Int) =
holder.bind(filteredApps[position])
override fun onBindViewHolder(holder: AppViewHolder, position: Int, payloads: List<Any>) {
if (payloads.isNotEmpty()) {
@Suppress("UNCHECKED_CAST") holder.handlePayload(payloads as List<String>)
return
}
onBindViewHolder(holder, position)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AppViewHolder =
AppViewHolder(LayoutAppsItemBinding.inflate(layoutInflater, parent, false))
override fun getItemCount(): Int = filteredApps.size
// Replaces android.widget.Filter, which spawned a new worker thread per
// filter() call (OutOfMemoryError: pthread_create failed, issue #1086).
// Computes the filtered list off the main thread and publishes on main;
// callers cancel the previous job via applyFilter() below.
fun computeFiltered(constraint: CharSequence): List<ProxiedApp> {
var result = if (constraint.isEmpty()) apps else apps.filter {
it.name.contains(constraint, true) || it.packageName.contains(
constraint, true
) || it.uid.toString().contains(constraint)
}
if (!sysApps) result = result.filter { !it.sys }
return result
}
fun publishFiltered(result: List<ProxiedApp>) {
filteredApps = result
@Suppress("NotifyDataSetChanged")
notifyDataSetChanged()
}
override fun getPopupText(view: View, position: Int): CharSequence {
return filteredApps[position].name.firstOrNull()?.toString() ?: ""
}
}
private val loading by lazy { binding.loading }
private lateinit var binding: LayoutAppsBinding
private val proxiedUids = SparseBooleanArray()
private var loader: Job? = null
private var filterJob: Job? = null
// Read on Dispatchers.Default in computeFiltered(); written from Default/IO/Main.
// @Volatile guarantees cross-thread visibility so filtering never sees a stale list.
@Volatile
private var apps = emptyList<ProxiedApp>()
private val appsAdapter = AppsAdapter()
// Coroutine-based replacement for the old Filter.filter(...) calls. Cancels the
// in-flight filter job (so rapid keystrokes don't pile up work) and computes the
// filtered list on a background dispatcher before publishing on main.
// debounceMs > 0 is used for the search box to avoid filtering on every keystroke.
@UiThread
private fun applyFilter(constraint: String = binding.search.text?.toString() ?: "", debounceMs: Long = 0) {
filterJob?.cancel()
filterJob = lifecycleScope.launch {
if (debounceMs > 0) delay(debounceMs)
val result = withContext(Dispatchers.Default) { appsAdapter.computeFiltered(constraint) }
appsAdapter.publishFiltered(result)
}
}
private fun initProxiedUids(str: String = DataStore.individual) {
proxiedUids.clear()
val apps = cachedApps
for (line in str.lineSequence()) {
val app = (apps[line] ?: continue)
val uid = app.applicationInfo?.uid ?: continue
proxiedUids[uid] = true
}
}
private fun isProxiedApp(app: ProxiedApp) = proxiedUids[app.uid]
@UiThread
private fun loadApps() {
loader?.cancel()
loader = lifecycleScope.launchWhenCreated {
loading.crossFadeFrom(binding.list)
val adapter = binding.list.adapter as AppsAdapter
withContext(Dispatchers.IO) { adapter.reload() }
applyFilter()
if (apps.isEmpty()) {
binding.list.visibility = View.GONE
binding.appPlaceholder.root.crossFadeFrom(loading)
} else {
binding.list.crossFadeFrom(loading)
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = LayoutAppsBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.appPlaceholder.openSettings.setOnClickListener {
val intent =
Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
data = android.net.Uri.fromParts("package", packageName, null)
}
startActivity(intent)
}
setSupportActionBar(binding.toolbar)
supportActionBar?.apply {
setTitle(R.string.proxied_apps)
setDisplayHomeAsUpEnabled(true)
setHomeAsUpIndicator(R.drawable.ic_navigation_close)
}
if (!DataStore.proxyApps) {
DataStore.proxyApps = true
}
binding.bypassGroup.check(if (DataStore.bypass) R.id.appProxyModeBypass else R.id.appProxyModeOn)
binding.bypassGroup.setOnCheckedChangeListener { _, checkedId ->
when (checkedId) {
R.id.appProxyModeDisable -> {
DataStore.proxyApps = false
finish()
}
R.id.appProxyModeOn -> DataStore.bypass = false
R.id.appProxyModeBypass -> DataStore.bypass = true
}
}
binding.autoSelectProxyApps.setOnClickListener { selectProxyApp() }
initProxiedUids()
binding.list.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
binding.list.itemAnimator = DefaultItemAnimator()
binding.list.adapter = appsAdapter
FastScrollerBuilder(binding.list).useMd2Style().build()
ViewCompat.setOnApplyWindowInsetsListener(binding.root, ListListener)
binding.search.addTextChangedListener {
applyFilter(it?.toString() ?: "", debounceMs = 250)
}
binding.showSystemApps.isChecked = sysApps
binding.showSystemApps.setOnCheckedChangeListener { _, isChecked ->
sysApps = isChecked
applyFilter()
}
instance = this
loadApps()
}
@Volatile
private var sysApps = true
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.per_app_proxy_menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_invert_selections -> {
runOnDefaultDispatcher {
val proxiedUidsOld = proxiedUids.clone()
for (app in apps) {
if (proxiedUidsOld.contains(app.uid)) {
proxiedUids.delete(app.uid)
} else {
proxiedUids[app.uid] = true
}
}
DataStore.individual = apps.filter { isProxiedApp(it) }
.joinToString("\n") { it.packageName }
apps = apps.sortedWith(compareBy({ !isProxiedApp(it) }, { it.name.toString() }))
onMainDispatcher {
applyFilter()
}
}
return true
}
R.id.action_clear_selections -> {
runOnDefaultDispatcher {
proxiedUids.clear()
DataStore.individual = ""
apps = apps.sortedWith(compareBy({ !isProxiedApp(it) }, { it.name.toString() }))
onMainDispatcher {
applyFilter()
}
}
}
R.id.action_export_clipboard -> {
val success =
SagerNet.trySetPrimaryClip("${DataStore.bypass}\n${DataStore.individual}")
Snackbar.make(
binding.list,
if (success) R.string.action_export_msg else R.string.action_export_err,
Snackbar.LENGTH_LONG
).show()
return true
}
R.id.action_import_clipboard -> {
val proxiedAppString =
SagerNet.clipboard.primaryClip?.getItemAt(0)?.text?.toString()
if (!proxiedAppString.isNullOrEmpty()) {
val i = proxiedAppString.indexOf('\n')
try {
val (enabled, apps) = if (i < 0) {
proxiedAppString to ""
} else proxiedAppString.substring(
0, i
) to proxiedAppString.substring(i + 1)
binding.bypassGroup.check(if (enabled.toBoolean()) R.id.appProxyModeBypass else R.id.appProxyModeOn)
DataStore.individual = apps
Snackbar.make(
binding.list, R.string.action_import_msg, Snackbar.LENGTH_LONG
).show()
initProxiedUids(apps)
appsAdapter.notifyItemRangeChanged(0, appsAdapter.itemCount, SWITCH)
return true
} catch (_: IllegalArgumentException) {
}
}
Snackbar.make(binding.list, R.string.action_import_err, Snackbar.LENGTH_LONG).show()
}
}
return super.onOptionsItemSelected(item)
}
private fun selectProxyApp() {
MaterialAlertDialogBuilder(this).setTitle(R.string.confirm)
.setMessage(R.string.auto_select_proxy_apps_message)
.setPositiveButton(R.string.yes) { _, _ ->
try {
val needProxyAppsList = getAutoProxyApps("")
val bypass = DataStore.bypass
proxiedUids.clear()
for (app in cachedApps) {
val needProxy =
needProxyAppsList.contains(app.key) || (app.value.applicationInfo?.uid
?: 0) == 1000
if (needProxy) {
if (!bypass) {
app.value.applicationInfo?.apply {
proxiedUids[uid] = true
}
}
} else {
if (bypass) {
app.value.applicationInfo?.apply {
proxiedUids[uid] = true
}
}
}
}
DataStore.individual =
apps.filter { isProxiedApp(it) }.joinToString("\n") { it.packageName }
apps = apps.sortedWith(compareBy({ !isProxiedApp(it) }, { it.name.toString() }))
applyFilter()
} catch (e: Exception) {
Logs.e(e)
}
}
.setNegativeButton(R.string.no, null)
.show()
}
private fun getAutoProxyApps(content: String): List<String> {
var list = listOf<String>()
try {
val proxyApps = if (TextUtils.isEmpty(content)) {
NGUtil.readTextFromAssets(app, "proxy_packagename.txt")
} else {
content
}
if (!TextUtils.isEmpty(proxyApps)) {
list = proxyApps.split("\n")
}
} catch (_: Exception) {
}
return list
}
override fun supportNavigateUpTo(upIntent: Intent) =
super.supportNavigateUpTo(upIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
override fun onKeyUp(keyCode: Int, event: KeyEvent?) = if (keyCode == KeyEvent.KEYCODE_MENU) {
if (binding.toolbar.isOverflowMenuShowing) binding.toolbar.hideOverflowMenu() else binding.toolbar.showOverflowMenu()
} else super.onKeyUp(keyCode, event)
override fun onDestroy() {
instance = null
loader?.cancel()
super.onDestroy()
}
}