mirror of
https://github.com/kalarina-bit/Sparkledns.git
synced 2026-11-22 15:46:09 +00:00
Keep storage and image decoding off the main thread at start-up
This commit is contained in:
@@ -40,6 +40,7 @@ import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
@@ -126,7 +127,7 @@ private fun AboutContent(modifier: Modifier, onOpenLicenses: () -> Unit) {
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
Image(
|
||||
painterResource(R.drawable.app_logo),
|
||||
remember { AppLogo.get(context) },
|
||||
contentDescription = null,
|
||||
modifier = Modifier
|
||||
.size(104.dp)
|
||||
|
||||
@@ -72,7 +72,10 @@ object Blocklist {
|
||||
|
||||
fun isBlocked(name: String): Boolean = _enabled.value && isBlockedIn(name, listHashes, customHashes)
|
||||
|
||||
fun reload(context: Context) = synchronized(lock) { load(BlocklistStore(context)) }
|
||||
// Reads the saved lists unless something did already, such as the background update job
|
||||
fun ensureLoaded(context: Context) {
|
||||
synchronized(lock) { ensureLoaded(BlocklistStore(context)) }
|
||||
}
|
||||
|
||||
fun setEnabled(context: Context, value: Boolean) {
|
||||
BlocklistStore(context).enabled = value
|
||||
@@ -329,8 +332,12 @@ private fun LongArray.sortUnique(): LongArray {
|
||||
}
|
||||
|
||||
private class BlocklistStore(context: Context) {
|
||||
private val dir = File(context.filesDir, "blocklist").apply { mkdirs() }
|
||||
private val sp = context.getSharedPreferences("blocklist", Context.MODE_PRIVATE)
|
||||
private val appContext = context.applicationContext
|
||||
|
||||
// Created on first use: switching blocking on or off, which happens on the main thread,
|
||||
// touches only the settings
|
||||
private val dir by lazy { File(appContext.filesDir, "blocklist").apply { mkdirs() } }
|
||||
private val sp = appContext.getSharedPreferences("blocklist", Context.MODE_PRIVATE)
|
||||
|
||||
var enabled: Boolean
|
||||
get() = sp.getBoolean("enabled", true)
|
||||
|
||||
@@ -5,6 +5,8 @@ import android.content.Context
|
||||
import android.os.Build
|
||||
import android.os.Process
|
||||
import android.os.StrictMode
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import java.io.File
|
||||
import java.io.PrintWriter
|
||||
import java.io.StringWriter
|
||||
@@ -17,22 +19,25 @@ class SparkleApp : Application() {
|
||||
Thread({
|
||||
// Reads what the first screen needs before it asks, so its first frame does not wait on storage
|
||||
Prefs(this).providerId
|
||||
CrashLog.preload(this)
|
||||
CrashLog.load(this)
|
||||
StatsStore.init(this)
|
||||
// Older versions cached a server list downloaded from the repository
|
||||
File(filesDir, "servers.txt").delete()
|
||||
AutoUpdate.apply(this)
|
||||
// Lists can hold millions of entries; loading them should not take CPU from the first frames
|
||||
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND)
|
||||
runCatching { Blocklist.reload(this) }
|
||||
runCatching { Blocklist.ensureLoaded(this) }
|
||||
}, "startup-load").start()
|
||||
}
|
||||
|
||||
// The VPN keeps the process running long after the screens are gone; decoded app icons
|
||||
// (up to 10 MB) can be rendered again the next time the Apps tab opens
|
||||
// (up to 10 MB) and the logo can be rendered again the next time they are shown
|
||||
override fun onTrimMemory(level: Int) {
|
||||
super.onTrimMemory(level)
|
||||
if (level >= TRIM_MEMORY_UI_HIDDEN) clearAppIconCache()
|
||||
if (level >= TRIM_MEMORY_UI_HIDDEN) {
|
||||
clearAppIconCache()
|
||||
AppLogo.clear()
|
||||
}
|
||||
}
|
||||
|
||||
// Debug builds only: logs disk and network access on the main thread, leaked closeables and the like
|
||||
@@ -46,13 +51,18 @@ class SparkleApp : Application() {
|
||||
object CrashLog {
|
||||
private const val FILE_NAME = "last_crash.txt"
|
||||
|
||||
// Null when there is no report, and until the startup thread has read it
|
||||
private val _report = MutableStateFlow<String?>(null)
|
||||
val report: StateFlow<String?> = _report
|
||||
|
||||
fun install(context: Context) {
|
||||
val file = File(context.filesDir, FILE_NAME)
|
||||
val appContext = context.applicationContext
|
||||
val previous = Thread.getDefaultUncaughtExceptionHandler()
|
||||
Thread.setDefaultUncaughtExceptionHandler { thread, error ->
|
||||
runCatching {
|
||||
val trace = StringWriter().also { error.printStackTrace(PrintWriter(it)) }.toString()
|
||||
file.writeText(
|
||||
// Looked up only now: install() runs on the main thread at start-up
|
||||
File(appContext.filesDir, FILE_NAME).writeText(
|
||||
"Thread: ${thread.name}\n" +
|
||||
"Android ${Build.VERSION.RELEASE} (API ${Build.VERSION.SDK_INT}), " +
|
||||
"${Build.MANUFACTURER} ${Build.MODEL}\n\n$trace"
|
||||
@@ -62,24 +72,14 @@ object CrashLog {
|
||||
}
|
||||
}
|
||||
|
||||
@Volatile
|
||||
private var preloaded = false
|
||||
|
||||
@Volatile
|
||||
private var report: String? = null
|
||||
|
||||
fun preload(context: Context) {
|
||||
report = load(context)
|
||||
preloaded = true
|
||||
// Runs on the startup thread, so the main thread never reads the file
|
||||
fun load(context: Context) {
|
||||
_report.value = runCatching { File(context.filesDir, FILE_NAME).takeIf { it.exists() }?.readText() }.getOrNull()
|
||||
}
|
||||
|
||||
fun read(context: Context): String? = if (preloaded) report else load(context)
|
||||
|
||||
fun clear(context: Context) {
|
||||
report = null
|
||||
File(context.filesDir, FILE_NAME).delete()
|
||||
_report.value = null
|
||||
val appContext = context.applicationContext
|
||||
Thread({ File(appContext.filesDir, FILE_NAME).delete() }, "crash-clear").start()
|
||||
}
|
||||
|
||||
private fun load(context: Context): String? =
|
||||
runCatching { File(context.filesDir, FILE_NAME).takeIf { it.exists() }?.readText() }.getOrNull()
|
||||
}
|
||||
|
||||
@@ -131,8 +131,8 @@ fun HomeScreen(
|
||||
val shown = active ?: selected
|
||||
val usesHttp3 = shown.http3 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE
|
||||
|
||||
val crashReport = remember { CrashLog.read(context) }
|
||||
var crashVisible by remember { mutableStateOf(crashReport != null) }
|
||||
val crashReport by CrashLog.report.collectAsStateWithLifecycle()
|
||||
val shownReport = rememberLast(crashReport).orEmpty() // kept while the card animates out
|
||||
// Strict Private DNS makes Android ignore the VPN's DNS server; followed while Home is visible
|
||||
val privateDnsHost by remember { privateDnsHosts(context) }.collectAsStateWithLifecycle(initialValue = null)
|
||||
|
||||
@@ -262,22 +262,21 @@ fun HomeScreen(
|
||||
verticalArrangement = Arrangement.spacedBy(20.dp),
|
||||
) {
|
||||
Image(
|
||||
painterResource(R.drawable.app_logo),
|
||||
remember { AppLogo.get(context) },
|
||||
contentDescription = null,
|
||||
modifier = Modifier
|
||||
.size(44.dp)
|
||||
.align(Alignment.CenterHorizontally),
|
||||
)
|
||||
|
||||
AnimatedVisibility(visible = crashVisible, enter = Motion.expandIn, exit = Motion.collapseOut) {
|
||||
val report = crashReport.orEmpty()
|
||||
AnimatedVisibility(visible = crashReport != null, enter = Motion.expandIn, exit = Motion.collapseOut) {
|
||||
CrashCard(
|
||||
report = report,
|
||||
report = shownReport,
|
||||
onCopy = {
|
||||
context.getSystemService(ClipboardManager::class.java)
|
||||
.setPrimaryClip(ClipData.newPlainText("SparkleDNS crash", report))
|
||||
.setPrimaryClip(ClipData.newPlainText("SparkleDNS crash", shownReport))
|
||||
},
|
||||
onDismiss = { CrashLog.clear(context); crashVisible = false },
|
||||
onDismiss = { CrashLog.clear(context) },
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -51,6 +51,7 @@ import kotlinx.coroutines.flow.flowOf
|
||||
class MainActivity : ComponentActivity() {
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
AppLogo.preload(this)
|
||||
enableEdgeToEdge()
|
||||
setContent {
|
||||
MaterialTheme(colorScheme = AppColors) { AppShell() }
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package cc.skysparkle.sparkledns
|
||||
|
||||
import android.content.Context
|
||||
import androidx.annotation.DrawableRes
|
||||
import androidx.annotation.StringRes
|
||||
import androidx.compose.foundation.background
|
||||
@@ -32,6 +33,8 @@ import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.ImageBitmap
|
||||
import androidx.compose.ui.res.imageResource
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
@@ -48,6 +51,28 @@ import java.util.Locale
|
||||
val CachedColor = Color(0xFF7FD1AE)
|
||||
val WarningColor = Color(0xFFFFB86B)
|
||||
|
||||
// The 512 px logo, decoded once while the screens are in use. Home shows it each time the tab
|
||||
// opens, and decoding it there would cost the main thread a frame.
|
||||
object AppLogo {
|
||||
@Volatile
|
||||
private var bitmap: ImageBitmap? = null
|
||||
|
||||
// Started with the activity, so the first frame of Home usually finds the logo decoded
|
||||
fun preload(context: Context) {
|
||||
if (bitmap != null) return
|
||||
val appContext = context.applicationContext
|
||||
Thread({ runCatching { get(appContext) } }, "logo-load").start()
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun get(context: Context): ImageBitmap =
|
||||
bitmap ?: ImageBitmap.imageResource(context.resources, R.drawable.app_logo).also { bitmap = it }
|
||||
|
||||
fun clear() {
|
||||
bitmap = null
|
||||
}
|
||||
}
|
||||
|
||||
// Icon on a soft circle of its own color
|
||||
@Composable
|
||||
fun IconBadge(@DrawableRes icon: Int, tint: Color = MaterialTheme.colorScheme.primary, size: Dp = 40.dp) {
|
||||
|
||||
Reference in New Issue
Block a user