diff --git a/CHANGELOG.md b/CHANGELOG.md index 6fb23cd..2f36ac6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # 变更记录 +## 2026-11-28 · 统计页重构:去掉顶部区间筛选,分布卡新增日/周/月/年与翻页,环形图改为引线标注并显示时长 + +- 同步源码更新 7 个文件(新增/修改 7,删除 0)。 + ## 2026-11-28 · v0.3.1:修复通知走时乱码数字、今日筛选收窄 - **修复通知与锁屏第二行时间显示为一长串错误数字**:`Chronometer` 的时间轴是 `SystemClock.elapsedRealtime()`(开机后毫秒),原先把 `System.currentTimeMillis()`(1970 年起算)当成了基准,两者相差十几亿毫秒,读数因此变成天文数字。改为统一用单调钟计算基准:倒计时 `base = now + 剩余`,正计时 `base = now - 已用`,暂停停在暂停值。布局里同时补上 `android:countDown="true"` 作为初始状态兜底。 diff --git a/src/main/java/com/focusbox/app/data/Store.kt b/src/main/java/com/focusbox/app/data/Store.kt index 4a826f6..c8958ca 100644 --- a/src/main/java/com/focusbox/app/data/Store.kt +++ b/src/main/java/com/focusbox/app/data/Store.kt @@ -467,17 +467,22 @@ object Store { return out } - fun distribution(fromMs: Long): List { val list = ArrayList() + /** + * 按项目汇总的专注时长,区间是左闭右开 [fromMs, toMs)。 + * 统计页的日/周/月/年四档都要能看历史区间,所以必须带上界; + * 只给下界的话「11月26日」会一路把 26 号之后的记录也算进来。 + */ + fun distribution(fromMs: Long, toMs: Long): List { val list = ArrayList() db.rawQuery( """ SELECT COALESCE(p._id, 0), COALESCE(p.name, '未归类'), COALESCE(p.color, -1), IFNULL(SUM(s.seconds),0), IFNULL(SUM(CASE WHEN s.completed = 1 THEN 1 ELSE 0 END),0) FROM sessions s LEFT JOIN projects p ON p._id = s.project_id - WHERE s.start_at >= ? + WHERE s.start_at >= ? AND s.start_at < ? GROUP BY s.project_id HAVING SUM(s.seconds) > 0 ORDER BY 4 DESC """.trimIndent(), - arrayOf(fromMs.toString()) + arrayOf(fromMs.toString(), toMs.toString()) ).use { c -> while (c.moveToNext()) { list.add( @@ -494,8 +499,8 @@ object Store { return list } - /** 按任务汇总的专注时长,用于统计页的"任务分布" */ - fun taskSlices(fromMs: Long): List { + /** 按任务汇总的专注时长,区间同样是 [fromMs, toMs) */ + fun taskSlices(fromMs: Long, toMs: Long): List { val list = ArrayList() db.rawQuery( """ @@ -504,11 +509,11 @@ object Store { FROM sessions s LEFT JOIN tasks t ON t._id = s.task_id LEFT JOIN projects p ON p._id = t.project_id - WHERE s.start_at >= ? + WHERE s.start_at >= ? AND s.start_at < ? GROUP BY s.task_id HAVING SUM(s.seconds) > 0 ORDER BY 4 DESC """.trimIndent(), - arrayOf(fromMs.toString()) + arrayOf(fromMs.toString(), toMs.toString()) ).use { c -> while (c.moveToNext()) { list.add( diff --git a/src/main/java/com/focusbox/app/ui/stats/PeriodDistributionCard.kt b/src/main/java/com/focusbox/app/ui/stats/PeriodDistributionCard.kt new file mode 100644 index 0000000..8a2dc8d --- /dev/null +++ b/src/main/java/com/focusbox/app/ui/stats/PeriodDistributionCard.kt @@ -0,0 +1,235 @@ +package com.focusbox.app.ui.stats + +import android.content.Context +import android.graphics.Typeface +import android.util.AttributeSet +import android.util.TypedValue +import android.view.Gravity +import android.widget.ImageView +import android.widget.LinearLayout +import android.widget.TextView +import androidx.core.content.ContextCompat +import com.focusbox.app.R +import com.focusbox.app.data.Store +import com.focusbox.app.util.Dates +import com.focusbox.app.util.col +import com.focusbox.app.util.dpi +import com.focusbox.app.widget.LabelDonutView + +/** + * 「项目分布 / 任务分布」卡片:自带 日 / 周 / 月 / 年 四档与左右翻页。 + * + * 为什么做成独立控件而不是在 Fragment 里堆代码:两张卡片结构完全一样, + * 只有数据源不同(按项目 / 按任务)。做成控件后各自持有自己的区间状态, + * 互不影响——看"本周的项目分布"和"这一年的任务分布"可以同时成立。 + */ +class PeriodDistributionCard @JvmOverloads constructor( + context: Context, + attrs: AttributeSet? = null, +) : LinearLayout(context, attrs) { + + enum class Scale(val labelRes: Int) { + DAY(R.string.scale_day), + WEEK(R.string.scale_week), + MONTH(R.string.scale_month), + YEAR(R.string.scale_year), + } + + private val tvTitle = TextView(context) + private val segItems = ArrayList(4) + private val tvPeriod = TextView(context) + private val btnPrev = ImageView(context) + private val btnNext = ImageView(context) + private val donut = LabelDonutView(context) + + /** 当前粒度,默认按天 */ + var scale = Scale.DAY + private set + + /** 锚点:落在目标周期内的任意时刻,实际区间由它推导 */ + private var anchor = Dates.todayStart() + + /** true = 按任务汇总,false = 按项目汇总 */ + var byTask = false + set(value) { + field = value + refresh() + } + + var cardTitle: String = "" + set(value) { + field = value + tvTitle.text = value + } + + init { + orientation = VERTICAL + background = ContextCompat.getDrawable(context, R.drawable.bg_card) + setPadding(context.dpi(16f), context.dpi(15f), context.dpi(16f), context.dpi(10f)) + build() + refresh() + } + + // ------------------------------------------------------------------ 结构 + + private fun build() { + tvTitle.apply { + setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f) + setTextColor(context.col(R.color.title)) + typeface = Typeface.DEFAULT_BOLD + includeFontPadding = false + } + addView(tvTitle) + + val seg = LinearLayout(context).apply { + orientation = HORIZONTAL + background = ContextCompat.getDrawable(context, R.drawable.bg_segment_track) + setPadding(context.dpi(3f), context.dpi(3f), context.dpi(3f), context.dpi(3f)) + } + addView(seg, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT).apply { + topMargin = context.dpi(13f) + }) + + Scale.entries.forEach { s -> + val tv = TextView(context).apply { + text = context.getString(s.labelRes) + setTextSize(TypedValue.COMPLEX_UNIT_SP, 13f) + gravity = Gravity.CENTER + setPadding(0, context.dpi(8f), 0, context.dpi(8f)) + isClickable = true + setOnClickListener { switchScale(s) } + } + segItems.add(tv) + seg.addView(tv, LayoutParams(0, LayoutParams.WRAP_CONTENT, 1f)) + } + + // 翻页行:左右箭头 + 居中周期文字(参考图的排布) + val periodRow = LinearLayout(context).apply { + orientation = HORIZONTAL + gravity = Gravity.CENTER_VERTICAL + } + addView(periodRow, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT).apply { + topMargin = context.dpi(4f) + }) + + btnPrev.apply { + setImageResource(R.drawable.ic_chevron_right) + rotation = 180f + setColorFilter(context.col(R.color.text_secondary)) + scaleType = ImageView.ScaleType.FIT_CENTER + setPadding(context.dpi(8f), context.dpi(8f), context.dpi(8f), context.dpi(8f)) + isClickable = true + setOnClickListener { shift(-1) } + } + periodRow.addView(btnPrev, LayoutParams(context.dpi(36f), context.dpi(40f))) + + tvPeriod.apply { + setTextSize(TypedValue.COMPLEX_UNIT_SP, 14f) + setTextColor(context.col(R.color.text)) + typeface = Typeface.DEFAULT_BOLD + gravity = Gravity.CENTER + includeFontPadding = false + } + periodRow.addView(tvPeriod, LayoutParams(0, LayoutParams.WRAP_CONTENT, 1f)) + + btnNext.apply { + setImageResource(R.drawable.ic_chevron_right) + setColorFilter(context.col(R.color.text_secondary)) + scaleType = ImageView.ScaleType.FIT_CENTER + setPadding(context.dpi(8f), context.dpi(8f), context.dpi(8f), context.dpi(8f)) + isClickable = true + setOnClickListener { shift(1) } + } + periodRow.addView(btnNext, LayoutParams(context.dpi(36f), context.dpi(40f))) + + addView(donut, LayoutParams(LayoutParams.MATCH_PARENT, context.dpi(222f)).apply { + topMargin = context.dpi(2f) + }) + } + + // ------------------------------------------------------------------ 交互 + + private fun switchScale(s: Scale) { + if (scale == s) return + scale = s + // 换粒度回到"当前",否则从 2024 年的日视图切到年视图会落在 2024 年,容易困惑 + anchor = Dates.todayStart() + refresh() + } + + private fun shift(delta: Int) { + if (delta > 0 && !canNext()) return + val s = start() + anchor = when (scale) { + Scale.DAY -> Dates.addDays(s, delta) + Scale.WEEK -> Dates.addDays(s, 7 * delta) + Scale.MONTH -> Dates.addMonths(s, delta) + Scale.YEAR -> Dates.addYears(s, delta) + } + refresh() + } + + private fun periodStart(ms: Long): Long = when (scale) { + Scale.DAY -> Dates.dayStart(ms) + Scale.WEEK -> Dates.weekStart(ms) + Scale.MONTH -> Dates.monthStart(ms) + Scale.YEAR -> Dates.yearStart(ms) + } + + private fun start(): Long = periodStart(anchor) + + private fun end(s: Long): Long = when (scale) { + Scale.DAY -> Dates.addDays(s, 1) + Scale.WEEK -> Dates.addDays(s, 7) + Scale.MONTH -> Dates.addMonths(s, 1) + Scale.YEAR -> Dates.addYears(s, 1) + } + + /** 未来没有记录,往后翻到当前周期为止 */ + private fun canNext(): Boolean = start() < periodStart(Dates.todayStart()) + + // ------------------------------------------------------------------ 渲染 + + fun refresh() { + val from = start() + val to = end(from) + + val raw = if (byTask) Store.taskSlices(from, to) else Store.distribution(from, to) + donut.setSlices( + raw.map { + LabelDonutView.Slice( + name = it.name, + seconds = it.seconds, + color = if (it.color == -1) context.col(R.color.text_tertiary) else it.color, + ) + } + ) + donut.centerText = Dates.durationBrief(raw.sumOf { it.seconds }) + donut.centerCaption = + context.getString(if (byTask) R.string.task_share else R.string.total_focus) + + tvPeriod.text = periodLabel(from, to) + applySegments() + btnNext.alpha = if (canNext()) 1f else 0.2f + } + + private fun periodLabel(from: Long, to: Long): String = when (scale) { + Scale.DAY -> Dates.mdLong(from) + Scale.WEEK -> context.getString(R.string.period_week_range, Dates.md(from), Dates.md(to - 1)) + Scale.MONTH -> context.getString(R.string.period_month, Dates.yearOf(from), Dates.monthOf(from)) + Scale.YEAR -> context.getString(R.string.period_year, Dates.yearOf(from)) + } + + private fun applySegments() { + val onText = context.col(R.color.title) + val offText = context.col(R.color.text_secondary) + val onBg = ContextCompat.getDrawable(context, R.drawable.bg_segment_on) + Scale.entries.forEachIndexed { i, s -> + val tv = segItems[i] + val selected = s == scale + tv.background = if (selected) onBg else null + tv.setTextColor(if (selected) onText else offText) + tv.typeface = if (selected) Typeface.DEFAULT_BOLD else Typeface.DEFAULT + } + } +} diff --git a/src/main/java/com/focusbox/app/ui/stats/StatsFragment.kt b/src/main/java/com/focusbox/app/ui/stats/StatsFragment.kt index ff9ff6f..4b986b7 100644 --- a/src/main/java/com/focusbox/app/ui/stats/StatsFragment.kt +++ b/src/main/java/com/focusbox/app/ui/stats/StatsFragment.kt @@ -1,36 +1,31 @@ package com.focusbox.app.ui.stats import android.graphics.Typeface -import android.graphics.drawable.GradientDrawable import android.os.Bundle import android.view.Gravity import android.view.View import android.widget.LinearLayout import android.widget.TextView -import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment import com.focusbox.app.R import com.focusbox.app.data.Store -import com.focusbox.app.model.ProjectSlice import com.focusbox.app.util.Dates import com.focusbox.app.util.Prefs -import com.focusbox.app.util.circleBg import com.focusbox.app.util.col import com.focusbox.app.util.dpi import com.focusbox.app.util.roundBg -import com.focusbox.app.util.visible import com.focusbox.app.widget.BarChartView -import com.focusbox.app.widget.DonutView import com.focusbox.app.widget.HeatmapView import com.focusbox.app.widget.RingView -import java.util.Calendar /** * 统计页。 * - * 三层信息:今天(我要不要现在开始)→ 区间趋势(这周/这月还行不行)→ 累计与分布 - * (时间到底花在哪)。四个区间(今日 / 本周 / 本月 / 全部)切换只影响趋势与两处分布, - * 不改变最上方的"今日"卡片——它永远是今天。 + * 三层信息:今天(我要不要现在开始)→ 近一周趋势与打卡 → 时间到底花在哪。 + * + * 顶部的区间筛选已经去掉:趋势固定看最近 7 天,两个分布卡各自带 + * 日 / 周 / 月 / 年 与左右翻页([PeriodDistributionCard]), + * 想同时比较"本周的项目分布"和"今年的任务分布"也不会互相牵制。 */ class StatsFragment : Fragment(R.layout.fragment_stats) { @@ -46,18 +41,12 @@ class StatsFragment : Fragment(R.layout.fragment_stats) { private lateinit var heatmap: HeatmapView private lateinit var tvHeatHint: TextView private lateinit var heatLegend: LinearLayout - private lateinit var donut: DonutView - private lateinit var donutLegend: LinearLayout - private lateinit var donutTask: DonutView - private lateinit var taskLegend: LinearLayout + private lateinit var cardProject: PeriodDistributionCard + private lateinit var cardTask: PeriodDistributionCard private lateinit var summaryGrid: LinearLayout - private lateinit var segToday: TextView - private lateinit var segWeek: TextView - private lateinit var segMonth: TextView - private lateinit var segAll: TextView - /** 0 今日 / 1 本周 / 2 本月 / 3 全部 */ - private var range = 0 + /** 趋势固定显示最近 7 天(含今天) */ + private val trendDays = 7 override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) @@ -73,20 +62,14 @@ class StatsFragment : Fragment(R.layout.fragment_stats) { heatmap = view.findViewById(R.id.heatmap) tvHeatHint = view.findViewById(R.id.tvHeatHint) heatLegend = view.findViewById(R.id.heatLegend) - donut = view.findViewById(R.id.donut) - donutLegend = view.findViewById(R.id.donutLegend) - donutTask = view.findViewById(R.id.donutTask) - taskLegend = view.findViewById(R.id.taskLegend) + cardProject = view.findViewById(R.id.cardProject) + cardTask = view.findViewById(R.id.cardTask) summaryGrid = view.findViewById(R.id.summaryGrid) - segToday = view.findViewById(R.id.segToday) - segWeek = view.findViewById(R.id.segWeek) - segMonth = view.findViewById(R.id.segMonth) - segAll = view.findViewById(R.id.segAll) - segToday.setOnClickListener { switchRange(0) } - segWeek.setOnClickListener { switchRange(1) } - segMonth.setOnClickListener { switchRange(2) } - segAll.setOnClickListener { switchRange(3) } + cardProject.cardTitle = getString(R.string.distribution_title) + cardProject.byTask = false + cardTask.cardTitle = getString(R.string.task_distribution_title) + cardTask.byTask = true buildHeatLegend() reload() @@ -102,37 +85,17 @@ class StatsFragment : Fragment(R.layout.fragment_stats) { if (!hidden && view != null) reload() } - private fun switchRange(r: Int) { - if (range == r) return - range = r - reload() - } - fun reload() { if (view == null || !isAdded) return - applySegments() renderToday() renderTrend() renderHeatmap() - renderDistribution() - renderTaskDistribution() + // 两张分布卡各自持有区间状态,回到页面只要重新取数 + cardProject.refresh() + cardTask.refresh() renderSummary() } - private fun applySegments() { - val ctx = requireContext() - val onText = ctx.col(R.color.title) - val offText = ctx.col(R.color.text_secondary) - listOf(segToday, segWeek, segMonth, segAll).forEachIndexed { i, tv -> - val selected = i == range - tv.background = if (selected) { - ContextCompat.getDrawable(ctx, R.drawable.bg_segment_on) - } else null - tv.setTextColor(if (selected) onText else offText) - tv.typeface = if (selected) Typeface.DEFAULT_BOLD else Typeface.DEFAULT - } - } - private fun renderToday() { val goal = Prefs.dailyGoalMinutes val stat = Store.todayStat(goal) @@ -147,46 +110,10 @@ class StatsFragment : Fragment(R.layout.fragment_stats) { tvStreak.text = "连续打卡 ${streak} 天 · 目标 ${goal} 分钟" } - private fun rangeStart(): Long = when (range) { - 0 -> Dates.todayStart() - 1 -> Dates.weekStart() - 2 -> Store.monthStart() - else -> 0L - } - private fun renderTrend() { + val from = Dates.addDays(Dates.todayStart(), -(trendDays - 1)) + val series = Store.dailySeries(from, trendDays) barChart.labelStep = 0 - if (range == 0) { - // 今日:按小时看节奏,24 根柱子,标签每 6 小时一次 - val series = Store.hourlySeries(Dates.todayStart()) - barChart.labelStep = 6 - barChart.setData(series) - val totalMinutes = series.sumOf { it.minutes } - tvTrendTotal.text = if (totalMinutes <= 0) { - getString(R.string.no_data) - } else { - "共 ${Dates.duration(totalMinutes * 60)}" - } - return - } - val from: Long - val days: Int - when (range) { - 1 -> { - from = Dates.weekStart() - days = (((Dates.todayStart() - from) / 86_400_000L).toInt() + 1).coerceIn(1, 7) - } - 2 -> { - from = Store.monthStart() - val c = Calendar.getInstance() - days = c.get(Calendar.DAY_OF_MONTH).coerceIn(1, 31) - } - else -> { - from = Dates.addDays(Dates.todayStart(), -29) - days = 30 - } - } - val series = Store.dailySeries(from, days) barChart.setData(series) val totalMinutes = series.sumOf { it.minutes } tvTrendTotal.text = if (totalMinutes <= 0) { @@ -234,78 +161,6 @@ class StatsFragment : Fragment(R.layout.fragment_stats) { gravity = Gravity.CENTER_VERTICAL } - private fun renderDistribution() { - val slices = Store.distribution(rangeStart()) - donut.caption = getString(R.string.total_focus) - donut.setSlices(slices) - fillLegend(donutLegend, slices, R.string.more_projects) - } - - /** 任务分布:同样一张占比环,数据换成按任务分组 */ - private fun renderTaskDistribution() { - val slices = Store.taskSlices(rangeStart()) - donutTask.caption = getString(R.string.task_share) - donutTask.setSlices(slices) - fillLegend(taskLegend, slices, R.string.more_tasks) - } - - private fun fillLegend(container: LinearLayout, slices: List, moreRes: Int) { - container.removeAllViews() - if (slices.isEmpty()) { - container.addView(TextView(requireContext()).apply { - text = getString(R.string.no_data) - textSize = 13f - setTextColor(col(R.color.text_tertiary)) - }) - return - } - val total = slices.sumOf { it.seconds }.coerceAtLeast(1) - slices.take(5).forEach { s -> container.addView(legendRow(s, total)) } - if (slices.size > 5) { - container.addView(TextView(requireContext()).apply { - text = getString(moreRes, slices.size - 5) - textSize = 11f - setTextColor(col(R.color.text_tertiary)) - setPadding(0, dpi(4f), 0, 0) - }) - } - } - - private fun legendRow(slice: ProjectSlice, total: Int): LinearLayout { - val ctx = requireContext() - val row = LinearLayout(ctx).apply { - orientation = LinearLayout.HORIZONTAL - gravity = Gravity.CENTER_VERTICAL - setPadding(0, dpi(4f), 0, dpi(4f)) - } - val dot = View(ctx) - val dlp = LinearLayout.LayoutParams(dpi(8f), dpi(8f)) - dlp.marginEnd = dpi(7f) - dot.layoutParams = dlp - dot.background = circleBg(if (slice.color == -1) ctx.col(R.color.text_tertiary) else slice.color) - - val name = TextView(ctx).apply { - text = slice.name - textSize = 12.5f - setTextColor(col(R.color.text)) - maxLines = 1 - ellipsize = android.text.TextUtils.TruncateAt.END - } - val nameLp = LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f) - name.layoutParams = nameLp - - val pct = (slice.seconds * 100 / total).coerceAtLeast(1) - val value = TextView(ctx).apply { - text = "$pct%" - textSize = 12f - setTextColor(col(R.color.text_secondary)) - } - row.addView(dot) - row.addView(name) - row.addView(value) - return row - } - private fun renderSummary() { val totals = Store.totals() summaryGrid.removeAllViews() diff --git a/src/main/java/com/focusbox/app/util/Dates.kt b/src/main/java/com/focusbox/app/util/Dates.kt index 7b95dfe..12f4eb0 100644 --- a/src/main/java/com/focusbox/app/util/Dates.kt +++ b/src/main/java/com/focusbox/app/util/Dates.kt @@ -30,23 +30,52 @@ object Dates { fun todayStart(): Long = dayStart(System.currentTimeMillis()) - /** 本周一 00:00(周一为一周起点,符合国内习惯) */ - fun weekStart(): Long { + /** 本周一 00:00(周一为一周起点,符合国内习惯);传任意时刻则返回它所在周的周一 */ + fun weekStart(ms: Long = System.currentTimeMillis()): Long { val c = Calendar.getInstance() - c.timeInMillis = todayStart() + c.timeInMillis = dayStart(ms) val dow = c.get(Calendar.DAY_OF_WEEK) // 1=周日 val back = if (dow == Calendar.SUNDAY) 6 else dow - 2 c.add(Calendar.DAY_OF_MONTH, -back) return c.timeInMillis } - fun monthStart(): Long { + /** 所在月的 1 日 00:00;不传参就是本月 */ + fun monthStart(ms: Long = System.currentTimeMillis()): Long { val c = Calendar.getInstance() - c.timeInMillis = todayStart() + c.timeInMillis = dayStart(ms) c.set(Calendar.DAY_OF_MONTH, 1) return c.timeInMillis } + /** 所在年的 1 月 1 日 00:00;不传参就是今年 */ + fun yearStart(ms: Long = System.currentTimeMillis()): Long { + val c = Calendar.getInstance() + c.timeInMillis = dayStart(ms) + c.set(Calendar.DAY_OF_MONTH, 1) + c.set(Calendar.MONTH, Calendar.JANUARY) + return c.timeInMillis + } + + fun addYears(ms: Long, years: Int): Long { + val c = Calendar.getInstance() + c.timeInMillis = ms + c.add(Calendar.YEAR, years) + return c.timeInMillis + } + + fun yearOf(ms: Long): Int { + val c = Calendar.getInstance() + c.timeInMillis = ms + return c.get(Calendar.YEAR) + } + + fun monthOf(ms: Long): Int { + val c = Calendar.getInstance() + c.timeInMillis = ms + return c.get(Calendar.MONTH) + 1 + } + fun addDays(ms: Long, days: Int): Long { val c = Calendar.getInstance() c.timeInMillis = ms @@ -80,6 +109,20 @@ object Dates { return if (m == 0) "${h}小时" else "${h}小时${m}分" } + /** + * 环形图标注用的紧凑口径:20m / 1h 10m / 4h 3m。 + * 参考图里贴着引线的数字要一眼读出分量,中文"小时/分"太长会把标注撑到环外。 + */ + fun durationBrief(seconds: Int): String { + if (seconds <= 0) return "0m" + val minutes = seconds / 60 + if (minutes <= 0) return "${seconds}s" + if (minutes < 60) return "${minutes}m" + val h = minutes / 60 + val m = minutes % 60 + return if (m == 0) "${h}h" else "${h}h ${m}m" + } + /** 图表坐标轴用的短格式:2h / 45m */ fun shortDuration(seconds: Int): String { if (seconds <= 0) return "0" diff --git a/src/main/java/com/focusbox/app/widget/LabelDonutView.kt b/src/main/java/com/focusbox/app/widget/LabelDonutView.kt new file mode 100644 index 0000000..58c7d3a --- /dev/null +++ b/src/main/java/com/focusbox/app/widget/LabelDonutView.kt @@ -0,0 +1,259 @@ +package com.focusbox.app.widget + +import android.content.Context +import android.graphics.Canvas +import android.graphics.Color +import android.graphics.Paint +import android.graphics.RectF +import android.text.TextPaint +import android.text.TextUtils +import android.util.AttributeSet +import android.view.View +import com.focusbox.app.R +import com.focusbox.app.util.Dates +import com.focusbox.app.util.col +import com.focusbox.app.util.dpf +import com.focusbox.app.util.spf +import kotlin.math.cos +import kotlin.math.sin + +/** + * 带引线标注的环形图。 + * + * 与普通占比环的区别:项目名与时长不放在图外的列表里,而是用折线牵到环的两侧 + * (左侧标注右对齐、右侧标注左对齐,圆点统一落在外侧边缘),这样一眼就能把 + * 色块和"这是谁、花了多久"对上,不用在图例里来回找。 + * + * 标注位置要自己算:同一侧的标签按角度落点排序后做最小间距夹逼, + * 否则相邻扇区的两行字会叠在一起。 + */ +class LabelDonutView @JvmOverloads constructor( + context: Context, + attrs: AttributeSet? = null, +) : View(context, attrs) { + + data class Slice(val name: String, val seconds: Int, val color: Int) + + private var slices: List = emptyList() + + /** 环中心的大字(总时长) */ + var centerText: String = "" + set(value) { + field = value + invalidate() + } + + /** 环中心的小字(总专注 / 任务占比) */ + var centerCaption: String = "" + set(value) { + field = value + invalidate() + } + + /** 最多画几条引线标注,多出来的合并成「其他」,避免标注挤成一团 */ + var maxLabels: Int = 6 + + private val strokeW = context.dpf(15f) + + private val arcPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + style = Paint.Style.STROKE + strokeWidth = strokeW + strokeCap = Paint.Cap.BUTT + } + private val trackPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + style = Paint.Style.STROKE + strokeWidth = strokeW + color = context.col(R.color.ring_track) + } + private val pctPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + textSize = context.spf(10f) + textAlign = Paint.Align.CENTER + isFakeBoldText = true + } + private val centerPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + textSize = context.spf(19f) + color = context.col(R.color.title) + textAlign = Paint.Align.CENTER + isFakeBoldText = true + } + private val captionPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + textSize = context.spf(10f) + color = context.col(R.color.text_tertiary) + textAlign = Paint.Align.CENTER + } + private val linePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + style = Paint.Style.STROKE + strokeWidth = context.dpf(1.2f) + } + private val dotPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.FILL } + private val tagValuePaint = TextPaint(Paint.ANTI_ALIAS_FLAG).apply { + textSize = context.spf(15f) + isFakeBoldText = true + } + private val tagNamePaint = TextPaint(Paint.ANTI_ALIAS_FLAG).apply { + textSize = context.spf(11f) + } + + fun setSlices(list: List) { + slices = list + invalidate() + } + + private data class Tag( + val slice: Slice, + val midDeg: Float, + val side: Int, + val anchorY: Float, + var y: Float = anchorY, + ) + + override fun onDraw(canvas: Canvas) { + val total = slices.sumOf { it.seconds } + val cx = width / 2f + val cy = height / 2f + + // 环的直径同时受宽高约束:宽度让出两侧标注区,高度不足时优先保证标注能排开 + val outer = minOf(width * 0.48f, height * 0.62f) + val r = (outer / 2f - strokeW / 2f).coerceAtLeast(context.dpf(24f)) + + canvas.drawCircle(cx, cy, r, trackPaint) + + if (total <= 0) { + drawCenter(canvas, cx, cy, context.getString(R.string.no_record)) + return + } + + val shown = collapse(slices) + val box = RectF(cx - r, cy - r, cx + r, cy + r) + val gapDeg = if (shown.size > 1) 2.2f else 0f + + // ---- 弧与百分比 + var start = -90f + val tags = ArrayList(shown.size) + shown.forEach { s -> + val sweep = s.seconds.toFloat() / total * 360f + val midDeg = start + sweep / 2f + arcPaint.color = s.color + canvas.drawArc(box, start + gapDeg / 2f, (sweep - gapDeg).coerceAtLeast(0.5f), false, arcPaint) + + val arcLen = sweep / 360f * (2 * Math.PI.toFloat() * r) + if (arcLen >= context.dpf(20f)) { + val rad = Math.toRadians(midDeg.toDouble()) + val px = cx + r * cos(rad).toFloat() + val py = cy + r * sin(rad).toFloat() + pctPaint.color = readableOn(s.color) + val fm = pctPaint.fontMetrics + canvas.drawText( + "${(s.seconds * 100f / total).toInt().coerceAtLeast(1)}%", + px, + py - (fm.ascent + fm.descent) / 2f, + pctPaint, + ) + } + + // 太薄的扇区不牵线,否则几条线会叠在同一个点上 + if (sweep >= 5f) { + val cosA = cos(radians(midDeg)) + val sinA = sin(radians(midDeg)) + tags.add( + Tag( + slice = s, + midDeg = midDeg, + side = if (cosA >= 0.0) 1 else -1, + anchorY = cy + ((r + strokeW) * sinA).toFloat(), + ) + ) + } + start += sweep + } + + drawCenter(canvas, cx, cy, null) + layoutTags(tags) + tags.forEach { drawTag(canvas, it, cx, cy, r) } + } + + private fun radians(deg: Float): Double = Math.toRadians(deg.toDouble()) + + private fun collapse(list: List): List { + if (list.size <= maxLabels) return list + val head = list.take(maxLabels - 1) + val rest = list.drop(maxLabels - 1) + return head + Slice( + name = context.getString(R.string.slice_other), + seconds = rest.sumOf { it.seconds }, + color = context.col(R.color.text_tertiary), + ) + } + + private fun drawCenter(canvas: Canvas, cx: Float, cy: Float, emptyHint: String?) { + val big = centerText.takeIf { it.isNotBlank() } ?: "0m" + canvas.drawText(big, cx, cy + context.dpf(2f), centerPaint) + val cap = emptyHint ?: centerCaption + if (cap.isNotBlank()) { + canvas.drawText(cap, cx, cy + context.dpf(18f), captionPaint) + } + } + + /** 同侧标签按落点排序后做最小间距夹逼,再整体收回可视区 */ + private fun layoutTags(tags: List) { + val minGap = context.dpf(29f) + val top = context.dpf(4f) + val bottom = height - context.dpf(8f) + for (side in intArrayOf(-1, 1)) { + val group = tags.filter { it.side == side }.sortedBy { it.anchorY } + if (group.isEmpty()) continue + group.forEachIndexed { i, t -> + t.y = if (i == 0) maxOf(t.anchorY, top) else maxOf(t.anchorY, group[i - 1].y + minGap) + } + val overflow = group.last().y - bottom + if (overflow > 0f) group.forEach { it.y -= overflow } + // 极端情况下(标注多、控件矮)再压回上界,宁可间距略小也不出画布 + group.forEach { it.y = it.y.coerceIn(top, bottom) } + } + } + + private fun drawTag(canvas: Canvas, tag: Tag, cx: Float, cy: Float, r: Float) { + val side = tag.side + val color = tag.slice.color + val dotR = context.dpf(2.6f) + val dotX = if (side > 0) width - context.dpf(3f) - dotR else context.dpf(3f) + dotR + val kneeX = cx + side * (r + context.dpf(13f)) + + val cosA = cos(radians(tag.midDeg)).toFloat() + val sinA = sin(radians(tag.midDeg)).toFloat() + val startX = cx + (r + strokeW / 2f) * cosA + val startY = cy + (r + strokeW / 2f) * sinA + + linePaint.color = color + linePaint.alpha = 200 + // 从环外缘斜出到折点,再水平指向外侧圆点 + canvas.drawLine(startX, startY, kneeX, tag.y, linePaint) + canvas.drawLine(kneeX, tag.y, dotX, tag.y, linePaint) + + dotPaint.color = color + canvas.drawCircle(dotX, tag.y, dotR, dotPaint) + + val textX = dotX - side * context.dpf(9f) + val maxW = (kotlin.math.abs(textX - (cx + side * (r + strokeW))) - context.dpf(6f)) + .coerceAtLeast(context.dpf(20f)) + + tagValuePaint.color = color + tagValuePaint.textAlign = if (side > 0) Paint.Align.RIGHT else Paint.Align.LEFT + tagNamePaint.color = color + tagNamePaint.textAlign = tagValuePaint.textAlign + + val value = Dates.durationBrief(tag.slice.seconds) + val name = TextUtils.ellipsize( + tag.slice.name, tagNamePaint, maxW, TextUtils.TruncateAt.END, + ).toString() + + canvas.drawText(value, textX, tag.y - context.dpf(3f), tagValuePaint) + canvas.drawText(name, textX, tag.y + context.dpf(13f), tagNamePaint) + } + + /** 环上的百分比文字:底色偏亮时改黑字,否则看不出来 */ + private fun readableOn(back: Int): Int { + val lum = 0.299f * Color.red(back) + 0.587f * Color.green(back) + 0.114f * Color.blue(back) + return if (lum > 170f) Color.argb(210, 0, 0, 0) else Color.argb(235, 255, 255, 255) + } +} diff --git a/src/main/res/layout/fragment_stats.xml b/src/main/res/layout/fragment_stats.xml index 8ed6431..8433ec0 100644 --- a/src/main/res/layout/fragment_stats.xml +++ b/src/main/res/layout/fragment_stats.xml @@ -20,59 +20,6 @@ android:layout_weight="1" android:text="@string/stats_title" style="@style/T.Title" /> - - - - - - - - - - - - - + - - - - - - - - - - + android:layout_marginTop="12dp" /> - - - - - - - - - - - + android:layout_marginTop="12dp" /> 任务占比 还有 %1$d 个项目 还有 %1$d 个任务 + 日 + 周 + 月 + 年 + %1$s - %2$s + %1$d年%2$d月 + %1$d年 + 其他 + 暂无记录 累计 连续打卡 %1$d 天