Cache chart geometry, labels and date formats

This commit is contained in:
2026-10-31 11:50:14 +02:00
parent e3f5906924
commit 87723f0a8f
3 changed files with 152 additions and 97 deletions
@@ -5,7 +5,6 @@ import android.content.ClipboardManager
import android.widget.Toast import android.widget.Toast
import androidx.annotation.DrawableRes import androidx.annotation.DrawableRes
import androidx.annotation.StringRes import androidx.annotation.StringRes
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.clickable import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
@@ -46,6 +45,7 @@ import androidx.compose.runtime.structuralEqualityPolicy
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.drawWithCache
import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
@@ -415,22 +415,28 @@ private fun companySlices(summary: StatsSummary, otherLabel: String): List<Slice
@Composable @Composable
private fun Donut(slices: List<Slice>, modifier: Modifier = Modifier) { private fun Donut(slices: List<Slice>, modifier: Modifier = Modifier) {
Canvas(modifier) { // The ring's geometry is worked out when the size changes, not every frame
val stroke = 14.dp.toPx() Spacer(
val diameter = size.minDimension - stroke modifier.drawWithCache {
val width = 14.dp.toPx()
val stroke = Stroke(width = width)
val diameter = size.minDimension - width
val topLeft = Offset((size.width - diameter) / 2f, (size.height - diameter) / 2f) val topLeft = Offset((size.width - diameter) / 2f, (size.height - diameter) / 2f)
val arcSize = Size(diameter, diameter) val arcSize = Size(diameter, diameter)
drawArc(OtherColor, 0f, 360f, useCenter = false, topLeft = topLeft, size = arcSize, style = Stroke(width = stroke)) onDrawBehind {
drawArc(OtherColor, 0f, 360f, useCenter = false, topLeft = topLeft, size = arcSize, style = stroke)
var start = -90f var start = -90f
slices.forEach { slice -> slices.forEach { slice ->
val sweep = slice.share * 360f val sweep = slice.share * 360f
if (sweep > 0f) { if (sweep > 0f) {
drawArc(slice.color, start, sweep, useCenter = false, topLeft = topLeft, size = arcSize, style = Stroke(width = stroke)) drawArc(slice.color, start, sweep, useCenter = false, topLeft = topLeft, size = arcSize, style = stroke)
} }
start += sweep start += sweep
} }
} }
} }
)
}
@Composable @Composable
private fun QueryRow( private fun QueryRow(
@@ -56,7 +56,7 @@ import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip 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.CornerRadius
import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size import androidx.compose.ui.geometry.Size
@@ -73,12 +73,14 @@ import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.TextLayoutResult
import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.drawText import androidx.compose.ui.text.drawText
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.rememberTextMeasurer import androidx.compose.ui.text.rememberTextMeasurer
import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp import androidx.compose.ui.unit.sp
@@ -88,11 +90,20 @@ import java.text.SimpleDateFormat
import java.util.Calendar import java.util.Calendar
import java.util.Date import java.util.Date
import java.util.Locale import java.util.Locale
import java.util.TimeZone
import kotlin.math.ceil
import kotlin.math.roundToInt
private const val HOUR_MS = 3_600_000L private const val HOUR_MS = 3_600_000L
// One bar of the chart: an hour, or a day in the 7-day view // One bar of the chart: an hour, or a day in the 7-day view
private class Bar(val total: Long, val blocked: Long, val label: String) 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)
@Composable @Composable
fun HomeScreen( fun HomeScreen(
@@ -116,10 +127,10 @@ fun HomeScreen(
var period by rememberSaveable { mutableStateOf(StatsPeriod.DAY) } var period by rememberSaveable { mutableStateOf(StatsPeriod.DAY) }
var summary by remember { mutableStateOf(StatsStore.summary(period.hours)) } var summary by remember { mutableStateOf(StatsStore.summary(period.hours)) }
var bars by remember { mutableStateOf(chartBars(period)) } var chartData by remember { mutableStateOf(buildChart(period)) }
fun refreshStats() { fun refreshStats() {
summary = StatsStore.summary(period.hours) summary = StatsStore.summary(period.hours)
bars = chartBars(period) chartData = buildChart(period)
} }
OnQueryLogChange { refreshStats() } OnQueryLogChange { refreshStats() }
val statsVersion by StatsStore.version.collectAsStateWithLifecycle() val statsVersion by StatsStore.version.collectAsStateWithLifecycle()
@@ -227,7 +238,7 @@ fun HomeScreen(
} }
} }
val chart: @Composable () -> Unit = { val chart: @Composable () -> Unit = {
ChartSection(bars, period, chartHeight, onPeriod = { period = it }) ChartSection(chartData, period, chartHeight, onPeriod = { period = it })
} }
val blocklist: @Composable () -> Unit = { val blocklist: @Composable () -> Unit = {
BlocklistCard( BlocklistCard(
@@ -244,18 +255,18 @@ fun HomeScreen(
Column( Column(
modifier = modifier modifier = modifier
.verticalScroll(rememberScrollState()) .verticalScroll(rememberScrollState())
.drawBehind { .drawWithCache {
// Soft light behind the logo while protected // Soft light behind the logo while protected. The gradient depends on the size only;
if (glow > 0f) { // the fade is applied as alpha when drawing.
drawCircle( val center = Offset(size.width / 2f, 0f)
brush = Brush.radialGradient( val radius = size.width * 0.65f
colors = listOf(Palette.Accent.copy(alpha = 0.22f * glow), Color.Transparent), val light = Brush.radialGradient(
center = Offset(size.width / 2f, 0f), colors = listOf(Palette.Accent.copy(alpha = 0.22f), Color.Transparent),
radius = size.width * 0.65f, center = center,
), radius = radius,
radius = size.width * 0.65f,
center = Offset(size.width / 2f, 0f),
) )
onDrawBehind {
if (glow > 0f) drawCircle(brush = light, radius = radius, center = center, alpha = glow)
} }
} }
.padding(start = side, end = side, top = 16.dp, bottom = bottomPadding), .padding(start = side, end = side, top = 16.dp, bottom = bottomPadding),
@@ -450,7 +461,7 @@ fun StatBlock(value: String, label: String, modifier: Modifier = Modifier, value
} }
@Composable @Composable
private fun ChartSection(bars: List<Bar>, period: StatsPeriod, height: Dp, onPeriod: (StatsPeriod) -> Unit) { private fun ChartSection(chart: Chart, period: StatsPeriod, height: Dp, onPeriod: (StatsPeriod) -> Unit) {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
Row(verticalAlignment = Alignment.CenterVertically) { Row(verticalAlignment = Alignment.CenterVertically) {
PeriodChip(period, onPeriod) PeriodChip(period, onPeriod)
@@ -465,7 +476,7 @@ private fun ChartSection(bars: List<Bar>, period: StatsPeriod, height: Dp, onPer
.height(height), .height(height),
contentAlignment = Alignment.Center, contentAlignment = Alignment.Center,
) { ) {
if (bars.all { it.total == 0L }) { if (chart.bars.all { it.total == 0L }) {
Text( Text(
stringResource(R.string.chart_empty), stringResource(R.string.chart_empty),
color = Palette.Fg3, color = Palette.Fg3,
@@ -475,19 +486,19 @@ private fun ChartSection(bars: List<Bar>, period: StatsPeriod, height: Dp, onPer
modifier = Modifier.padding(horizontal = 24.dp), modifier = Modifier.padding(horizontal = 24.dp),
) )
} else { } else {
TrafficChart(bars, Modifier.fillMaxWidth().height(height)) TrafficChart(chart.bars, Modifier.fillMaxWidth().height(height))
} }
} }
// Hours: first hour on the left, now on the right. Days: a label under every bar. // Hours: first hour on the left, now on the right. Days: a label under every bar.
Row(Modifier.fillMaxWidth()) { Row(Modifier.fillMaxWidth()) {
if (period == StatsPeriod.DAY) { if (chart.period == StatsPeriod.DAY) {
Text(bars.firstOrNull()?.label.orEmpty(), color = Palette.Fg3, fontSize = 11.sp, modifier = Modifier.weight(1f)) 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) Text(stringResource(R.string.chart_now), color = Palette.Fg3, fontSize = 11.sp)
} else { } else {
bars.forEachIndexed { index, bar -> chart.labels.forEachIndexed { index, label ->
Text( Text(
bar.label, label,
color = if (index == bars.lastIndex) Palette.Fg else Palette.Fg3, color = if (index == chart.labels.lastIndex) Palette.Fg else Palette.Fg3,
fontSize = 11.sp, fontSize = 11.sp,
maxLines = 1, maxLines = 1,
textAlign = TextAlign.Center, textAlign = TextAlign.Center,
@@ -518,10 +529,11 @@ private fun LegendItem(label: String, color: Color) {
@Composable @Composable
private fun TrafficChart(bars: List<Bar>, modifier: Modifier = Modifier) { private fun TrafficChart(bars: List<Bar>, modifier: Modifier = Modifier) {
val measurer = rememberTextMeasurer() val measurer = rememberTextMeasurer()
val labelStyle = TextStyle(color = Palette.Fg3, fontSize = 10.sp) // Scale, grid and grid labels are worked out when the bars or the size change, not every frame
Canvas(modifier) { Spacer(
modifier.drawWithCache {
val n = bars.size val n = bars.size
if (n == 0) return@Canvas if (n == 0) return@drawWithCache onDrawBehind {}
val maxValue = niceCeiling(bars.maxOf { it.total }.coerceAtLeast(1L)) val maxValue = niceCeiling(bars.maxOf { it.total }.coerceAtLeast(1L))
val top = 16.dp.toPx() val top = 16.dp.toPx()
val base = size.height - 2.dp.toPx() val base = size.height - 2.dp.toPx()
@@ -529,34 +541,50 @@ private fun TrafficChart(bars: List<Bar>, modifier: Modifier = Modifier) {
val slot = size.width / n val slot = size.width / n
val barWidth = (slot * if (n > 10) 0.62f else 0.5f).coerceAtLeast(2.dp.toPx()) 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 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 fun height(value: Long) = value.toFloat() / maxValue * span
listOf(maxValue / 2, maxValue).filter { it > 0 }.forEach { value -> val grid = listOf(maxValue / 2, maxValue).filter { it > 0 }.map { value ->
val gridY = base - height(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)
}
onDrawBehind {
grid.forEach { line ->
drawLine( drawLine(
color = Palette.Line, color = Palette.Line,
start = Offset(0f, gridY), start = Offset(0f, line.y),
end = Offset(size.width, gridY), end = Offset(size.width, line.y),
strokeWidth = 1.dp.toPx(), strokeWidth = gridWidth,
pathEffect = PathEffect.dashPathEffect(floatArrayOf(3.dp.toPx(), 4.dp.toPx())), pathEffect = dash,
)
drawText(
textMeasurer = measurer,
text = formatCompact(value),
topLeft = Offset(0f, gridY - 14.dp.toPx()),
style = labelStyle,
) )
drawText(line.label, topLeft = Offset(0f, line.labelTop))
} }
bars.forEachIndexed { index, bar -> bars.forEachIndexed { index, bar ->
val x = index * slot + (slot - barWidth) / 2 val x = index * slot + (slot - barWidth) / 2
if (bar.total == 0L) { if (bar.total == 0L) {
val stub = 2.dp.toPx()
drawRoundRect(Palette.Line, Offset(x, base - stub), Size(barWidth, stub), CornerRadius(stub / 2)) drawRoundRect(Palette.Line, Offset(x, base - stub), Size(barWidth, stub), CornerRadius(stub / 2))
return@forEachIndexed return@forEachIndexed
} }
val current = index == n - 1 val current = index == n - 1
val h = height(bar.total).coerceAtLeast(4.dp.toPx()) val h = height(bar.total).coerceAtLeast(minBar)
drawRoundRect( drawRoundRect(
if (current) Palette.Accent else Palette.Accent.copy(alpha = 0.6f), if (current) Palette.Accent else Palette.Accent.copy(alpha = 0.6f),
Offset(x, base - h), Offset(x, base - h),
@@ -564,7 +592,7 @@ private fun TrafficChart(bars: List<Bar>, modifier: Modifier = Modifier) {
radius, radius,
) )
if (bar.blocked > 0) { if (bar.blocked > 0) {
val hb = height(bar.blocked).coerceIn(2.dp.toPx(), h) val hb = height(bar.blocked).coerceIn(minBlocked, h)
if (hb >= h - radius.x) { if (hb >= h - radius.x) {
drawRoundRect(Palette.Blocked, Offset(x, base - hb), Size(barWidth, hb), radius) drawRoundRect(Palette.Blocked, Offset(x, base - hb), Size(barWidth, hb), radius)
} else { } else {
@@ -574,6 +602,10 @@ private fun TrafficChart(bars: List<Bar>, modifier: Modifier = Modifier) {
} }
} }
} }
)
}
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 // 1, 2 or 5 times a power of ten, at least [value]: keeps the grid labels round
private fun niceCeiling(value: Long): Long { private fun niceCeiling(value: Long): Long {
@@ -585,15 +617,31 @@ private fun niceCeiling(value: Long): Long {
return 10 * magnitude 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) // 24 hourly bars, or 7 bars for the calendar days of the last week (today last)
private fun chartBars(period: StatsPeriod, now: Long = System.currentTimeMillis()): List<Bar> { private fun buildChart(period: StatsPeriod, now: Long = System.currentTimeMillis()): Chart {
val hours = StatsStore.hourly(period.hours, now) val hours = StatsStore.hourly(period.hours, now)
val firstHour = now / HOUR_MS - (hours.size - 1) val firstHour = now / HOUR_MS - (hours.size - 1)
val formats = chartFormats()
if (period == StatsPeriod.DAY) { if (period == StatsPeriod.DAY) {
val format = SimpleDateFormat("HH:00", Locale.getDefault()) // Only the first hour gets a label; the other end of the axis says "now"
return hours.mapIndexed { index, point -> val label = formats.hour.format(Date(firstHour * HOUR_MS))
Bar(point.total, point.blocked, format.format(Date((firstHour + index) * HOUR_MS))) return Chart(period, hours.map { Bar(it.total, it.blocked) }, listOf(label))
}
} }
val calendar = Calendar.getInstance() val calendar = Calendar.getInstance()
fun dayKey(time: Long): Int { fun dayKey(time: Long): Int {
@@ -615,8 +663,7 @@ private fun chartBars(period: StatsPeriod, now: Long = System.currentTimeMillis(
blocked[day] += point.blocked blocked[day] += point.blocked
} }
} }
val format = SimpleDateFormat("EEE", Locale.getDefault()) return Chart(period, List(7) { Bar(totals[it], blocked[it]) }, dayStarts.map { formats.day.format(Date(it)) })
return dayStarts.mapIndexed { index, time -> Bar(totals[index], blocked[index], format.format(Date(time))) }
} }
private enum class BlocklistOffer { NONE, SWITCH_ON, FIRST_LIST } private enum class BlocklistOffer { NONE, SWITCH_ON, FIRST_LIST }
@@ -214,6 +214,8 @@ fun SubPage(title: String, onBack: () -> Unit, modifier: Modifier = Modifier, co
} }
} }
private val SearchTextStyle = TextStyle(color = Palette.Fg, fontSize = 14.sp)
@Composable @Composable
fun SearchField( fun SearchField(
value: String, value: String,
@@ -247,7 +249,7 @@ fun SearchField(
onValueChange = onValueChange, onValueChange = onValueChange,
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
singleLine = true, singleLine = true,
textStyle = TextStyle(color = Palette.Fg, fontSize = 14.sp), textStyle = SearchTextStyle,
cursorBrush = SolidColor(Palette.Accent), cursorBrush = SolidColor(Palette.Accent),
) )
} }