mirror of
https://github.com/kalarina-bit/Sparkledns.git
synced 2026-11-22 07:36:09 +00:00
Release v1.1.2
This commit is contained in:
@@ -25,11 +25,12 @@ import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.offset
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
@@ -39,6 +40,8 @@ import androidx.compose.foundation.selection.toggleable
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
@@ -47,63 +50,96 @@ import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.draw.drawBehind
|
||||
import androidx.compose.ui.draw.drawWithCache
|
||||
import androidx.compose.ui.geometry.CornerRadius
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.geometry.Size
|
||||
import androidx.compose.ui.graphics.Brush
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.Path
|
||||
import androidx.compose.ui.graphics.PathEffect
|
||||
import androidx.compose.ui.graphics.StrokeCap
|
||||
import androidx.compose.ui.graphics.StrokeJoin
|
||||
import androidx.compose.ui.graphics.drawscope.Stroke
|
||||
import androidx.compose.ui.graphics.graphicsLayer
|
||||
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalHapticFeedback
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.text.TextLayoutResult
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.drawText
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.rememberTextMeasurer
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.Constraints
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.IntOffset
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import kotlinx.coroutines.delay
|
||||
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Calendar
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
import java.util.TimeZone
|
||||
import kotlin.math.ceil
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
private const val CHART_HOURS = 24
|
||||
private const val HOUR_MS = 3_600_000L
|
||||
|
||||
// One bar of the chart: an hour, or a day in the 7-day view
|
||||
private data class Bar(val total: Long, val blocked: Long)
|
||||
|
||||
// Bars with the labels under them: the first hour of the day view, or every day of the week.
|
||||
// A refresh that brings equal data leaves the chart alone.
|
||||
private data class Chart(val period: StatsPeriod, val bars: List<Bar>, val labels: List<String>)
|
||||
|
||||
private val ChartLabelStyle = TextStyle(color = Palette.Fg3, fontSize = 10.sp)
|
||||
|
||||
// Where the three grip lines on the knob of the power switch sit, as fractions of its width
|
||||
private val KnobLines = floatArrayOf(0.29f, 0.5f, 0.71f)
|
||||
|
||||
@Composable
|
||||
fun HomeScreen(bottomPadding: Dp, onOpenBlocklist: () -> Unit, modifier: Modifier = Modifier) {
|
||||
fun HomeScreen(
|
||||
bottomPadding: Dp,
|
||||
onOpenBlocklist: () -> Unit,
|
||||
onOpenServers: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val prefs = remember { Prefs(context) }
|
||||
val haptics = LocalHapticFeedback.current
|
||||
val scope = rememberCoroutineScope()
|
||||
val active by DohVpnService.active.collectAsStateWithLifecycle()
|
||||
val running = active != null
|
||||
val lists by Blocklist.lists.collectAsStateWithLifecycle()
|
||||
val total by Blocklist.total.collectAsStateWithLifecycle()
|
||||
val blocking by Blocklist.enabled.collectAsStateWithLifecycle()
|
||||
val listsReady by Blocklist.ready.collectAsStateWithLifecycle()
|
||||
val download by Blocklist.busy.collectAsStateWithLifecycle()
|
||||
val downloadError by Blocklist.error.collectAsStateWithLifecycle()
|
||||
|
||||
var summary by remember { mutableStateOf(StatsStore.summary(CHART_HOURS)) }
|
||||
var points by remember { mutableStateOf(StatsStore.hourly(CHART_HOURS)) }
|
||||
var period by rememberSaveable { mutableStateOf(StatsPeriod.DAY) }
|
||||
var summary by remember { mutableStateOf(StatsStore.summary(period.hours)) }
|
||||
var chartData by remember { mutableStateOf(buildChart(period)) }
|
||||
fun refreshStats() {
|
||||
summary = StatsStore.summary(CHART_HOURS)
|
||||
points = StatsStore.hourly(CHART_HOURS)
|
||||
summary = StatsStore.summary(period.hours)
|
||||
chartData = buildChart(period)
|
||||
}
|
||||
OnQueryLogChange { refreshStats() }
|
||||
val statsVersion by StatsStore.version.collectAsStateWithLifecycle()
|
||||
LaunchedEffect(statsVersion) { refreshStats() }
|
||||
LaunchedEffect(statsVersion, period) { refreshStats() }
|
||||
|
||||
// The server is picked in Settings; this screen is composed anew each time it is shown
|
||||
val selected = remember { prefs.resolve() }
|
||||
@@ -111,21 +147,12 @@ fun HomeScreen(bottomPadding: Dp, onOpenBlocklist: () -> Unit, modifier: Modifie
|
||||
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)
|
||||
|
||||
// Set by a tap until the VPN state changes or the attempt gives up, so a double tap neither
|
||||
// starts two connections nor switches the VPN back on right after turning it off
|
||||
var busy by remember { mutableStateOf(false) }
|
||||
LaunchedEffect(active) { busy = false }
|
||||
LaunchedEffect(busy) {
|
||||
if (busy) {
|
||||
delay(BUSY_TIMEOUT_MS)
|
||||
busy = false
|
||||
}
|
||||
}
|
||||
var busy by rememberVpnBusy(active)
|
||||
|
||||
val vpnPermission = rememberLauncherForActivityResult(
|
||||
ActivityResultContracts.StartActivityForResult()
|
||||
@@ -148,6 +175,7 @@ fun HomeScreen(bottomPadding: Dp, onOpenBlocklist: () -> Unit, modifier: Modifie
|
||||
fun toggle() {
|
||||
if (busy) return
|
||||
busy = true
|
||||
haptics.performHapticFeedback(if (running) HapticFeedbackType.ToggleOff else HapticFeedbackType.ToggleOn)
|
||||
if (running) {
|
||||
sendAction(context, DohVpnService.ACTION_STOP)
|
||||
return
|
||||
@@ -158,65 +186,50 @@ fun HomeScreen(bottomPadding: Dp, onOpenBlocklist: () -> Unit, modifier: Modifie
|
||||
else connectVpn()
|
||||
}
|
||||
|
||||
val glow by animateFloatAsState(if (running) 1f else 0f, tween(600), label = "glow")
|
||||
|
||||
Column(
|
||||
modifier = modifier
|
||||
.verticalScroll(rememberScrollState())
|
||||
.drawBehind {
|
||||
// Soft light behind the logo while protected
|
||||
if (glow > 0f) {
|
||||
drawCircle(
|
||||
brush = Brush.radialGradient(
|
||||
colors = listOf(Palette.Accent.copy(alpha = 0.22f * glow), Color.Transparent),
|
||||
center = Offset(size.width / 2f, 0f),
|
||||
radius = size.width * 0.65f,
|
||||
),
|
||||
radius = size.width * 0.65f,
|
||||
center = Offset(size.width / 2f, 0f),
|
||||
)
|
||||
}
|
||||
}
|
||||
.padding(top = 16.dp, bottom = bottomPadding),
|
||||
verticalArrangement = Arrangement.spacedBy(20.dp),
|
||||
) {
|
||||
Image(
|
||||
painterResource(R.drawable.app_logo),
|
||||
contentDescription = null,
|
||||
modifier = Modifier
|
||||
.size(44.dp)
|
||||
.align(Alignment.CenterHorizontally),
|
||||
)
|
||||
|
||||
AnimatedVisibility(visible = crashVisible, enter = Motion.expandIn, exit = Motion.collapseOut) {
|
||||
val report = crashReport.orEmpty()
|
||||
Box(Modifier.padding(horizontal = 20.dp)) {
|
||||
CrashCard(
|
||||
report = report,
|
||||
onCopy = {
|
||||
context.getSystemService(ClipboardManager::class.java)
|
||||
.setPrimaryClip(ClipData.newPlainText("SparkleDNS crash", report))
|
||||
},
|
||||
onDismiss = { CrashLog.clear(context); crashVisible = false },
|
||||
)
|
||||
}
|
||||
// What the blocklist card offers: nothing, switching blocking back on, or a first list
|
||||
val proList = lists.firstOrNull { it.url == HAGEZI_PRO_URL }
|
||||
val offer = when {
|
||||
!listsReady -> BlocklistOffer.NONE
|
||||
!blocking -> BlocklistOffer.SWITCH_ON
|
||||
total == 0 && lists.none { it.enabled } -> BlocklistOffer.FIRST_LIST
|
||||
else -> BlocklistOffer.NONE
|
||||
}
|
||||
fun acceptOffer() {
|
||||
when (offer) {
|
||||
BlocklistOffer.SWITCH_ON -> Blocklist.setEnabled(context, true)
|
||||
BlocklistOffer.FIRST_LIST ->
|
||||
if (proList != null) scope.editBlocklist(context) { Blocklist.setListEnabled(context, HAGEZI_PRO_URL, true) }
|
||||
else Blocklist.download(context, HAGEZI_PRO_URL)
|
||||
BlocklistOffer.NONE -> Unit
|
||||
}
|
||||
}
|
||||
|
||||
val glow by animateFloatAsState(if (running) 1f else 0f, tween(600), label = "glow")
|
||||
val wide = windowWidth() >= WideLayoutWidth
|
||||
val side = sidePadding(windowWidth(), if (wide) MaxWideContentWidth else MaxContentWidth)
|
||||
// A tall screen gets a taller chart instead of empty space under the content
|
||||
val chartHeight = if (wide) {
|
||||
(windowHeight() - 420.dp).coerceIn(160.dp, 360.dp)
|
||||
} else {
|
||||
(windowHeight() - 700.dp).coerceIn(150.dp, 320.dp)
|
||||
}
|
||||
|
||||
val status: @Composable () -> Unit = {
|
||||
StatusCard(
|
||||
running = running,
|
||||
providerName = shown.displayName(context),
|
||||
http3 = usesHttp3,
|
||||
enabled = !busy && (running || canConnect),
|
||||
onToggle = ::toggle,
|
||||
modifier = Modifier.padding(horizontal = 20.dp),
|
||||
onOpenServers = onOpenServers,
|
||||
)
|
||||
|
||||
PrivateDnsWarning(privateDnsHost, prefs, Modifier.padding(horizontal = 20.dp))
|
||||
|
||||
PrivateDnsWarning(privateDnsHost, prefs)
|
||||
}
|
||||
val stats: @Composable () -> Unit = {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 24.dp),
|
||||
.padding(horizontal = 4.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
StatBlock(formatCompact(summary.total), stringResource(R.string.stat_requests), Modifier.weight(1f))
|
||||
@@ -228,63 +241,78 @@ fun HomeScreen(bottomPadding: Dp, onOpenBlocklist: () -> Unit, modifier: Modifie
|
||||
)
|
||||
StatBlock(stringResource(R.string.mon_ms, summary.avgLatencyMs), stringResource(R.string.stat_avg), Modifier.weight(1f))
|
||||
}
|
||||
}
|
||||
val chart: @Composable () -> Unit = {
|
||||
ChartSection(chartData, period, chartHeight, onPeriod = { period = it })
|
||||
}
|
||||
val blocklist: @Composable () -> Unit = {
|
||||
BlocklistCard(
|
||||
info = stringResource(R.string.home_lists_info, lists.count { it.enabled }, formatCount(total.toLong())),
|
||||
offer = offer,
|
||||
downloading = download == HAGEZI_PRO_URL,
|
||||
error = if (offer == BlocklistOffer.FIRST_LIST) downloadError else null,
|
||||
canAccept = download == null,
|
||||
onAccept = ::acceptOffer,
|
||||
onClick = onOpenBlocklist,
|
||||
)
|
||||
}
|
||||
|
||||
Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 20.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(14.dp, Alignment.End),
|
||||
) {
|
||||
LegendItem(stringResource(R.string.stat_requests), Palette.Accent)
|
||||
LegendItem(stringResource(R.string.mon_blocked), Palette.Muted)
|
||||
Column(
|
||||
modifier = modifier
|
||||
.verticalScroll(rememberScrollState())
|
||||
.drawWithCache {
|
||||
// Soft light behind the logo while protected. The gradient depends on the size only;
|
||||
// the fade is applied as alpha when drawing.
|
||||
val center = Offset(size.width / 2f, 0f)
|
||||
val radius = size.width * 0.65f
|
||||
val light = Brush.radialGradient(
|
||||
colors = listOf(Palette.Accent.copy(alpha = 0.22f), Color.Transparent),
|
||||
center = center,
|
||||
radius = radius,
|
||||
)
|
||||
onDrawBehind {
|
||||
if (glow > 0f) drawCircle(brush = light, radius = radius, center = center, alpha = glow)
|
||||
}
|
||||
}
|
||||
TrafficChart(
|
||||
points,
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.height(150.dp),
|
||||
.padding(start = side, end = side, top = 16.dp, bottom = bottomPadding),
|
||||
verticalArrangement = Arrangement.spacedBy(20.dp),
|
||||
) {
|
||||
Image(
|
||||
remember { AppLogo.get(context) },
|
||||
contentDescription = null,
|
||||
modifier = Modifier
|
||||
.size(44.dp)
|
||||
.align(Alignment.CenterHorizontally),
|
||||
)
|
||||
|
||||
AnimatedVisibility(visible = crashReport != null, enter = Motion.expandIn, exit = Motion.collapseOut) {
|
||||
CrashCard(
|
||||
report = shownReport,
|
||||
onCopy = {
|
||||
context.getSystemService(ClipboardManager::class.java)
|
||||
.setPrimaryClip(ClipData.newPlainText("SparkleDNS crash", shownReport))
|
||||
},
|
||||
onDismiss = { CrashLog.clear(context) },
|
||||
)
|
||||
val startLabel = remember(points) {
|
||||
val start = System.currentTimeMillis() - (CHART_HOURS - 1) * 3_600_000L
|
||||
SimpleDateFormat("HH:00", Locale.getDefault()).format(Date(start))
|
||||
}
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 20.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(startLabel, color = Palette.Fg3, fontSize = 11.sp, modifier = Modifier.weight(1f))
|
||||
Text(
|
||||
stringResource(R.string.period_24h),
|
||||
color = Palette.Fg2,
|
||||
fontSize = 12.sp,
|
||||
fontWeight = FontWeight.Bold,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(16.dp))
|
||||
.background(Palette.Card)
|
||||
.padding(horizontal = 12.dp, vertical = 6.dp),
|
||||
)
|
||||
Text(
|
||||
stringResource(R.string.chart_now),
|
||||
color = Palette.Fg3,
|
||||
fontSize = 11.sp,
|
||||
textAlign = TextAlign.End,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
BlocklistRow(
|
||||
info = if (blocking) {
|
||||
stringResource(R.string.home_lists_info, lists.count { it.enabled }, formatCount(total.toLong()))
|
||||
} else {
|
||||
stringResource(R.string.blocking_off)
|
||||
},
|
||||
onClick = onOpenBlocklist,
|
||||
modifier = Modifier.padding(horizontal = 20.dp),
|
||||
)
|
||||
if (wide) {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(24.dp)) {
|
||||
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(20.dp)) {
|
||||
status()
|
||||
blocklist()
|
||||
}
|
||||
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(20.dp)) {
|
||||
stats()
|
||||
chart()
|
||||
}
|
||||
}
|
||||
} else {
|
||||
status()
|
||||
stats()
|
||||
chart()
|
||||
blocklist()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -295,15 +323,15 @@ private fun StatusCard(
|
||||
http3: Boolean,
|
||||
enabled: Boolean,
|
||||
onToggle: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
onOpenServers: () -> Unit,
|
||||
) {
|
||||
Column(
|
||||
modifier = modifier
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.appCard()
|
||||
.padding(horizontal = 20.dp, vertical = 24.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(6.dp),
|
||||
) {
|
||||
AnimatedContent(
|
||||
targetState = running,
|
||||
@@ -319,13 +347,21 @@ private fun StatusCard(
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
}
|
||||
// Tapping the server opens the server list in Settings
|
||||
val dot by animateColorAsState(if (running) Palette.Accent else Palette.Track, Motion.color, label = "dot")
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.clickable(onClickLabel = stringResource(R.string.change_server), onClick = onOpenServers)
|
||||
.heightIn(min = 40.dp)
|
||||
.padding(start = 10.dp, end = 4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Box(
|
||||
Modifier
|
||||
.size(7.dp)
|
||||
.clip(CircleShape)
|
||||
.background(dot)
|
||||
.drawBehind { drawRect(dot) }
|
||||
)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
val via = stringResource(R.string.home_via, providerName) + if (http3) " · HTTP/3" else ""
|
||||
@@ -336,14 +372,18 @@ private fun StatusCard(
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
textAlign = TextAlign.Center,
|
||||
modifier = Modifier.weight(1f, fill = false),
|
||||
)
|
||||
Spacer(Modifier.width(2.dp))
|
||||
Chevron(Modifier.size(16.dp))
|
||||
}
|
||||
Spacer(Modifier.height(10.dp))
|
||||
Spacer(Modifier.height(8.dp))
|
||||
PowerToggle(on = running, enabled = enabled, onToggle = onToggle)
|
||||
}
|
||||
}
|
||||
|
||||
// The big ON / OFF switch; the white knob slides across
|
||||
// The big ON / OFF switch; the white knob slides across. The animated color and position are
|
||||
// read only when drawing and placing, so the animation does not recompose the switch every frame.
|
||||
@Composable
|
||||
private fun PowerToggle(on: Boolean, enabled: Boolean, onToggle: () -> Unit) {
|
||||
val track by animateColorAsState(if (on) Palette.Accent else Palette.Track, Motion.color, label = "track")
|
||||
@@ -354,7 +394,7 @@ private fun PowerToggle(on: Boolean, enabled: Boolean, onToggle: () -> Unit) {
|
||||
.size(width = 120.dp, height = 50.dp)
|
||||
.graphicsLayer { alpha = if (enabled) 1f else 0.5f }
|
||||
.clip(RoundedCornerShape(25.dp))
|
||||
.background(track)
|
||||
.drawBehind { drawRect(track) }
|
||||
.toggleable(value = on, enabled = enabled, role = Role.Switch, onValueChange = { onToggle() })
|
||||
.semantics { contentDescription = description }
|
||||
.padding(5.dp),
|
||||
@@ -371,7 +411,7 @@ private fun PowerToggle(on: Boolean, enabled: Boolean, onToggle: () -> Unit) {
|
||||
)
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.offset(x = knob)
|
||||
.offset { IntOffset(knob.roundToPx(), 0) }
|
||||
.size(40.dp)
|
||||
.clip(CircleShape)
|
||||
.background(Color.White),
|
||||
@@ -379,7 +419,7 @@ private fun PowerToggle(on: Boolean, enabled: Boolean, onToggle: () -> Unit) {
|
||||
) {
|
||||
Canvas(Modifier.size(14.dp)) {
|
||||
val stroke = 1.6.dp.toPx()
|
||||
listOf(0.29f, 0.5f, 0.71f).forEach { fraction ->
|
||||
KnobLines.forEach { fraction ->
|
||||
drawLine(
|
||||
color = Palette.Fg3,
|
||||
start = Offset(size.width * fraction, size.height * 0.21f),
|
||||
@@ -394,27 +434,25 @@ private fun PowerToggle(on: Boolean, enabled: Boolean, onToggle: () -> Unit) {
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PrivateDnsWarning(privateDnsHost: String?, prefs: Prefs, modifier: Modifier = Modifier) {
|
||||
private fun PrivateDnsWarning(privateDnsHost: String?, prefs: Prefs) {
|
||||
val context = LocalContext.current
|
||||
val lastHost = remember { arrayOf("") }
|
||||
privateDnsHost?.let { lastHost[0] = it }
|
||||
val shownHost = rememberLast(privateDnsHost).orEmpty()
|
||||
var dismissedHost by remember { mutableStateOf(prefs.dismissedPrivateDns) }
|
||||
AnimatedVisibility(
|
||||
visible = privateDnsHost != null && privateDnsHost != dismissedHost,
|
||||
enter = Motion.expandIn,
|
||||
exit = Motion.collapseOut,
|
||||
modifier = modifier,
|
||||
) {
|
||||
HintCard(
|
||||
text = stringResource(R.string.hint, lastHost[0]),
|
||||
text = stringResource(R.string.hint, shownHost),
|
||||
icon = R.drawable.ic_alert,
|
||||
tint = WarningColor,
|
||||
action = {
|
||||
TextButton(onClick = { openNetworkSettings(context) }) { Text(stringResource(R.string.open_settings)) }
|
||||
},
|
||||
onDismiss = {
|
||||
dismissedHost = lastHost[0]
|
||||
prefs.dismissedPrivateDns = lastHost[0]
|
||||
dismissedHost = shownHost
|
||||
prefs.dismissedPrivateDns = shownHost
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -428,12 +466,62 @@ fun StatBlock(value: String, label: String, modifier: Modifier = Modifier, value
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ChartSection(chart: Chart, period: StatsPeriod, height: Dp, onPeriod: (StatsPeriod) -> Unit) {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
PeriodChip(period, onPeriod)
|
||||
Spacer(Modifier.weight(1f))
|
||||
LegendItem(stringResource(R.string.stat_requests), Palette.Accent)
|
||||
Spacer(Modifier.width(14.dp))
|
||||
LegendItem(stringResource(R.string.mon_blocked), Palette.Blocked)
|
||||
}
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.height(height),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
if (chart.bars.all { it.total == 0L }) {
|
||||
Text(
|
||||
stringResource(R.string.chart_empty),
|
||||
color = Palette.Fg3,
|
||||
fontSize = 13.sp,
|
||||
lineHeight = 18.sp,
|
||||
textAlign = TextAlign.Center,
|
||||
modifier = Modifier.padding(horizontal = 24.dp),
|
||||
)
|
||||
} else {
|
||||
TrafficChart(chart.bars, Modifier.fillMaxWidth().height(height))
|
||||
}
|
||||
}
|
||||
// Hours: first hour on the left, now on the right. Days: a label under every bar.
|
||||
Row(Modifier.fillMaxWidth()) {
|
||||
if (chart.period == StatsPeriod.DAY) {
|
||||
Text(chart.labels.firstOrNull().orEmpty(), color = Palette.Fg3, fontSize = 11.sp, modifier = Modifier.weight(1f))
|
||||
Text(stringResource(R.string.chart_now), color = Palette.Fg3, fontSize = 11.sp)
|
||||
} else {
|
||||
chart.labels.forEachIndexed { index, label ->
|
||||
Text(
|
||||
label,
|
||||
color = if (index == chart.labels.lastIndex) Palette.Fg else Palette.Fg3,
|
||||
fontSize = 11.sp,
|
||||
maxLines = 1,
|
||||
textAlign = TextAlign.Center,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun LegendItem(label: String, color: Color) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Box(
|
||||
Modifier
|
||||
.size(width = 12.dp, height = 3.dp)
|
||||
.size(8.dp)
|
||||
.clip(RoundedCornerShape(2.dp))
|
||||
.background(color)
|
||||
)
|
||||
@@ -442,76 +530,89 @@ private fun LegendItem(label: String, color: Color) {
|
||||
}
|
||||
}
|
||||
|
||||
// Requests (accent line with a soft fill) and blocked queries (grey line) per hour
|
||||
// One bar per hour or day: requests in the accent color with the blocked part at the bottom.
|
||||
// Empty slots show a short stub, so a mostly empty day reads as empty instead of broken.
|
||||
@Composable
|
||||
private fun TrafficChart(points: List<HourPoint>, modifier: Modifier = Modifier) {
|
||||
private fun TrafficChart(bars: List<Bar>, modifier: Modifier = Modifier) {
|
||||
val measurer = rememberTextMeasurer()
|
||||
val labelStyle = TextStyle(color = Palette.Fg3, fontSize = 10.sp)
|
||||
Canvas(modifier) {
|
||||
val n = points.size
|
||||
if (n < 2) return@Canvas
|
||||
val maxValue = niceCeiling(points.maxOf { it.total }.coerceAtLeast(1L))
|
||||
val inset = 6.dp.toPx()
|
||||
val top = 14.dp.toPx()
|
||||
val base = size.height - 8.dp.toPx()
|
||||
val span = base - top
|
||||
val step = (size.width - 2 * inset) / (n - 1)
|
||||
fun x(index: Int) = inset + index * step
|
||||
fun y(value: Long) = base - value.toFloat() / maxValue * span
|
||||
// Scale, grid and grid labels are worked out when the bars or the size change, not every frame
|
||||
Spacer(
|
||||
modifier.drawWithCache {
|
||||
val n = bars.size
|
||||
if (n == 0) return@drawWithCache onDrawBehind {}
|
||||
val maxValue = niceCeiling(bars.maxOf { it.total }.coerceAtLeast(1L))
|
||||
val top = 16.dp.toPx()
|
||||
val base = size.height - 2.dp.toPx()
|
||||
val span = base - top
|
||||
val slot = size.width / n
|
||||
val barWidth = (slot * if (n > 10) 0.62f else 0.5f).coerceAtLeast(2.dp.toPx())
|
||||
val radius = CornerRadius((barWidth / 2).coerceAtMost(4.dp.toPx()))
|
||||
val stub = 2.dp.toPx()
|
||||
val minBar = 4.dp.toPx()
|
||||
val minBlocked = 2.dp.toPx()
|
||||
val gridWidth = 1.dp.toPx()
|
||||
val dash = PathEffect.dashPathEffect(floatArrayOf(3.dp.toPx(), 4.dp.toPx()))
|
||||
fun height(value: Long) = value.toFloat() / maxValue * span
|
||||
|
||||
listOf(maxValue / 2, maxValue).forEach { value ->
|
||||
val gridY = y(value)
|
||||
drawLine(
|
||||
color = Palette.Line,
|
||||
start = Offset(0f, gridY),
|
||||
end = Offset(size.width, gridY),
|
||||
strokeWidth = 1.dp.toPx(),
|
||||
pathEffect = PathEffect.dashPathEffect(floatArrayOf(3.dp.toPx(), 4.dp.toPx())),
|
||||
)
|
||||
drawText(
|
||||
textMeasurer = measurer,
|
||||
text = formatCompact(value),
|
||||
topLeft = Offset(20.dp.toPx(), gridY - 15.dp.toPx()),
|
||||
style = labelStyle,
|
||||
)
|
||||
}
|
||||
val grid = listOf(maxValue / 2, maxValue).filter { it > 0 }.map { value ->
|
||||
val y = base - height(value)
|
||||
val labelTop = y - 14.dp.toPx()
|
||||
// The same constraints drawText() would use for a label at this spot
|
||||
val label = measurer.measure(
|
||||
text = formatCompact(value),
|
||||
style = ChartLabelStyle,
|
||||
constraints = Constraints(
|
||||
maxWidth = ceil(size.width).roundToInt().coerceAtLeast(0),
|
||||
maxHeight = ceil(size.height - labelTop).roundToInt().coerceAtLeast(0),
|
||||
),
|
||||
layoutDirection = layoutDirection,
|
||||
density = this,
|
||||
)
|
||||
GridLine(y, labelTop, label)
|
||||
}
|
||||
|
||||
val line = Path()
|
||||
val area = Path()
|
||||
val blocked = Path()
|
||||
points.forEachIndexed { index, point ->
|
||||
val px = x(index)
|
||||
if (index == 0) {
|
||||
line.moveTo(px, y(point.total))
|
||||
area.moveTo(px, base)
|
||||
area.lineTo(px, y(point.total))
|
||||
blocked.moveTo(px, y(point.blocked))
|
||||
} else {
|
||||
line.lineTo(px, y(point.total))
|
||||
area.lineTo(px, y(point.total))
|
||||
blocked.lineTo(px, y(point.blocked))
|
||||
onDrawBehind {
|
||||
grid.forEach { line ->
|
||||
drawLine(
|
||||
color = Palette.Line,
|
||||
start = Offset(0f, line.y),
|
||||
end = Offset(size.width, line.y),
|
||||
strokeWidth = gridWidth,
|
||||
pathEffect = dash,
|
||||
)
|
||||
drawText(line.label, topLeft = Offset(0f, line.labelTop))
|
||||
}
|
||||
|
||||
bars.forEachIndexed { index, bar ->
|
||||
val x = index * slot + (slot - barWidth) / 2
|
||||
if (bar.total == 0L) {
|
||||
drawRoundRect(Palette.Line, Offset(x, base - stub), Size(barWidth, stub), CornerRadius(stub / 2))
|
||||
return@forEachIndexed
|
||||
}
|
||||
val current = index == n - 1
|
||||
val h = height(bar.total).coerceAtLeast(minBar)
|
||||
drawRoundRect(
|
||||
if (current) Palette.Accent else Palette.Accent.copy(alpha = 0.6f),
|
||||
Offset(x, base - h),
|
||||
Size(barWidth, h),
|
||||
radius,
|
||||
)
|
||||
if (bar.blocked > 0) {
|
||||
val hb = height(bar.blocked).coerceIn(minBlocked, h)
|
||||
if (hb >= h - radius.x) {
|
||||
drawRoundRect(Palette.Blocked, Offset(x, base - hb), Size(barWidth, hb), radius)
|
||||
} else {
|
||||
drawRect(Palette.Blocked, Offset(x, base - hb), Size(barWidth, hb))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
area.lineTo(x(n - 1), base)
|
||||
area.close()
|
||||
|
||||
drawPath(area, Palette.Accent.copy(alpha = 0.14f))
|
||||
drawPath(
|
||||
blocked,
|
||||
Palette.Muted,
|
||||
style = Stroke(width = 1.6.dp.toPx(), cap = StrokeCap.Round, join = StrokeJoin.Round),
|
||||
)
|
||||
drawPath(
|
||||
line,
|
||||
Palette.Accent,
|
||||
style = Stroke(width = 2.4.dp.toPx(), cap = StrokeCap.Round, join = StrokeJoin.Round),
|
||||
)
|
||||
val end = Offset(x(n - 1), y(points.last().total))
|
||||
drawCircle(Palette.Bg, radius = 5.dp.toPx(), center = end)
|
||||
drawCircle(Palette.Accent, radius = 5.dp.toPx(), center = end, style = Stroke(width = 2.4.dp.toPx()))
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
private class GridLine(val y: Float, val labelTop: Float, val label: TextLayoutResult)
|
||||
|
||||
// 1, 2 or 5 times a power of ten, at least [value]: keeps the grid labels round
|
||||
private fun niceCeiling(value: Long): Long {
|
||||
var magnitude = 1L
|
||||
@@ -522,35 +623,127 @@ private fun niceCeiling(value: Long): Long {
|
||||
return 10 * magnitude
|
||||
}
|
||||
|
||||
// Date formats of the chart for the current locale and time zone. The chart is refreshed up to
|
||||
// once a second, so they are kept rather than built anew each time. Main thread only.
|
||||
private class ChartFormats(val locale: Locale, val zone: String) {
|
||||
val hour = SimpleDateFormat("HH:00", locale)
|
||||
val day = SimpleDateFormat("EEE", locale)
|
||||
}
|
||||
|
||||
private var chartFormats: ChartFormats? = null
|
||||
|
||||
private fun chartFormats(): ChartFormats {
|
||||
val locale = Locale.getDefault()
|
||||
val zone = TimeZone.getDefault().id
|
||||
return chartFormats?.takeIf { it.locale == locale && it.zone == zone }
|
||||
?: ChartFormats(locale, zone).also { chartFormats = it }
|
||||
}
|
||||
|
||||
// 24 hourly bars, or 7 bars for the calendar days of the last week (today last)
|
||||
private fun buildChart(period: StatsPeriod, now: Long = System.currentTimeMillis()): Chart {
|
||||
val hours = StatsStore.hourly(period.hours, now)
|
||||
val firstHour = now / HOUR_MS - (hours.size - 1)
|
||||
val formats = chartFormats()
|
||||
if (period == StatsPeriod.DAY) {
|
||||
// Only the first hour gets a label; the other end of the axis says "now"
|
||||
val label = formats.hour.format(Date(firstHour * HOUR_MS))
|
||||
return Chart(period, hours.map { Bar(it.total, it.blocked) }, listOf(label))
|
||||
}
|
||||
val calendar = Calendar.getInstance()
|
||||
fun dayKey(time: Long): Int {
|
||||
calendar.timeInMillis = time
|
||||
return calendar.get(Calendar.YEAR) * 1000 + calendar.get(Calendar.DAY_OF_YEAR)
|
||||
}
|
||||
val dayStarts = (6 downTo 0).map { back ->
|
||||
calendar.timeInMillis = now
|
||||
calendar.add(Calendar.DAY_OF_YEAR, -back)
|
||||
calendar.timeInMillis
|
||||
}
|
||||
val keys = dayStarts.map { dayKey(it) }
|
||||
val totals = LongArray(7)
|
||||
val blocked = LongArray(7)
|
||||
hours.forEachIndexed { index, point ->
|
||||
val day = keys.indexOf(dayKey((firstHour + index) * HOUR_MS))
|
||||
if (day >= 0) {
|
||||
totals[day] += point.total
|
||||
blocked[day] += point.blocked
|
||||
}
|
||||
}
|
||||
return Chart(period, List(7) { Bar(totals[it], blocked[it]) }, dayStarts.map { formats.day.format(Date(it)) })
|
||||
}
|
||||
|
||||
private enum class BlocklistOffer { NONE, SWITCH_ON, FIRST_LIST }
|
||||
|
||||
@Composable
|
||||
private fun BlocklistRow(info: String, onClick: () -> Unit, modifier: Modifier = Modifier) {
|
||||
private fun BlocklistCard(
|
||||
info: String,
|
||||
offer: BlocklistOffer,
|
||||
downloading: Boolean,
|
||||
error: String?,
|
||||
canAccept: Boolean,
|
||||
onAccept: () -> Unit,
|
||||
onClick: () -> Unit,
|
||||
) {
|
||||
val subtitle = when {
|
||||
error != null -> stringResource(R.string.bl_download_failed, error)
|
||||
offer == BlocklistOffer.SWITCH_ON -> stringResource(R.string.blocklist_cta_master)
|
||||
offer == BlocklistOffer.FIRST_LIST -> stringResource(R.string.blocklist_cta_lists)
|
||||
else -> info
|
||||
}
|
||||
Row(
|
||||
modifier = modifier
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.appCard()
|
||||
.clickable(onClick = onClick)
|
||||
.padding(16.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
val idle = offer != BlocklistOffer.NONE
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.size(40.dp)
|
||||
.clip(CircleShape)
|
||||
.background(Palette.Accent),
|
||||
.background(if (idle) Palette.Track else Palette.Accent),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(
|
||||
painterResource(R.drawable.ic_privacy),
|
||||
contentDescription = null,
|
||||
tint = Palette.AccentInk,
|
||||
tint = if (idle) Palette.Fg2 else Palette.AccentInk,
|
||||
modifier = Modifier.size(22.dp),
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.width(14.dp))
|
||||
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(3.dp)) {
|
||||
Text(stringResource(R.string.blocklist_title), color = Palette.Fg, fontSize = 15.sp, fontWeight = FontWeight.Bold)
|
||||
Text(info, color = Palette.Fg2, fontSize = 12.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(
|
||||
subtitle,
|
||||
color = if (error != null) Palette.Blocked else Palette.Fg2,
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 16.sp,
|
||||
maxLines = 3,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.width(10.dp))
|
||||
if (offer == BlocklistOffer.NONE) {
|
||||
Chevron()
|
||||
} else {
|
||||
Button(
|
||||
onClick = onAccept,
|
||||
enabled = canAccept && !downloading,
|
||||
shape = RoundedCornerShape(14.dp),
|
||||
contentPadding = PaddingValues(horizontal = 14.dp),
|
||||
modifier = Modifier.heightIn(min = 40.dp),
|
||||
) {
|
||||
if (downloading) {
|
||||
CircularProgressIndicator(Modifier.size(16.dp), strokeWidth = 2.dp, color = Palette.Fg2)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(stringResource(R.string.downloading), fontSize = 13.sp, maxLines = 1)
|
||||
} else {
|
||||
Text(stringResource(R.string.turn_on), fontWeight = FontWeight.Bold, fontSize = 13.sp, maxLines = 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
Chevron()
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user