Compare commits
74 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
603ad73335 | ||
|
|
94c22bf59c | ||
|
|
9f8714c2b6 | ||
|
|
5dbaafb22d | ||
|
|
11b40553d3 | ||
|
|
0d89f6339d | ||
|
|
aa59407516 | ||
|
|
8d70910a48 | ||
|
|
22dd9334a3 | ||
|
|
6518b0970a | ||
|
|
4788c2353f | ||
|
|
9584603d8b | ||
|
|
787b5db81e | ||
|
|
e0beddaaf5 | ||
|
|
45c6b4fdbf | ||
|
|
9eacf7d87b | ||
|
|
5e882a77ad | ||
|
|
41edf65211 | ||
|
|
44018b8abb | ||
|
|
64dc9d5bac | ||
|
|
49faa9cae8 | ||
|
|
87c95b4b89 | ||
|
|
d8033ef71d | ||
|
|
c712798198 | ||
|
|
ae75410e9b | ||
|
|
234df41f64 | ||
|
|
aad58da3b9 | ||
|
|
0a7d5fda8c | ||
|
|
ec286bcc6b | ||
|
|
853186015d | ||
|
|
1df122af48 | ||
|
|
177c965894 | ||
|
|
c9c7a79349 | ||
|
|
320554381e | ||
|
|
a1e200a1d6 | ||
|
|
256ccfe1ae | ||
|
|
0058efe5df | ||
|
|
6989dc0c68 | ||
|
|
43b12b1bf4 | ||
|
|
fcfd167623 | ||
|
|
44b0baacca | ||
|
|
ce48d805fc | ||
|
|
65f56490e9 | ||
|
|
35a7c4a785 | ||
|
|
ab8840d421 | ||
|
|
ce4ec2cd51 | ||
|
|
467d34afe8 | ||
|
|
256c0d4540 | ||
|
|
30b385a4d9 | ||
|
|
8a7147b299 | ||
|
|
47294f4fcf | ||
|
|
8ad5441ba4 | ||
|
|
9c8e2eb534 | ||
|
|
eb3d961b0a | ||
|
|
9fdecfb1b9 | ||
|
|
a8446bcf51 | ||
|
|
54df5b398c | ||
|
|
8a1f41ca9d | ||
|
|
4a648669ea | ||
|
|
60fd3d1044 | ||
|
|
ed7927af1d | ||
|
|
2d999edc0c | ||
|
|
4e062923ef | ||
|
|
7d8995ead0 | ||
|
|
4444b18b29 | ||
|
|
11dc2825cc | ||
|
|
2dd7f8b506 | ||
|
|
3277fa5826 | ||
|
|
00a01b3f22 | ||
|
|
01ca852b2a | ||
|
|
8e7de267a4 | ||
|
|
9305bd588b | ||
|
|
77319b30da | ||
|
|
8694908305 |
590
CHANGELOG.md
590
CHANGELOG.md
File diff suppressed because it is too large
Load Diff
23
README.md
23
README.md
@@ -1,8 +1,8 @@
|
||||
# FocusBox(时间简史)
|
||||
|
||||
> 仓库:`FocusBox` · 类型:Android 应用 · 版本:`0.5.1` · 作者:石头厝 / XIGE
|
||||
> 仓库:`FocusBox` · 类型:Android 应用 · 版本:`3.4` · 作者:石头厝 / XIGE
|
||||
|
||||
自用安卓番茄钟与任务清单:专注计时(倒计时 / 正计时)、任务与重复计划、项目核算、统计图表。
|
||||
自用安卓番茄钟与任务清单:专注计时(倒计时 / 正计时)、任务与重复计划、项目核算(20 色与类型标签)、统计图表。
|
||||
|
||||
本仓库同步自本地应用源码,**仅包含应用实现代码与必要资源**;不包含依赖、构建工具、编译产物、签名材料、环境配置或备份数据。
|
||||
|
||||
@@ -12,15 +12,22 @@
|
||||
|
||||
## 特性概览
|
||||
|
||||
- **首页**:圆环左右滑动切换倒计时与正计时(两页布局一致、切换不晃动);圆环上下滑动调整本轮时长(5–180 分钟);选任务用两步式底部弹层(先项目后任务),选中后自动套用该任务的专注时长;左侧重置回到本轮起点,右侧完成可填写原因并结束本轮,暂停也记录原因。科技蓝主色贯穿按钮、圆环与图表。
|
||||
- **任务**:标题、备注、项目、优先级、专注时长、截止日期、按天/周/月重复(未完成时按间隔自动滚到当前周期,撤销完成会一并撤掉自动生成的新一条);筛选「全部 / 今日 / 已完成」,今日 = 截止日期正好是今天且未完成 + 今天完成的任务(逾期项只在「全部」里带标记显示);已完成项显示真实起止时分秒与实际专注时长,提前结束原因追加在备注里。
|
||||
- **项目**:八色标记,卡片显示待办数、完成数、累计时长、完成率;编辑、归档、删除及删除确认使用圆角底部弹层,删除时任务回收至收件箱。
|
||||
- **统计**:今日目标环、最近 7 天趋势、12 周专注频率热力图、项目分布与任务分布(各自带 日 / 周 / 月 / 年 与左右翻页,环形图外侧引线标注分类时长与占比)、累计四项。
|
||||
- **计时可靠性**:只保存结束时间戳,剩余时间现算;前台服务 + 系统 Chronometer 通知,息屏、锁屏、切后台均继续走时。
|
||||
- **通知**:自定义布局(任务名 / 系统计时器 / 暂停与结束图标,两颗按钮之间留空),状态栏常驻秒表图标,不显示中文状态文案。应用显示名为「时间简史」,图标为 Things 蓝底白色时钟。
|
||||
- **首页(专注)**:圆环左右滑动切换倒计时与正计时(两页布局一致、切换不晃动);圆环上下滑动调整本轮时长(5–180 分钟);选任务用两步式底部弹层(先项目后任务),选中任务即自动开始计时,计时中任务卡显示「正在专注」且不可点,本轮结束/复位后恢复。右侧按钮随计时方向换形态:正计时是「结束」(点一下直接停表收尾,不弹原因),倒计时是「完成」(提前完成并填写原因,原因写入该轮完成记录备注);暂停同样记录原因。科技蓝主色贯穿按钮、圆环与图表。
|
||||
- **任务**:标题、备注、项目、优先级、专注时长(数字可点击直接输入,5–180 分钟)、截止日期、按天/周/月重复。默认筛选「今日」(未完成按截止日、含逾期;已完成按完成时刻),状态「全部」下同一任务——含重复系列与多轮完成记录——只占一行:还有未完成显示最新待办,全部完成显示最近一条完成记录;「已完成」视图看全量历史。完成记录行点勾选圈可撤销完成(源任务回待办,专注时长仍留在统计)。重复任务不计逾期;修改重复设置会写穿整条系列,改成「不重复」后不会复活。新建任务默认截止今天。
|
||||
- **项目**:20 色标记(两两色差 ΔE00 ≥ 15)与类型标签(默认工作/学习/娱乐/提升,设置页可增删改);卡片显示类型、任务数、累计时长、已完成次数;卡片三点菜单支持 编辑 / 新建任务 / 归档 / 删除;删除 = 任务与专注记录一并真删。
|
||||
- **统计**:今日目标环(达成允许超 100%)、今日累计时长 / 番茄数 / 任务数(完成任务只认真实专注记录并按系列去重)、最近 7 天趋势、12 周专注频率热力图、类型 / 项目 / 任务三张分布卡(日 / 周 / 月 / 年 + 环形图外侧引线标注占比最高 6 条,其余切片不合并、在下方两列明细完整列出;左右翻页带下界)、累计四项。
|
||||
- **数据安全**:删除即真删;系统自动备份已关闭(`allowBackup=false`),换机/重装不会带回已删除的数据;设置页「导出数据」走系统文件选择器导出项目 / 任务 / 专注记录三张表的 JSON,不需要存储权限。
|
||||
- **计时可靠性**:只保存结束时间戳,剩余时间现算(系统校时跳变用单调钟兜底);前台服务 + 系统 Chronometer 通知,息屏、锁屏、切后台均继续走时;跨零点滚动与系列自检在后台线程执行,不阻塞界面。
|
||||
- **通知**:自定义布局(任务名 / 系统计时器 / 暂停与结束图标),状态栏常驻秒表图标;通知「结束」先恢复前台再收尾,Android 8+ 不再抛 RemoteServiceException。应用显示名为「时间简史」,图标为 Things 蓝底白色时钟。
|
||||
|
||||
目标机型:华为 P30 / HarmonyOS 4.0(Android 12 / API 31),minSdk 24、targetSdk 34,无 Google 服务依赖。
|
||||
|
||||
## 版本号规则
|
||||
|
||||
- 对外发布版本:v3.0 → v3.1 → v3.2 → v3.3 → **v3.4**(versionCode 82,严格递增)。
|
||||
- 发布号之间的内部小版本为 3.41、3.42…,只做日常提交,不单独发布;发布节奏由作者手动控制。
|
||||
- 发布产物以 versionCode 为准,versionName 仅作展示。
|
||||
|
||||
## 构建说明
|
||||
|
||||
1. 按 Android 项目结构将 `src/main/` 放回 `app/src/main/`,自行补齐 `build.gradle.kts`、`settings.gradle.kts` 与 Gradle Wrapper。
|
||||
|
||||
@@ -23,8 +23,7 @@
|
||||
|
||||
<application
|
||||
android:name=".App"
|
||||
android:allowBackup="true"
|
||||
android:fullBackupContent="true"
|
||||
android:allowBackup="false"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:label="@string/app_name"
|
||||
android:roundIcon="@mipmap/ic_launcher"
|
||||
|
||||
@@ -5,12 +5,15 @@ import androidx.appcompat.app.AppCompatDelegate
|
||||
import com.focusbox.app.data.Store
|
||||
import com.focusbox.app.service.Notif
|
||||
import com.focusbox.app.service.TimerCore
|
||||
import com.focusbox.app.util.Dates
|
||||
import com.focusbox.app.util.Prefs
|
||||
|
||||
class App : Application() {
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
// 先把资源交给 Dates:Store / 统计页在初始化阶段就可能格式化时长
|
||||
Dates.attach(resources)
|
||||
Prefs.init(this)
|
||||
Store.init(this)
|
||||
// 重复任务按间隔滚到当前周期:冷启动就补齐,避免过期后不再出现在清单里
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,6 @@
|
||||
package com.focusbox.app.model
|
||||
|
||||
/** 项目(清单)。收件箱固定 id=1,不可删除。 */
|
||||
/** 项目(清单)。id=0 表示未分类,不对应项目行;项目行均可编辑/归档/删除。 */
|
||||
data class Project(
|
||||
val id: Long,
|
||||
val name: String,
|
||||
@@ -8,13 +8,23 @@ data class Project(
|
||||
val archived: Boolean,
|
||||
val sort: Int,
|
||||
val openTasks: Int,
|
||||
/**
|
||||
* 任务本体中已完成的数量,只用于「任务总数」与进度条。
|
||||
*
|
||||
* 只数一次性任务(repeat_type = 0):重复任务的根任务每跨一个周期就会被
|
||||
* autoFinishSeries 标成 done,算进来的话进度条会长期虚高,第二天就自己满了。
|
||||
*/
|
||||
val doneTasks: Int,
|
||||
/** 累计专注秒数(该项目下所有专注记录之和,含重复实例) */
|
||||
val focusSeconds: Int,
|
||||
/** 累计真实完成次数(已完成专注记录的条数),项目页「已完成N次」展示用 */
|
||||
val pomodoros: Int,
|
||||
/** 排序序号:非置顶项目按它升序排,数字越小越靠前 */
|
||||
val sortIndex: Int = 0,
|
||||
/** 置顶时间戳:0 未置顶;置顶项目排最前,多个置顶按它倒序(越近越靠前) */
|
||||
val pinnedAt: Long = 0,
|
||||
/** 项目类型(工作/学习/娱乐/提升或自定义),空串表示未设置;统计页类型分布按它归并 */
|
||||
val type: String = "",
|
||||
) {
|
||||
val totalTasks: Int get() = openTasks + doneTasks
|
||||
val progress: Float get() = if (totalTasks == 0) 0f else doneTasks.toFloat() / totalTasks
|
||||
@@ -62,6 +72,30 @@ data class Task(
|
||||
/** 一条专注记录的起止时刻与实际秒数,用于在已完成任务上显示真实工作时段。 */
|
||||
data class SessionSpan(val startAt: Long, val endAt: Long, val seconds: Int = 0)
|
||||
|
||||
/**
|
||||
* 项目卡展开后的一条任务行:任务本体 + 三项统计。
|
||||
* 仅用于项目页展开列表,任务页的 Task 口径不变。
|
||||
*/
|
||||
data class ProjectTaskStat(
|
||||
val task: Task,
|
||||
/** 最近一次完成时刻(源任务 done_at 与该任务 sessions 最近 end_at 取大),0 表示未完成过 */
|
||||
val lastDoneAt: Long,
|
||||
/** 累计完成次数(done_pomodoros;勾选完成且无 session 时至少 1) */
|
||||
val doneCount: Int,
|
||||
/** 累计专注秒数(sessions 里该任务的 seconds 之和) */
|
||||
val focusSeconds: Int,
|
||||
)
|
||||
|
||||
/** 项目页一条完成记录:对应一条已完成的任务行(与任务页完成记录同源)。 */
|
||||
data class ProjectCompletion(
|
||||
val taskId: Long,
|
||||
val taskTitle: String,
|
||||
val note: String,
|
||||
val startAt: Long,
|
||||
val endAt: Long,
|
||||
val seconds: Int,
|
||||
)
|
||||
|
||||
/** 提前完成时交给 UI 落备注的实际专注信息 */
|
||||
data class FocusFinish(
|
||||
val taskId: Long,
|
||||
@@ -103,6 +137,13 @@ data class TodayStat(
|
||||
val doneTasks: Int = 0,
|
||||
val goalMinutes: Int = 120,
|
||||
) {
|
||||
/**
|
||||
* 真实达成率:按今日实际专注分钟数除以目标分钟数,**不设 100% 上限**。
|
||||
* 圆环自身把进度夹紧到 1(满圈就是满圈),顶部文字走 [goalPercent] 显示真实值。
|
||||
*/
|
||||
val goalProgress: Float
|
||||
get() = if (goalMinutes <= 0) 0f else (minutes.toFloat() / goalMinutes).coerceIn(0f, 1f)
|
||||
get() = if (goalMinutes <= 0) 0f else (minutes.toFloat() / goalMinutes).coerceAtLeast(0f)
|
||||
|
||||
/** 展示用百分比:四舍五入,可以超过 100 */
|
||||
val goalPercent: Int get() = Math.round(goalProgress * 100f)
|
||||
}
|
||||
|
||||
@@ -46,11 +46,14 @@ object LockOverlay {
|
||||
/** 显示(幂等):已在显示或无权限时不重复添加 */
|
||||
fun show(context: Context) {
|
||||
if (root != null || !canShow(context)) return
|
||||
val ctx = context.applicationContext
|
||||
val manager = ctx.getSystemService(Context.WINDOW_SERVICE) as WindowManager
|
||||
var view: View? = null
|
||||
var added = false
|
||||
try {
|
||||
val ctx = context.applicationContext
|
||||
val manager = ctx.getSystemService(Context.WINDOW_SERVICE) as WindowManager
|
||||
val view = LayoutInflater.from(ctx).inflate(R.layout.activity_lock_screen, null)
|
||||
view.setOnClickListener { hide() }
|
||||
val v = LayoutInflater.from(ctx).inflate(R.layout.activity_lock_screen, null)
|
||||
view = v
|
||||
v.setOnClickListener { hide() }
|
||||
|
||||
// API 26+ 用应用悬浮窗类型;更旧版本退回 TYPE_PHONE(本应用 minSdk 24)
|
||||
val type = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
@@ -81,13 +84,19 @@ object LockOverlay {
|
||||
lp.gravity = Gravity.TOP
|
||||
lp.x = 0
|
||||
lp.y = -statusBar
|
||||
manager.addView(view, lp)
|
||||
manager.addView(v, lp)
|
||||
added = true
|
||||
|
||||
root = view
|
||||
root = v
|
||||
wm = manager
|
||||
orientation = ctx.resources.configuration.orientation
|
||||
render(view)
|
||||
render(v)
|
||||
} catch (_: Exception) {
|
||||
// addView 成功之后再抛异常(例如 render 里找控件)时,窗口已经挂在屏幕上了。
|
||||
// 之前只把 root 置空,窗口却留着 → isShowing() 返回 false,谁也关不掉它,
|
||||
// 用户只能重启手机。这里必须先把窗口摘掉再清状态。
|
||||
val v = view
|
||||
if (added && v != null) runCatching { manager.removeView(v) }
|
||||
root = null
|
||||
wm = null
|
||||
}
|
||||
|
||||
@@ -247,7 +247,8 @@ object Notif {
|
||||
.setOngoing(true)
|
||||
.setCategory(NotificationCompat.CATEGORY_ALARM)
|
||||
.setPriority(NotificationCompat.PRIORITY_HIGH)
|
||||
.setAutoCancel(true)
|
||||
// 不配 setAutoCancel:与 setOngoing(true) 互相矛盾(常驻通知点不掉),
|
||||
// 留着只会让人误以为点了会自己消失
|
||||
.build()
|
||||
runCatching { NotificationManagerCompat.from(context).notify(ID_FULLSCREEN, n) }
|
||||
}
|
||||
|
||||
@@ -189,11 +189,32 @@ object TimerCore {
|
||||
// 时间够长就按结束时刻补记,不够就当没发生过,绝不虚增统计。
|
||||
val finishedAt = endAt.takeIf { it > 0 } ?: System.currentTimeMillis()
|
||||
val elapsed = finishedAt - startedAt
|
||||
val counted = mode == MODE_FOCUS && startedAt > 0 && elapsed >= totalMs * 9 / 10
|
||||
running = false
|
||||
if (mode == MODE_FOCUS && startedAt > 0 && elapsed >= totalMs * 9 / 10) {
|
||||
record((totalMs / 1000).toInt(), completed = true, endMs = finishedAt)
|
||||
if (counted) {
|
||||
val seconds = (totalMs / 1000).toInt()
|
||||
record(seconds, completed = true, endMs = finishedAt)
|
||||
// 与 complete() 的收尾完全对齐:这一轮既然算进统计,完成记录里
|
||||
// 就必须有一条对应的行,否则会出现「统计里有、记录里没有」,
|
||||
// 任务在任务页和项目页都还显示未完成。
|
||||
if (taskId > 0) {
|
||||
runCatching {
|
||||
Store.addCompletionRecord(
|
||||
sourceId = taskId,
|
||||
note = (roundNotes + ctx.getString(R.string.task_note_recovered))
|
||||
.joinToString("\n"),
|
||||
startAt = startedAt,
|
||||
endAt = finishedAt,
|
||||
seconds = seconds,
|
||||
)
|
||||
}
|
||||
// 与「提前完成」同一口径:这一轮跑完就是这条任务本轮结束
|
||||
runCatching { Store.finishSeries(taskId) }
|
||||
}
|
||||
round += 1
|
||||
}
|
||||
// 这一轮已经结束(无论算不算数),暂存的暂停备注都不能留给下一轮
|
||||
clearRoundNotes()
|
||||
remainingMs = durationFor(mode)
|
||||
startedAt = 0
|
||||
endAt = 0
|
||||
@@ -448,9 +469,26 @@ object TimerCore {
|
||||
if (countUp) {
|
||||
val elapsedMs = displayNow()
|
||||
val elapsed = (elapsedMs / 1000).toInt()
|
||||
val startMs = System.currentTimeMillis() - elapsedMs
|
||||
// 正计时暂停后 startedAt 已归零,这里按实际累计时长反推起点
|
||||
if (elapsed >= 60) {
|
||||
record(elapsed, completed = false, startMs = System.currentTimeMillis() - elapsedMs)
|
||||
record(elapsed, completed = false, startMs = startMs)
|
||||
// 秒表停下来代表这一轮结束,与倒计时自然完成同口径收尾:
|
||||
// 写一条完成记录副本并把源任务标成已完成。之前只写 session,
|
||||
// 于是「专注页跑完了、任务页还挂一条未完成」,也没有完成记录可查。
|
||||
// completed 仍记 0:正计时不判是否达标,只表示这段时间确实专注过。
|
||||
if (taskId > 0 && mode == MODE_FOCUS) {
|
||||
runCatching {
|
||||
Store.addCompletionRecord(
|
||||
sourceId = taskId,
|
||||
note = roundNotes.joinToString("\n"),
|
||||
startAt = startMs,
|
||||
endAt = System.currentTimeMillis(),
|
||||
seconds = elapsed,
|
||||
)
|
||||
}
|
||||
runCatching { Store.finishSeries(taskId) }
|
||||
}
|
||||
}
|
||||
running = false
|
||||
endAt = 0
|
||||
@@ -512,9 +550,10 @@ object TimerCore {
|
||||
seconds = seconds,
|
||||
)
|
||||
}
|
||||
// 完成按钮 = 这次任务做完了:源任务从列表消失,历史在「已完成」视图看;
|
||||
// 重复任务不用管,跨零点后 rollRepeatingTasks 会按周期生成新实例
|
||||
Store.setTaskDone(taskId, true)
|
||||
// 完成按钮 = 这次任务做完了:系列里所有待办行(根 + 当前轮实例)一起收尾,
|
||||
// 未完成列表不再残留自动生成的实例;重复任务跨零点后
|
||||
// rollRepeatingTasks 会按周期生成新实例,节奏不受影响
|
||||
Store.finishSeries(taskId)
|
||||
}
|
||||
clearRoundNotes()
|
||||
running = false
|
||||
@@ -553,35 +592,6 @@ object TimerCore {
|
||||
TimerService.stop(ctx)
|
||||
}
|
||||
|
||||
/** 跳过:专注跳过不算完成,休息跳过直接进入专注 */
|
||||
fun skip() {
|
||||
if (countUp) {
|
||||
stopEarly()
|
||||
return
|
||||
}
|
||||
if (mode == MODE_FOCUS) {
|
||||
val elapsed = elapsedSec()
|
||||
if (elapsed >= 60 && startedAt > 0) record(elapsed, completed = false)
|
||||
running = false
|
||||
endAt = 0
|
||||
startedAt = 0
|
||||
advanceFromFocus()
|
||||
} else {
|
||||
running = false
|
||||
endAt = 0
|
||||
startedAt = 0
|
||||
mode = MODE_FOCUS
|
||||
totalMs = durationFor(MODE_FOCUS)
|
||||
remainingMs = totalMs
|
||||
}
|
||||
clearPause()
|
||||
clearRoundNotes()
|
||||
save()
|
||||
cancelDeadlineAlarm()
|
||||
notifyChanged()
|
||||
TimerService.stop(ctx)
|
||||
}
|
||||
|
||||
/** 由前台服务每秒调用 */
|
||||
fun tick() {
|
||||
if (!running || countUp) return
|
||||
@@ -622,6 +632,10 @@ object TimerCore {
|
||||
)
|
||||
}
|
||||
}
|
||||
// 与「提前完成」同一口径:一轮专注跑完 = 这条任务本轮结束。
|
||||
// 收掉系列全部待办行(根 + 当前轮实例),不标记的话会出现
|
||||
// 「专注页已完成、任务页仍挂一条未完成」的两套状态。
|
||||
if (taskId > 0) runCatching { Store.finishSeries(taskId) }
|
||||
clearRoundNotes()
|
||||
round += 1
|
||||
}
|
||||
@@ -697,23 +711,26 @@ object TimerCore {
|
||||
}
|
||||
|
||||
private fun save() {
|
||||
Prefs.timerMode = mode
|
||||
Prefs.timerRunning = running
|
||||
Prefs.timerCountUp = countUp
|
||||
Prefs.timerTotalMs = totalMs
|
||||
Prefs.timerRemainingMs = remainingMs
|
||||
Prefs.timerEndAt = endAt
|
||||
Prefs.timerEndElapsed = if (endAt > 0) endElapsed else 0L
|
||||
Prefs.timerClockOffset = clockOffset
|
||||
Prefs.timerPauseReason = pendingPauseReason
|
||||
Prefs.timerPauseStartAt = pendingPauseStartAt
|
||||
Prefs.timerPauseTaskId = pendingPauseTaskId
|
||||
Prefs.timerRoundNotes = roundNotes.joinToString("\n")
|
||||
Prefs.timerStartedAt = startedAt
|
||||
Prefs.timerTaskId = taskId
|
||||
Prefs.timerProjectId = projectId
|
||||
Prefs.timerRound = round
|
||||
Prefs.timerAccumMs = accumMs
|
||||
// 一次 Editor 提交代替逐字段 setter(原来要 apply() 十七次)
|
||||
Prefs.saveTimer(
|
||||
mode = mode,
|
||||
running = running,
|
||||
countUp = countUp,
|
||||
totalMs = totalMs,
|
||||
remainingMs = remainingMs,
|
||||
endAt = endAt,
|
||||
endElapsed = if (endAt > 0) endElapsed else 0L,
|
||||
clockOffset = clockOffset,
|
||||
pauseReason = pendingPauseReason,
|
||||
roundNotes = roundNotes.joinToString("\n"),
|
||||
pauseStartAt = pendingPauseStartAt,
|
||||
pauseTaskId = pendingPauseTaskId,
|
||||
startedAt = startedAt,
|
||||
taskId = taskId,
|
||||
projectId = projectId,
|
||||
round = round,
|
||||
accumMs = accumMs,
|
||||
)
|
||||
}
|
||||
|
||||
fun resetRound() {
|
||||
|
||||
@@ -55,7 +55,9 @@ class TimerService : Service() {
|
||||
TimerCore.tick()
|
||||
// 锁屏悬浮窗的读数刷新(窗口存在时每秒重画日期/时钟/倒计时)
|
||||
LockOverlay.update(this@TimerService)
|
||||
handler.postDelayed(this, 1000L)
|
||||
// 不再无条件续命:正计时只在锁屏窗口存在时才需要每秒重画,
|
||||
// 窗口关了就该停,长时间正计时不该一直空转
|
||||
if (needTicker()) handler.postDelayed(this, 1000L) else stopTicker()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -112,6 +114,8 @@ class TimerService : Service() {
|
||||
&& (TimerCore.running || TimerCore.displayNow() > 0)
|
||||
if (want) LockOverlay.show(this) else LockOverlay.hide()
|
||||
if (LockOverlay.isShowing()) Notif.cancelFullscreen(this)
|
||||
// 悬浮窗显隐直接决定正计时要不要每秒刷新(见 needTicker)
|
||||
syncTicker()
|
||||
}
|
||||
|
||||
/** 灭屏:先补结算,悬浮窗可用就直接盖到锁屏上(保持熄屏,按电源键即见);不可用走全屏意图兜底 */
|
||||
@@ -177,9 +181,15 @@ class TimerService : Service() {
|
||||
syncTicker()
|
||||
}
|
||||
ACTION_STOP -> {
|
||||
// 先补前台化再收尾:这条 intent 可能由 startForegroundService() 拉起,
|
||||
// Android 8+ 要求 5 秒内必须 startForeground(),否则抛
|
||||
// RemoteServiceException("did not then call startForeground")。
|
||||
// 原实现在这里直接 stopSelf,把前台化整个跳过了。
|
||||
startForegroundCompat()
|
||||
// 休息是纯计时:通知上的"结束"也走 endBreak,不产生任何记录
|
||||
if (TimerCore.mode == TimerCore.MODE_FOCUS) TimerCore.stopEarly() else TimerCore.endBreak()
|
||||
stopTicker()
|
||||
stopForeground(STOP_FOREGROUND_REMOVE)
|
||||
stopSelf()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
@@ -195,12 +205,20 @@ class TimerService : Service() {
|
||||
}
|
||||
|
||||
/**
|
||||
* 只有倒计时需要每秒推进(判断是否到点)。
|
||||
* 正计时靠时间戳现算、通知靠系统 Chronometer 走时,
|
||||
* 既不用轮询也不用占着 WakeLock,长时间正计时不会白耗电。
|
||||
* 是否需要每秒跑一次 ticker。
|
||||
*
|
||||
* 倒计时必须跑(判断是否到点);正计时靠时间戳现算、通知靠系统 Chronometer 走时,
|
||||
* 平时不需要轮询——但锁屏悬浮窗/锁屏页的读数是 Canvas/TextView 自己画的,
|
||||
* 只有 ticker 会去重画。原来 ticker 只对倒计时启动,正计时一锁屏数字就冻住了。
|
||||
*/
|
||||
private fun needTicker(): Boolean {
|
||||
if (!TimerCore.running) return false
|
||||
if (!TimerCore.countUp) return true
|
||||
return LockOverlay.isShowing() || LockScreenActivity.showing
|
||||
}
|
||||
|
||||
private fun syncTicker() {
|
||||
if (TimerCore.running && !TimerCore.countUp) startTicker() else stopTicker()
|
||||
if (needTicker()) startTicker() else stopTicker()
|
||||
}
|
||||
|
||||
/** EMUI 偶发拒绝前台启动时的自愈重试标记:只重试一次,避免无限循环 */
|
||||
|
||||
@@ -27,6 +27,7 @@ import com.focusbox.app.ui.tasks.TasksFragment
|
||||
import com.focusbox.app.util.col
|
||||
import com.focusbox.app.util.dpi
|
||||
import com.focusbox.app.util.tint
|
||||
import java.util.concurrent.Executors
|
||||
|
||||
/**
|
||||
* 单 Activity + 五个常驻 Fragment。
|
||||
@@ -105,22 +106,46 @@ class MainActivity : AppCompatActivity() {
|
||||
super.onSaveInstanceState(outState)
|
||||
}
|
||||
|
||||
/** 前台每 60 秒检查一次跨零点,重复任务在 0 点后自动生成当日实例 */
|
||||
private val rollHandler = Handler(Looper.getMainLooper())
|
||||
|
||||
/**
|
||||
* 跨零点滚动与系列自检都要写库:放到后台单线程执行,跑完回主线程刷列表。
|
||||
*
|
||||
* 之前直接在 onResume 和 60 秒定时器里跑,自检对每个系列根发两次查询,
|
||||
* 系列一多就会顶住主线程(首帧掉帧、滚动发涩)。SQLite 同连接内部串行,跨线程安全。
|
||||
*/
|
||||
private val rollExecutor = Executors.newSingleThreadExecutor { r ->
|
||||
Thread(r, "fb-roll").apply { isDaemon = true }
|
||||
}
|
||||
private var rolling = false
|
||||
|
||||
private fun rollAsync() {
|
||||
if (rolling) return
|
||||
rolling = true
|
||||
rollExecutor.execute {
|
||||
val changed = runCatching { Store.rollRepeatingTasks() }.getOrDefault(0)
|
||||
rollHandler.post {
|
||||
rolling = false
|
||||
if (changed > 0 && !isFinishing) {
|
||||
(fragments[TAB_TASKS] as? TasksFragment)?.reload()
|
||||
(fragments[TAB_PROJECTS] as? ProjectsFragment)?.reload()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 前台每 60 秒检查一次跨零点,重复任务在 0 点后自动生成当日实例 */
|
||||
private val rollRunner = object : Runnable {
|
||||
override fun run() {
|
||||
if (runCatching { Store.rollRepeatingTasks() }.getOrDefault(0) > 0) {
|
||||
(fragments[TAB_TASKS] as? TasksFragment)?.reload()
|
||||
(fragments[TAB_PROJECTS] as? ProjectsFragment)?.reload()
|
||||
}
|
||||
rollAsync()
|
||||
rollHandler.postDelayed(this, 60_000L)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
// 进程常驻时跨天不会重走 App.onCreate,回到前台再滚一次重复任务。
|
||||
// 放在 super 之前:片段 onResume 里的 reload 读到的就是推进后的日期。
|
||||
runCatching { Store.rollRepeatingTasks() }
|
||||
// 滚动本身放后台,完成后由回调回主线程刷新任务页与项目页。
|
||||
rollAsync()
|
||||
// 打开/回到前台默认停在专注页;休息正在计时时不打断
|
||||
if (!TimerCore.running && TimerCore.mode != TimerCore.MODE_FOCUS) {
|
||||
runCatching { TimerCore.setMode(TimerCore.MODE_FOCUS) }
|
||||
@@ -135,6 +160,12 @@ class MainActivity : AppCompatActivity() {
|
||||
super.onPause()
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
rollHandler.removeCallbacks(rollRunner)
|
||||
rollExecutor.shutdownNow()
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
override fun onNewIntent(intent: Intent?) {
|
||||
super.onNewIntent(intent)
|
||||
val tab = intent?.getIntExtra(EXTRA_TAB, -1) ?: -1
|
||||
@@ -254,6 +285,15 @@ class MainActivity : AppCompatActivity() {
|
||||
showTab(TAB_FOCUS)
|
||||
}
|
||||
|
||||
/**
|
||||
* 按任务 id 开始计时,供项目页的完成记录行使用:
|
||||
* 记录行本身是已完成的行,先经 [Store.startTargetFor] 换成系列里可计时的任务。
|
||||
*/
|
||||
fun startFocusFrom(taskId: Long) {
|
||||
val target = Store.startTargetFor(taskId) ?: return
|
||||
startFocusOn(target)
|
||||
}
|
||||
|
||||
/** 设置改动后(清空数据、改主题)统一刷新其余页面 */
|
||||
fun refreshAll() {
|
||||
for (f in fragments) {
|
||||
@@ -261,6 +301,9 @@ class MainActivity : AppCompatActivity() {
|
||||
is TasksFragment -> f.reload()
|
||||
is ProjectsFragment -> f.reload()
|
||||
is StatsFragment -> f.reload()
|
||||
// 专注页缓存着任务名与项目色,清空/批量改动后必须重读,
|
||||
// 否则切过去还挂着已经被删掉的任务(要等进程重启才消失)
|
||||
is FocusFragment -> f.reloadTask()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,11 +26,13 @@ import com.focusbox.app.model.Project
|
||||
import com.focusbox.app.model.Task
|
||||
import com.focusbox.app.service.TimerCore
|
||||
import com.focusbox.app.ui.SheetDialog
|
||||
import com.focusbox.app.ui.tasks.TaskSheet
|
||||
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.projectMetaLine
|
||||
import com.focusbox.app.util.roundBg
|
||||
import com.focusbox.app.util.tint
|
||||
import com.focusbox.app.util.visible
|
||||
@@ -147,7 +149,11 @@ class FocusFragment : Fragment(R.layout.fragment_focus) {
|
||||
TimerCore.reset()
|
||||
render()
|
||||
}
|
||||
btnFinish.setOnClickListener { showFinishSheet() }
|
||||
// 正计时的右侧按钮是「结束」:点一下直接走正常结束流程,没有"提前"一说;
|
||||
// 倒计时仍是「提前完成」,保留原因输入框
|
||||
btnFinish.setOnClickListener {
|
||||
if (TimerCore.countUp) endCountUp() else showFinishSheet()
|
||||
}
|
||||
taskCard.setOnClickListener { pickTask() }
|
||||
segFocus.setOnClickListener {
|
||||
if (!TimerCore.running) {
|
||||
@@ -197,6 +203,12 @@ class FocusFragment : Fragment(R.layout.fragment_focus) {
|
||||
}
|
||||
}
|
||||
|
||||
/** 数据被清空或批量改动后由 Activity 调用:丢掉任务缓存并按当前状态重画 */
|
||||
fun reloadTask() {
|
||||
cachedTaskId = Long.MIN_VALUE
|
||||
if (view != null) render()
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 绘制
|
||||
|
||||
private fun buildPageDots() {
|
||||
@@ -236,7 +248,16 @@ class FocusFragment : Fragment(R.layout.fragment_focus) {
|
||||
btnFinish.visibility = if (focusMode) View.VISIBLE else View.INVISIBLE
|
||||
taskCard.visible(focusMode)
|
||||
dots.visibility = View.VISIBLE
|
||||
btnFinish.contentDescription = getString(R.string.finish)
|
||||
// 右侧按钮随计时方向换形态:正计时=结束,倒计时=完成。
|
||||
// 用 tag 记住当前形态,避免每 250ms 重建一次 drawable。
|
||||
val endMode = focusMode && TimerCore.countUp
|
||||
if (btnFinish.tag != endMode) {
|
||||
btnFinish.tag = endMode
|
||||
btnFinish.setImageResource(if (endMode) R.drawable.ic_end else R.drawable.ic_finish)
|
||||
btnFinish.tint(col(R.color.text_secondary))
|
||||
btnFinish.contentDescription =
|
||||
getString(if (endMode) R.string.end_timing else R.string.finish)
|
||||
}
|
||||
|
||||
btnMain.text = when {
|
||||
!focusMode -> getString(if (TimerCore.running) R.string.end_break else R.string.start_break)
|
||||
@@ -333,6 +354,22 @@ class FocusFragment : Fragment(R.layout.fragment_focus) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 正计时结束:秒表停下就是这一轮结束,直接按正常结束流程收尾
|
||||
* (写专注记录、任务标记完成、停表复位),不弹原因输入框 ——
|
||||
* 正计时没有"计划时长",也就谈不上"提前"。
|
||||
*/
|
||||
private fun endCountUp() {
|
||||
if (TimerCore.mode != TimerCore.MODE_FOCUS) return
|
||||
if (TimerCore.elapsedNow() <= 0) {
|
||||
Toast.makeText(requireContext(), R.string.finish_need_start, Toast.LENGTH_SHORT).show()
|
||||
return
|
||||
}
|
||||
TimerCore.stopEarly()
|
||||
(activity as? com.focusbox.app.ui.MainActivity)?.refreshAll()
|
||||
render()
|
||||
}
|
||||
|
||||
/** 暂停也记原因;起止时段在点击"继续"时补齐并写入任务备注 */
|
||||
private fun showPauseSheet() {
|
||||
reasonSheet(
|
||||
@@ -386,6 +423,8 @@ class FocusFragment : Fragment(R.layout.fragment_focus) {
|
||||
lp.marginStart = dpi(4f)
|
||||
lp.marginEnd = dpi(4f)
|
||||
v.layoutParams = lp
|
||||
// 轮次圆点只是进度装饰,读屏挨个念一遍反而吵
|
||||
v.importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO
|
||||
dots.addView(v)
|
||||
}
|
||||
}
|
||||
@@ -404,6 +443,10 @@ class FocusFragment : Fragment(R.layout.fragment_focus) {
|
||||
cachedProject = cachedTask?.let { Store.project(it.projectId) }
|
||||
}
|
||||
val task = cachedTask
|
||||
// 专注进行中,任务已经绑进这一轮:右侧文案改成「正在专注」,整卡不可点。
|
||||
// 否则中途换任务会把 elapsed 清零重建(setTask 会重设 totalMs),这一轮就白跑了。
|
||||
val locked = TimerCore.running && TimerCore.mode == TimerCore.MODE_FOCUS && task != null
|
||||
taskCard.isClickable = !locked
|
||||
if (task == null) {
|
||||
taskDot.visible(false)
|
||||
tvTask.text = getString(R.string.no_task)
|
||||
@@ -417,7 +460,7 @@ class FocusFragment : Fragment(R.layout.fragment_focus) {
|
||||
tvTask.text = task.title
|
||||
val projectName = project?.name ?: getString(R.string.inbox)
|
||||
tvTaskMeta.text = getString(R.string.task_card_meta, projectName, task.focusMinutes, task.donePomodoros)
|
||||
tvTaskAction.text = getString(R.string.task_selected)
|
||||
tvTaskAction.text = getString(if (locked) R.string.task_focusing else R.string.task_selected)
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 手势
|
||||
@@ -487,6 +530,39 @@ class FocusFragment : Fragment(R.layout.fragment_focus) {
|
||||
|
||||
// ------------------------------------------------------------------ 任务
|
||||
|
||||
/**
|
||||
* 选任务弹层第二步底部的「立即创建」:拉起新建任务弹层。
|
||||
*
|
||||
* [projectId] 是刚才在第二步看到的那个项目 —— 用户都已经点进这个项目的任务列表了,
|
||||
* 新建的任务必然属于它,所以弹层里直接预选好项目,不用再选一次。
|
||||
*
|
||||
* 保存成功后把新任务设为当前任务(圆环套用它设定的专注时长),
|
||||
* 与「选中已有任务」一样停在这一页等用户点开始,方便先调时长。
|
||||
*/
|
||||
/**
|
||||
* 「立即创建」:建完任务后自动选中并停在这一页,**不自动开始**。
|
||||
*
|
||||
* 与选任务弹层同一个口径:选中只是把圆环换成该任务的时长,
|
||||
* 还要让人有机会上下拖动调整,所以开跑仍然由主按钮触发。
|
||||
*/
|
||||
private fun createTaskAndSelect(projectId: Long) {
|
||||
val ctx = context ?: return
|
||||
val act = activity
|
||||
val sheet = TaskSheet(ctx, null, projectId) { newId ->
|
||||
if (newId > 0) {
|
||||
Store.task(newId)?.let { t ->
|
||||
TimerCore.setCountUp(false)
|
||||
TimerCore.setTask(t.id, t.projectId, t.focusMinutes)
|
||||
Toast.makeText(ctx, R.string.task_created, Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
cachedTaskId = Long.MIN_VALUE
|
||||
(act as? com.focusbox.app.ui.MainActivity)?.refreshAll()
|
||||
}
|
||||
if (view != null) render()
|
||||
}
|
||||
sheet.show()
|
||||
}
|
||||
|
||||
/**
|
||||
* 选择任务:第一步选项目,第二步只列出该项目的待办。
|
||||
* 用自绘底部弹层而不是系统 AlertDialog,便于圆角、分步标题与选中态。
|
||||
@@ -508,7 +584,7 @@ class FocusFragment : Fragment(R.layout.fragment_focus) {
|
||||
|
||||
fun addRow(
|
||||
title: String,
|
||||
meta: String,
|
||||
meta: CharSequence,
|
||||
color: Int?,
|
||||
selected: Boolean,
|
||||
alignLeft: Boolean = false,
|
||||
@@ -534,8 +610,12 @@ class FocusFragment : Fragment(R.layout.fragment_focus) {
|
||||
list.addView(row)
|
||||
}
|
||||
|
||||
// 第二步当前停留的项目:底部的「立即创建」要把它带进新建任务弹层
|
||||
var pickedProjectId = 0L
|
||||
|
||||
// 局部函数必须先声明后引用:showTasks 在前,showProjects 的点击回调才能调用它
|
||||
fun showTasks(projectId: Long) {
|
||||
pickedProjectId = projectId
|
||||
val project = Store.project(projectId)
|
||||
tvTitle.text = project?.name ?: getString(R.string.inbox)
|
||||
tvStep.text = getString(R.string.pick_step, 2)
|
||||
@@ -543,7 +623,8 @@ class FocusFragment : Fragment(R.layout.fragment_focus) {
|
||||
btnBack.visibility = View.VISIBLE
|
||||
btnClear.visibility = View.VISIBLE
|
||||
list.removeAllViews()
|
||||
val tasks = Store.tasks(projectId, includeDone = false)
|
||||
// 选任务只按项目列任务:不按完成、逾期过滤,也不显示完成记录
|
||||
val tasks = Store.projectTasks(projectId)
|
||||
if (tasks.isEmpty()) {
|
||||
list.addView(TextView(ctx).apply {
|
||||
text = getString(R.string.pick_task_empty)
|
||||
@@ -554,17 +635,17 @@ class FocusFragment : Fragment(R.layout.fragment_focus) {
|
||||
})
|
||||
}
|
||||
tasks.forEach { t ->
|
||||
val meta = buildString {
|
||||
append(getString(R.string.minutes_value, t.focusMinutes))
|
||||
if (t.due > 0) append(" · ${Dates.dueLabel(t.due)}截止")
|
||||
}
|
||||
// 行内只写任务时间(专注时长),不挂截止/随时、也不标完成或逾期
|
||||
val meta = getString(R.string.value_minutes, t.focusMinutes)
|
||||
addRow(
|
||||
title = t.title,
|
||||
meta = meta,
|
||||
color = project?.color,
|
||||
selected = t.id == TimerCore.taskId,
|
||||
) {
|
||||
// 选中任务后回到倒计时,并把圆环切到该任务设定的时长
|
||||
// 选中任务后回到倒计时,并把圆环切到该任务设定的时长。
|
||||
// 这里**不自动开始**:选完任务常常还要上下拖动圆环调整本轮时长,
|
||||
// 一旦自动跑起来,纵向拖动就被 handleDialTouch 判为忽略(running 时才不让调)。
|
||||
TimerCore.setCountUp(false)
|
||||
TimerCore.setTask(t.id, t.projectId, t.focusMinutes)
|
||||
sheet.dismiss()
|
||||
@@ -586,7 +667,8 @@ class FocusFragment : Fragment(R.layout.fragment_focus) {
|
||||
Store.projects().forEach { p ->
|
||||
addRow(
|
||||
title = p.name,
|
||||
meta = getString(R.string.pick_project_meta, p.openTasks),
|
||||
// 与项目页卡片同一套统计:类型 · N个任务 · 已完成M次 · 累计时长
|
||||
meta = ctx.projectMetaLine(p),
|
||||
color = p.color,
|
||||
selected = p.id == currentPid,
|
||||
alignLeft = true, // 项目列表不要左侧色点缩进,名称贴左对齐
|
||||
@@ -597,10 +679,12 @@ class FocusFragment : Fragment(R.layout.fragment_focus) {
|
||||
|
||||
btnBack.setOnClickListener { showProjects() }
|
||||
btnClose.setOnClickListener { sheet.dismiss() }
|
||||
// 第二步底部:没有合适的任务就当场建一个,建完自动选中并回到专注页
|
||||
btnClear.text = getString(R.string.create_now)
|
||||
btnClear.setTextColor(col(R.color.brand))
|
||||
btnClear.setOnClickListener {
|
||||
TimerCore.setTask(0, 0)
|
||||
sheet.dismiss()
|
||||
render()
|
||||
createTaskAndSelect(pickedProjectId)
|
||||
}
|
||||
sheet.setContentView(root)
|
||||
showProjects()
|
||||
|
||||
@@ -19,6 +19,7 @@ import com.focusbox.app.data.Store
|
||||
import com.focusbox.app.service.Notif
|
||||
import com.focusbox.app.service.TimerCore
|
||||
import com.focusbox.app.util.Dates
|
||||
import com.focusbox.app.util.Prefs
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Calendar
|
||||
import java.util.Locale
|
||||
@@ -102,6 +103,9 @@ class LockScreenActivity : AppCompatActivity() {
|
||||
override fun onStart() {
|
||||
super.onStart()
|
||||
showing = true
|
||||
// 本页能走到 onStart,说明系统确实允许从后台把页面盖到锁屏上。
|
||||
// 记下这一刻:设置页据此把「锁屏显示权限」从「去开启」换成「已开启」
|
||||
Prefs.lockShownAt = System.currentTimeMillis()
|
||||
// 页面已经实际盖到锁屏上了,抽屉里那条触发通知清掉
|
||||
Notif.cancelFullscreen(this)
|
||||
applyImmersive()
|
||||
|
||||
@@ -1,30 +1,62 @@
|
||||
package com.focusbox.app.ui.projects
|
||||
|
||||
import android.content.res.ColorStateList
|
||||
import android.graphics.Paint
|
||||
import android.text.Spannable
|
||||
import android.text.SpannableString
|
||||
import android.text.style.StrikethroughSpan
|
||||
import android.view.LayoutInflater
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import android.widget.ImageView
|
||||
import android.widget.LinearLayout
|
||||
import android.widget.ProgressBar
|
||||
import android.widget.TextView
|
||||
import androidx.recyclerview.widget.RecyclerView
|
||||
import com.focusbox.app.R
|
||||
import com.focusbox.app.model.Project
|
||||
import com.focusbox.app.model.ProjectCompletion
|
||||
import com.focusbox.app.model.ProjectTaskStat
|
||||
import com.focusbox.app.model.Task
|
||||
import com.focusbox.app.util.Dates
|
||||
import com.focusbox.app.util.col
|
||||
import com.focusbox.app.util.projectMetaLine
|
||||
import com.focusbox.app.util.roundBg
|
||||
import com.focusbox.app.util.tint
|
||||
import com.focusbox.app.util.visible
|
||||
|
||||
/**
|
||||
* 项目列表:点击项目头就地展开该项目下创建的任务,不再跳转任务页。
|
||||
* 任务不按完成/逾期过滤,全部列出;任务下方用「展开/收起完成记录」开关
|
||||
* 控制该项目的历史完成记录,避免记录越积越长。
|
||||
*/
|
||||
class ProjectAdapter(
|
||||
private val onClick: (Project) -> Unit,
|
||||
private val onToggleExpand: (Project) -> Unit,
|
||||
private val onLongClick: (Project) -> Unit,
|
||||
private val onMore: (Project) -> Unit,
|
||||
private val onStart: (Task) -> Unit,
|
||||
private val onEdit: (Task) -> Unit,
|
||||
private val onToggleDone: () -> Unit,
|
||||
) : RecyclerView.Adapter<ProjectAdapter.VH>() {
|
||||
|
||||
private var items: List<Project> = emptyList()
|
||||
private var expandedId: Long = -1L
|
||||
private var stats: Map<Long, List<ProjectTaskStat>> = emptyMap()
|
||||
private var completions: Map<Long, List<ProjectCompletion>> = emptyMap()
|
||||
private var showDone: Boolean = false
|
||||
|
||||
fun submit(list: List<Project>) {
|
||||
fun submit(
|
||||
list: List<Project>,
|
||||
expanded: Long,
|
||||
taskStats: Map<Long, List<ProjectTaskStat>>,
|
||||
completionRows: Map<Long, List<ProjectCompletion>>,
|
||||
showDoneRows: Boolean,
|
||||
) {
|
||||
items = list
|
||||
expandedId = expanded
|
||||
stats = taskStats
|
||||
completions = completionRows
|
||||
showDone = showDoneRows
|
||||
notifyDataSetChanged()
|
||||
}
|
||||
|
||||
@@ -41,18 +73,17 @@ class ProjectAdapter(
|
||||
private val progress: ProgressBar = v.findViewById(R.id.progress)
|
||||
private val colorBar: View = v.findViewById(R.id.colorBar)
|
||||
private val more: ImageView = v.findViewById(R.id.btnMore)
|
||||
private val header: View = v.findViewById(R.id.projectHeader)
|
||||
private val taskList: LinearLayout = v.findViewById(R.id.taskList)
|
||||
private val tvTaskEmpty: TextView = v.findViewById(R.id.tvTaskEmpty)
|
||||
|
||||
fun bind(p: Project) {
|
||||
val ctx = itemView.context
|
||||
name.text = p.name
|
||||
colorBar.background = ctx.roundBg(p.color, 2f)
|
||||
|
||||
// 只看任务与时长,不再显示番茄数
|
||||
val parts = ArrayList<String>(3)
|
||||
parts.add("${p.openTasks} 待办")
|
||||
if (p.doneTasks > 0) parts.add("${p.doneTasks} 已完成")
|
||||
if (p.focusSeconds >= 60) parts.add(Dates.duration(p.focusSeconds))
|
||||
meta.text = parts.joinToString(" · ")
|
||||
// 统计行组装已提取为共享函数(项目页与专注页选任务第一步同一口径),见 Ui.projectMetaLine
|
||||
meta.text = ctx.projectMetaLine(p)
|
||||
|
||||
progress.progress = (p.progress * 100).toInt()
|
||||
progress.progressTintList = ColorStateList.valueOf(p.color)
|
||||
@@ -61,11 +92,134 @@ class ProjectAdapter(
|
||||
more.tint(ctx.col(R.color.text_tertiary))
|
||||
more.setOnClickListener { onMore(p) }
|
||||
|
||||
itemView.setOnClickListener { onClick(p) }
|
||||
itemView.setOnLongClickListener {
|
||||
header.setOnClickListener { onToggleExpand(p) }
|
||||
header.setOnLongClickListener {
|
||||
onLongClick(p)
|
||||
true
|
||||
}
|
||||
|
||||
val expanded = expandedId == p.id
|
||||
val rows = if (expanded) stats[p.id].orEmpty() else emptyList()
|
||||
val records = if (expanded) completions[p.id].orEmpty() else emptyList()
|
||||
taskList.visible(expanded && (rows.isNotEmpty() || records.isNotEmpty()))
|
||||
tvTaskEmpty.visible(expanded && rows.isEmpty() && records.isEmpty())
|
||||
if (!expanded) return
|
||||
|
||||
fun addTaskRow(row: ProjectTaskStat) {
|
||||
val item = LayoutInflater.from(ctx)
|
||||
.inflate(R.layout.item_project_task, taskList, false)
|
||||
bindTaskRow(item, row, p)
|
||||
taskList.addView(item)
|
||||
}
|
||||
|
||||
taskList.removeAllViews()
|
||||
// 项目下创建的任务全部列出:不按完成/逾期过滤,也不重复生成
|
||||
rows.forEach { addTaskRow(it) }
|
||||
|
||||
// 任务下面单独一条开关:展开/隐藏该项目下的完成记录
|
||||
if (records.isNotEmpty()) {
|
||||
val toggle = LayoutInflater.from(ctx)
|
||||
.inflate(R.layout.item_footer, taskList, false)
|
||||
val tv = toggle.findViewById<TextView>(R.id.tvFooter)
|
||||
tv.text = ctx.getString(
|
||||
if (showDone) R.string.project_collapse_done else R.string.project_expand_done,
|
||||
records.size,
|
||||
)
|
||||
tv.setTextColor(ctx.col(R.color.brand))
|
||||
toggle.setOnClickListener { onToggleDone() }
|
||||
taskList.addView(toggle)
|
||||
if (showDone) records.forEach { addCompletionRow(it, p) }
|
||||
}
|
||||
}
|
||||
|
||||
private fun bindTaskRow(item: View, row: ProjectTaskStat, p: Project) {
|
||||
val ctx = item.context
|
||||
val task = row.task
|
||||
val tvTitle: TextView = item.findViewById(R.id.tvTaskTitle)
|
||||
val tvMeta: TextView = item.findViewById(R.id.tvTaskMeta)
|
||||
val btnPlay: ImageView = item.findViewById(R.id.btnTaskPlay)
|
||||
item.findViewById<View>(R.id.taskColorBar).background = ctx.roundBg(p.color, 2f)
|
||||
|
||||
// 顶部是「创建了就一直在」的任务清单:不划线、不变灰;
|
||||
// 完成与否只体现在下面的完成记录里
|
||||
tvTitle.text = task.title
|
||||
tvTitle.setTextColor(ctx.col(R.color.text))
|
||||
tvTitle.paintFlags = tvTitle.paintFlags and Paint.STRIKE_THRU_TEXT_FLAG.inv()
|
||||
|
||||
// 任务时间(专注时长)· 最近完成 · 累计次数与累计专注
|
||||
val parts = ArrayList<String>(3)
|
||||
parts.add(ctx.getString(R.string.minutes_value, task.focusMinutes))
|
||||
if (row.lastDoneAt > 0) {
|
||||
val whenText = "${Dates.md(row.lastDoneAt)}·${Dates.hm(row.lastDoneAt)}"
|
||||
parts.add(ctx.getString(R.string.project_task_last_done, whenText))
|
||||
}
|
||||
val totals = StringBuilder()
|
||||
if (row.doneCount > 0) {
|
||||
totals.append(ctx.getString(R.string.project_task_done_count, row.doneCount))
|
||||
}
|
||||
if (row.focusSeconds > 0) {
|
||||
// 累计专注只写「数字分钟」,不加说明文案,也不留空格
|
||||
totals.append(ctx.getString(R.string.minutes_value, row.focusSeconds / 60))
|
||||
}
|
||||
if (totals.isNotEmpty()) parts.add(totals.toString())
|
||||
tvMeta.text = parts.joinToString(" · ")
|
||||
|
||||
// 开始键常驻:已完成的创建任务同样可以再开始一轮,
|
||||
// 由调用方把「已完成的行」换成系列里当前可计时的任务
|
||||
btnPlay.visible(true)
|
||||
btnPlay.tint(ctx.col(R.color.brand))
|
||||
btnPlay.setOnClickListener { onStart(task) }
|
||||
// 与任务页一致:点行打开编辑/删除弹窗
|
||||
item.setOnClickListener { onEdit(task) }
|
||||
}
|
||||
|
||||
private fun addCompletionRow(record: ProjectCompletion, p: Project) {
|
||||
val ctx = itemView.context
|
||||
val item = LayoutInflater.from(ctx)
|
||||
.inflate(R.layout.item_project_task, taskList, false)
|
||||
item.findViewById<View>(R.id.taskColorBar).background = ctx.roundBg(p.color, 2f)
|
||||
|
||||
val tvTitle: TextView = item.findViewById(R.id.tvTaskTitle)
|
||||
val tvMeta: TextView = item.findViewById(R.id.tvTaskMeta)
|
||||
val btnPlay: ImageView = item.findViewById(R.id.btnTaskPlay)
|
||||
// 完成记录行只做历史展示:开始键只出现在上面的创建任务行
|
||||
btnPlay.visible(false)
|
||||
|
||||
// 完成记录与任务页底部一致:任务名划线,完成原因跟在后面但不划线
|
||||
val noteText = record.note.replace('\n', ' ')
|
||||
val titleText = if (noteText.isBlank()) {
|
||||
record.taskTitle
|
||||
} else {
|
||||
"${record.taskTitle} · $noteText"
|
||||
}
|
||||
val line = SpannableString(titleText)
|
||||
if (record.taskTitle.isNotEmpty()) {
|
||||
line.setSpan(
|
||||
StrikethroughSpan(), 0, record.taskTitle.length,
|
||||
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE,
|
||||
)
|
||||
}
|
||||
tvTitle.text = line
|
||||
tvTitle.setTextColor(ctx.col(R.color.text_secondary))
|
||||
tvTitle.paintFlags = tvTitle.paintFlags and Paint.STRIKE_THRU_TEXT_FLAG.inv()
|
||||
|
||||
// 与任务页完成记录同格式:日期 周几 起-止 · 专注X;没有真实时长就只写完成时刻
|
||||
tvMeta.text = if (record.seconds > 0) {
|
||||
ctx.getString(
|
||||
R.string.done_meta,
|
||||
"${Dates.dateWithWeek(record.startAt)} ${Dates.hms(record.startAt)}" +
|
||||
"-${Dates.hms(record.endAt)}",
|
||||
Dates.duration(record.seconds),
|
||||
)
|
||||
} else {
|
||||
ctx.getString(
|
||||
R.string.done_at_only,
|
||||
"${Dates.dateWithWeek(record.endAt)} ${Dates.hms(record.endAt)}",
|
||||
)
|
||||
}
|
||||
item.isClickable = false
|
||||
item.setOnClickListener(null)
|
||||
taskList.addView(item)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,10 +13,13 @@ import androidx.appcompat.app.AlertDialog
|
||||
import com.focusbox.app.R
|
||||
import com.focusbox.app.data.Store
|
||||
import com.focusbox.app.model.Project
|
||||
import com.focusbox.app.service.TimerCore
|
||||
import com.focusbox.app.ui.SheetDialog
|
||||
import com.focusbox.app.util.Palette
|
||||
import com.focusbox.app.util.Prefs
|
||||
import com.focusbox.app.util.circleBg
|
||||
import com.focusbox.app.util.dpi
|
||||
import com.focusbox.app.util.makeChip
|
||||
import com.focusbox.app.util.roundBg
|
||||
import com.focusbox.app.util.visible
|
||||
|
||||
@@ -31,11 +34,22 @@ class ProjectSheet(
|
||||
private val etSortIndex: EditText = root.findViewById(R.id.etSortIndex)
|
||||
private val swPinned: androidx.appcompat.widget.SwitchCompat = root.findViewById(R.id.swPinned)
|
||||
private val colorRow: LinearLayout = root.findViewById(R.id.colorRow)
|
||||
private val typeRow: com.focusbox.app.util.FlowLayout = root.findViewById(R.id.typeRow)
|
||||
|
||||
private var color: Int = existing?.color ?: Palette.colorAt(0)
|
||||
|
||||
/**
|
||||
* 当前选中的类型。空串表示「不设置」——老项目全部是空串,
|
||||
* 打开编辑时默认就停在「不设置」,不会因为用户只想改个名字被强行归类。
|
||||
*/
|
||||
private var type: String = existing?.type.orEmpty()
|
||||
|
||||
init {
|
||||
setContentView(root)
|
||||
// 项目编辑含多个输入框:必须走满屏容器 + 键盘顶起,否则输入法会盖住弹层
|
||||
fitOnIme(root)
|
||||
// 满屏容器后仍保留“点弹层外关闭”,点弹层内部空白不关闭
|
||||
(root.parent as? View)?.setOnClickListener { dismiss() }
|
||||
root.setOnClickListener { }
|
||||
root.findViewById<TextView>(R.id.sheetTitle).setText(
|
||||
if (existing == null) R.string.add_project else R.string.edit
|
||||
)
|
||||
@@ -45,6 +59,7 @@ class ProjectSheet(
|
||||
etSortIndex.setText(existing.sortIndex.toString())
|
||||
}
|
||||
swPinned.isChecked = (existing?.pinnedAt ?: 0L) > 0L
|
||||
renderTypes()
|
||||
renderColors()
|
||||
|
||||
val btnDelete = root.findViewById<TextView>(R.id.btnDelete)
|
||||
@@ -57,6 +72,11 @@ class ProjectSheet(
|
||||
.setNegativeButton(R.string.cancel, null)
|
||||
.setPositiveButton(R.string.delete) { _, _ ->
|
||||
Store.deleteProject(existing.id)
|
||||
// 项目下的任务行已经删掉了:正在计时的如果正好是其中一条,
|
||||
// 必须先把计时解绑,否则这一轮结束时会写出一条挂不到任务上的记录
|
||||
if (TimerCore.taskId > 0 && Store.task(TimerCore.taskId) == null) {
|
||||
TimerCore.setTask(0, 0)
|
||||
}
|
||||
onSaved()
|
||||
dismiss()
|
||||
}
|
||||
@@ -73,7 +93,7 @@ class ProjectSheet(
|
||||
val pinned = swPinned.isChecked
|
||||
if (existing == null) {
|
||||
// 新建置顶:置顶时间取当下,排进置顶组
|
||||
Store.addProject(name, color, sortIndex, pinned)
|
||||
Store.addProject(name, color, sortIndex, pinned, type)
|
||||
} else {
|
||||
// 已置顶且保持置顶 → 保留原置顶时间(重复保存不刷新排序);
|
||||
// 新勾置顶 → 以保存这一刻为置顶时间;取消置顶 → Store 里归 0
|
||||
@@ -82,35 +102,78 @@ class ProjectSheet(
|
||||
existing.pinnedAt > 0L -> existing.pinnedAt
|
||||
else -> System.currentTimeMillis()
|
||||
}
|
||||
Store.updateProject(existing.id, name, color, existing.archived, sortIndex, pinned, pinnedAt)
|
||||
Store.updateProject(
|
||||
existing.id, name, color, existing.archived, sortIndex, pinned, pinnedAt, type,
|
||||
)
|
||||
}
|
||||
onSaved()
|
||||
dismiss()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 类型胶囊:设置页里的类型列表 + 一个「不设置」。
|
||||
*
|
||||
* 老项目不带类型,编辑时必须能保持空值;如果只给列表不给「不设置」,
|
||||
* 用户点开编辑就等于被迫归类,改回去还得再找一圈。
|
||||
* 已选但后来在设置里被删掉的类型照样显示出来(selected 为真),
|
||||
* 否则用户看不到自己原来选的是什么,一保存就被清空。
|
||||
*/
|
||||
private fun renderTypes() {
|
||||
val ctx = context
|
||||
typeRow.removeAllViews()
|
||||
val options = ArrayList<String>(Prefs.projectTypes)
|
||||
if (type.isNotBlank() && !options.contains(type)) options.add(0, type)
|
||||
|
||||
val none = ctx.makeChip(ctx.getString(R.string.project_type_none), type.isBlank())
|
||||
none.setOnClickListener {
|
||||
type = ""
|
||||
renderTypes()
|
||||
}
|
||||
typeRow.addView(none)
|
||||
|
||||
options.forEach { name ->
|
||||
val chip = ctx.makeChip(name, name == type)
|
||||
chip.setOnClickListener {
|
||||
// 再点一次已选中的类型 = 取消归类
|
||||
type = if (type == name) "" else name
|
||||
renderTypes()
|
||||
}
|
||||
typeRow.addView(chip)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 20 色两行平铺(每行 10 个)。
|
||||
*
|
||||
* 从一行横向滑动改成两行:20 个色点若排成一行要滑很久才找得到,
|
||||
* 两行 × 10 个刚好铺满一屏宽度(10 × 32dp = 320dp),窄屏仍可横向滑动兜底。
|
||||
*/
|
||||
private fun renderColors() {
|
||||
val ctx = context
|
||||
colorRow.removeAllViews()
|
||||
Palette.colors.forEach { c ->
|
||||
val wrap = FrameLayout(ctx)
|
||||
val lp = LinearLayout.LayoutParams(dpi(40f), dpi(40f))
|
||||
lp.marginEnd = dpi(2f)
|
||||
wrap.layoutParams = lp
|
||||
wrap.background = if (c == color) ctx.roundBg(Color.TRANSPARENT, 100f, c, 2f) else null
|
||||
Palette.colors.toList().chunked(10).forEach { rowColors ->
|
||||
val row = LinearLayout(ctx).apply { orientation = LinearLayout.HORIZONTAL }
|
||||
colorRow.addView(row)
|
||||
rowColors.forEach { c ->
|
||||
val wrap = FrameLayout(ctx)
|
||||
val lp = LinearLayout.LayoutParams(dpi(32f), dpi(32f))
|
||||
wrap.layoutParams = lp
|
||||
wrap.background = if (c == color) ctx.roundBg(Color.TRANSPARENT, 100f, c, 2f) else null
|
||||
|
||||
val dot = View(ctx)
|
||||
val dlp = FrameLayout.LayoutParams(dpi(26f), dpi(26f))
|
||||
dlp.gravity = Gravity.CENTER
|
||||
dot.layoutParams = dlp
|
||||
dot.background = circleBg(c)
|
||||
wrap.addView(dot)
|
||||
val dot = View(ctx)
|
||||
val dlp = FrameLayout.LayoutParams(dpi(20f), dpi(20f))
|
||||
dlp.gravity = Gravity.CENTER
|
||||
dot.layoutParams = dlp
|
||||
dot.background = circleBg(c)
|
||||
wrap.addView(dot)
|
||||
|
||||
wrap.setOnClickListener {
|
||||
color = c
|
||||
renderColors()
|
||||
wrap.setOnClickListener {
|
||||
color = c
|
||||
renderColors()
|
||||
}
|
||||
row.addView(wrap)
|
||||
}
|
||||
colorRow.addView(wrap)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,8 +10,12 @@ import androidx.recyclerview.widget.RecyclerView
|
||||
import com.focusbox.app.R
|
||||
import com.focusbox.app.data.Store
|
||||
import com.focusbox.app.model.Project
|
||||
import com.focusbox.app.model.ProjectCompletion
|
||||
import com.focusbox.app.model.ProjectTaskStat
|
||||
import com.focusbox.app.service.TimerCore
|
||||
import com.focusbox.app.ui.MainActivity
|
||||
import com.focusbox.app.ui.SheetDialog
|
||||
import com.focusbox.app.ui.tasks.TaskSheet
|
||||
import com.focusbox.app.util.col
|
||||
import com.focusbox.app.util.visible
|
||||
|
||||
@@ -25,6 +29,13 @@ class ProjectsFragment : Fragment(R.layout.fragment_projects) {
|
||||
|
||||
private var showArchived = false
|
||||
|
||||
/** 当前展开的项目 id;-1 表示全部收起。只展开一个,避免列表过长 */
|
||||
private var expandedProjectId = -1L
|
||||
private var taskStats: Map<Long, List<ProjectTaskStat>> = emptyMap()
|
||||
private var completions: Map<Long, List<ProjectCompletion>> = emptyMap()
|
||||
/** 项目任务下方的完成记录默认折叠,避免历史记录越积越长 */
|
||||
private var showDoneInProject = false
|
||||
|
||||
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
|
||||
super.onViewCreated(view, savedInstanceState)
|
||||
recycler = view.findViewById(R.id.recycler)
|
||||
@@ -33,9 +44,20 @@ class ProjectsFragment : Fragment(R.layout.fragment_projects) {
|
||||
btnArchived = view.findViewById(R.id.btnArchived)
|
||||
|
||||
adapter = ProjectAdapter(
|
||||
onClick = { p -> (activity as? MainActivity)?.openProjectTasks(p.id) },
|
||||
onToggleExpand = { p ->
|
||||
val opening = expandedProjectId != p.id
|
||||
expandedProjectId = if (opening) p.id else -1L
|
||||
if (opening) showDoneInProject = false
|
||||
reload()
|
||||
},
|
||||
onLongClick = { p -> showActions(p) },
|
||||
onMore = { p -> showActions(p) },
|
||||
onStart = { t -> (activity as? MainActivity)?.startFocusFrom(t.id) },
|
||||
onEdit = { t -> TaskSheet(requireContext(), t, 0L) { reload() }.show() },
|
||||
onToggleDone = {
|
||||
showDoneInProject = !showDoneInProject
|
||||
reload()
|
||||
},
|
||||
)
|
||||
recycler.layoutManager = LinearLayoutManager(requireContext())
|
||||
recycler.adapter = adapter
|
||||
@@ -68,10 +90,19 @@ class ProjectsFragment : Fragment(R.layout.fragment_projects) {
|
||||
val archived = all.filter { it.archived }
|
||||
|
||||
val shown = if (showArchived) all else active
|
||||
adapter.submit(shown)
|
||||
// 展开态只在可见项目上加载统计;项目被删/归档后自动收起,不留悬空 id
|
||||
if (expandedProjectId != -1L && shown.none { it.id == expandedProjectId }) {
|
||||
expandedProjectId = -1L
|
||||
}
|
||||
// 只给展开的那一个项目取统计:两条都是递归 CTE,对全部项目逐个跑一遍
|
||||
// 是纯浪费(未展开的项目根本不会渲染这些行)
|
||||
val expanded = expandedProjectId
|
||||
taskStats = if (expanded == -1L) emptyMap() else mapOf(expanded to Store.projectTaskRows(expanded))
|
||||
completions = if (expanded == -1L) emptyMap() else mapOf(expanded to Store.projectCompletions(expanded))
|
||||
adapter.submit(shown, expandedProjectId, taskStats, completions, showDoneInProject)
|
||||
|
||||
tvSummary.text = getString(
|
||||
R.string.project_summary, active.size, active.sumOf { it.openTasks }
|
||||
R.string.project_summary, active.size, active.sumOf { it.totalTasks }
|
||||
)
|
||||
tvEmpty.visible(shown.isEmpty())
|
||||
|
||||
@@ -79,7 +110,11 @@ class ProjectsFragment : Fragment(R.layout.fragment_projects) {
|
||||
btnArchived.visible(false)
|
||||
} else {
|
||||
btnArchived.visible(true)
|
||||
btnArchived.text = if (showArchived) "隐藏已归档" else "已归档 ${archived.size}"
|
||||
btnArchived.text = if (showArchived) {
|
||||
getString(R.string.hide_archived)
|
||||
} else {
|
||||
getString(R.string.archived_count, archived.size)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -120,6 +155,10 @@ class ProjectsFragment : Fragment(R.layout.fragment_projects) {
|
||||
val isInbox = p.id == Store.INBOX_ID
|
||||
val actions = ArrayList<Pair<String, Boolean>>()
|
||||
actions.add(getString(R.string.edit) to false)
|
||||
// 编辑下面直接给「任务」:建在当前项目下,弹层与任务页、专注页用的是同一个
|
||||
// TaskSheet,保存后回本页刷新,省掉「切到任务页 → 点 + → 再选项目」两步。
|
||||
// 菜单项文案用短名(TaskSheet 自己的标题仍是「新建任务」,两处不冲突)
|
||||
actions.add(getString(R.string.menu_task) to false)
|
||||
if (!isInbox) {
|
||||
actions.add(getString(if (p.archived) R.string.unarchive else R.string.archive) to false)
|
||||
actions.add(getString(R.string.delete) to true)
|
||||
@@ -127,15 +166,16 @@ class ProjectsFragment : Fragment(R.layout.fragment_projects) {
|
||||
actionSheet(p.name, actions = actions) { which ->
|
||||
when {
|
||||
which == 0 -> ProjectSheet(requireContext(), p) { reload() }.show()
|
||||
which == 1 && !isInbox -> {
|
||||
// 归档/取消归档只切 archived,序号与置顶状态原样保留
|
||||
which == 1 -> TaskSheet(requireContext(), null, p.id) { reload() }.show()
|
||||
which == 2 && !isInbox -> {
|
||||
// 归档/取消归档只切 archived,序号、置顶状态与类型原样保留
|
||||
Store.updateProject(
|
||||
p.id, p.name, p.color, !p.archived,
|
||||
p.sortIndex, p.pinnedAt > 0, p.pinnedAt,
|
||||
p.sortIndex, p.pinnedAt > 0, p.pinnedAt, p.type,
|
||||
)
|
||||
reload()
|
||||
}
|
||||
which == 2 && !isInbox -> confirmDelete(p)
|
||||
which == 3 && !isInbox -> confirmDelete(p)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -148,6 +188,11 @@ class ProjectsFragment : Fragment(R.layout.fragment_projects) {
|
||||
) { which ->
|
||||
if (which == 1) {
|
||||
Store.deleteProject(p.id)
|
||||
// 项目下的任务行已随之删除:正在计时的若属于它们,先解绑,
|
||||
// 否则这一轮结束会写成一条挂不到任务的「未关联」记录
|
||||
if (TimerCore.taskId > 0 && Store.task(TimerCore.taskId) == null) {
|
||||
TimerCore.setTask(0, 0)
|
||||
}
|
||||
reload()
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -2,6 +2,7 @@ package com.focusbox.app.ui.stats
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Typeface
|
||||
import android.graphics.drawable.GradientDrawable
|
||||
import android.util.AttributeSet
|
||||
import android.util.TypedValue
|
||||
import android.view.Gravity
|
||||
@@ -12,8 +13,10 @@ 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.Prefs
|
||||
import com.focusbox.app.util.col
|
||||
import com.focusbox.app.util.dpi
|
||||
import com.focusbox.app.util.percentText
|
||||
import com.focusbox.app.widget.LabelDonutView
|
||||
|
||||
/**
|
||||
@@ -35,6 +38,9 @@ class PeriodDistributionCard @JvmOverloads constructor(
|
||||
YEAR(R.string.scale_year),
|
||||
}
|
||||
|
||||
/** 数据源:按项目 / 按任务 / 按项目类型。三张卡结构完全一致,只有取数不同 */
|
||||
enum class Mode { PROJECT, TASK, TYPE }
|
||||
|
||||
private val tvTitle = TextView(context)
|
||||
private val segItems = ArrayList<TextView>(4)
|
||||
private val tvPeriod = TextView(context)
|
||||
@@ -42,6 +48,12 @@ class PeriodDistributionCard @JvmOverloads constructor(
|
||||
private val btnNext = ImageView(context)
|
||||
private val donut = LabelDonutView(context)
|
||||
|
||||
/**
|
||||
* 环下方明细列表:环只标占比最高的 6 条,剩下的全部在这里逐条列出。
|
||||
* 不合并成「其他」——被合并掉的任务在页面上等于消失,用户根本不知道自己漏了什么。
|
||||
*/
|
||||
private val legend = LinearLayout(context)
|
||||
|
||||
/** 当前粒度,默认按天 */
|
||||
var scale = Scale.DAY
|
||||
private set
|
||||
@@ -49,8 +61,15 @@ class PeriodDistributionCard @JvmOverloads constructor(
|
||||
/** 锚点:落在目标周期内的任意时刻,实际区间由它推导 */
|
||||
private var anchor = Dates.todayStart()
|
||||
|
||||
/** true = 按任务汇总,false = 按项目汇总 */
|
||||
var byTask = false
|
||||
/**
|
||||
* 锚点是否停在「当前周期」。停在当前周期时,跨天/跨周后的 refresh()
|
||||
* 自动跟进到新周期(否则进程隔夜存活的话,日视图会一直停在昨天);
|
||||
* 用户主动翻页看过历史后保持原样,不抢回焦点。
|
||||
*/
|
||||
private var atCurrentPeriod = true
|
||||
|
||||
/** 取数口径:项目 / 任务 / 类型 */
|
||||
var mode = Mode.PROJECT
|
||||
set(value) {
|
||||
field = value
|
||||
refresh()
|
||||
@@ -145,6 +164,88 @@ class PeriodDistributionCard @JvmOverloads constructor(
|
||||
addView(donut, LayoutParams(LayoutParams.MATCH_PARENT, context.dpi(222f)).apply {
|
||||
topMargin = context.dpi(2f)
|
||||
})
|
||||
|
||||
legend.apply {
|
||||
orientation = VERTICAL
|
||||
visibility = GONE
|
||||
}
|
||||
addView(legend, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT).apply {
|
||||
topMargin = context.dpi(6f)
|
||||
})
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 明细列表
|
||||
|
||||
/**
|
||||
* 把环上没有牵线的切片按「圆点 + 名称 / 时长 · 占比」两列铺开(参考图版式)。
|
||||
* 每格宽度均分,名称超长省略,保证列对齐不来回跳。
|
||||
*/
|
||||
private fun renderLegend(rest: List<LabelDonutView.Slice>, total: Int) {
|
||||
legend.removeAllViews()
|
||||
if (rest.isEmpty() || total <= 0) {
|
||||
legend.visibility = GONE
|
||||
return
|
||||
}
|
||||
legend.visibility = VISIBLE
|
||||
|
||||
rest.chunked(2).forEach { pair ->
|
||||
val row = LinearLayout(context).apply { orientation = HORIZONTAL }
|
||||
legend.addView(row, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT))
|
||||
pair.forEach { slice ->
|
||||
row.addView(buildLegendCell(slice, total), LayoutParams(0, LayoutParams.WRAP_CONTENT, 1f))
|
||||
}
|
||||
// 单数时补一个空位,最后一行不会因为权重拉伸变成通栏
|
||||
if (pair.size == 1) {
|
||||
row.addView(android.view.View(context), LayoutParams(0, 1, 1f))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun buildLegendCell(slice: LabelDonutView.Slice, total: Int): LinearLayout {
|
||||
val cell = LinearLayout(context).apply {
|
||||
orientation = HORIZONTAL
|
||||
setPadding(0, context.dpi(7f), context.dpi(8f), context.dpi(7f))
|
||||
}
|
||||
|
||||
val dot = android.view.View(context).apply {
|
||||
background = GradientDrawable().apply {
|
||||
shape = GradientDrawable.OVAL
|
||||
setColor(slice.color)
|
||||
}
|
||||
}
|
||||
// 8dp 圆点,下移 5dp 与名称首行的视觉中心对齐
|
||||
cell.addView(dot, LayoutParams(context.dpi(8f), context.dpi(8f)).apply {
|
||||
topMargin = context.dpi(5f)
|
||||
})
|
||||
|
||||
val text = LinearLayout(context).apply {
|
||||
orientation = VERTICAL
|
||||
setPadding(context.dpi(8f), 0, 0, 0)
|
||||
}
|
||||
cell.addView(text, LayoutParams(0, LayoutParams.WRAP_CONTENT, 1f))
|
||||
|
||||
text.addView(TextView(context).apply {
|
||||
this.text = slice.name
|
||||
setTextSize(TypedValue.COMPLEX_UNIT_SP, 13f)
|
||||
setTextColor(context.col(R.color.title))
|
||||
maxLines = 1
|
||||
ellipsize = android.text.TextUtils.TruncateAt.END
|
||||
includeFontPadding = false
|
||||
})
|
||||
|
||||
text.addView(TextView(context).apply {
|
||||
this.text = context.getString(
|
||||
R.string.legend_meta,
|
||||
Dates.duration(slice.seconds),
|
||||
percentText(slice.seconds, total),
|
||||
)
|
||||
setTextSize(TypedValue.COMPLEX_UNIT_SP, 11f)
|
||||
setTextColor(context.col(R.color.text_secondary))
|
||||
maxLines = 1
|
||||
includeFontPadding = false
|
||||
})
|
||||
|
||||
return cell
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 交互
|
||||
@@ -154,11 +255,13 @@ class PeriodDistributionCard @JvmOverloads constructor(
|
||||
scale = s
|
||||
// 换粒度回到"当前",否则从 2024 年的日视图切到年视图会落在 2024 年,容易困惑
|
||||
anchor = Dates.todayStart()
|
||||
atCurrentPeriod = true
|
||||
refresh()
|
||||
}
|
||||
|
||||
private fun shift(delta: Int) {
|
||||
if (delta > 0 && !canNext()) return
|
||||
if (delta < 0 && !canPrev()) return
|
||||
val s = start()
|
||||
anchor = when (scale) {
|
||||
Scale.DAY -> Dates.addDays(s, delta)
|
||||
@@ -166,6 +269,8 @@ class PeriodDistributionCard @JvmOverloads constructor(
|
||||
Scale.MONTH -> Dates.addMonths(s, delta)
|
||||
Scale.YEAR -> Dates.addYears(s, delta)
|
||||
}
|
||||
// 翻回当前周期时恢复"跟随",翻去历史周期则停住,之后跨天不再自动跳走
|
||||
atCurrentPeriod = periodStart(anchor) == periodStart(Dates.todayStart())
|
||||
refresh()
|
||||
}
|
||||
|
||||
@@ -188,13 +293,31 @@ class PeriodDistributionCard @JvmOverloads constructor(
|
||||
/** 未来没有记录,往后翻到当前周期为止 */
|
||||
private fun canNext(): Boolean = start() < periodStart(Dates.todayStart())
|
||||
|
||||
/**
|
||||
* 最早一条记录所在的周期:再往前必然是空图。
|
||||
* 原来左箭头没有下界,按「日」一路连点能翻到 1970 年。
|
||||
*/
|
||||
private fun canPrev(): Boolean {
|
||||
val earliest = Store.earliestSessionAt()
|
||||
if (earliest <= 0L) return false
|
||||
return start() > periodStart(earliest)
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 渲染
|
||||
|
||||
fun refresh() {
|
||||
// 停在"当前周期"时锚点跟进到今天:进程跨天存活(应用开着过夜、第二天直接回统计页)
|
||||
// 后,日/周/月/年视图才会切到新周期,而不是拿着旧锚点把前一天再画一遍
|
||||
if (atCurrentPeriod) anchor = Dates.todayStart()
|
||||
val from = start()
|
||||
val to = end(from)
|
||||
|
||||
val raw = if (byTask) Store.taskSlices(from, to) else Store.distribution(from, to)
|
||||
val raw = when (mode) {
|
||||
Mode.TASK -> Store.taskSlices(from, to)
|
||||
// 类型归属链路与项目一致,只是把项目换成项目的类型字段
|
||||
Mode.TYPE -> Store.typeSlices(from, to, Prefs.projectTypes)
|
||||
Mode.PROJECT -> Store.distribution(from, to)
|
||||
}
|
||||
donut.setSlices(
|
||||
raw.map {
|
||||
LabelDonutView.Slice(
|
||||
@@ -204,11 +327,14 @@ class PeriodDistributionCard @JvmOverloads constructor(
|
||||
)
|
||||
}
|
||||
)
|
||||
donut.centerText = Dates.durationBrief(raw.sumOf { it.seconds })
|
||||
val total = raw.sumOf { it.seconds }
|
||||
donut.centerText = Dates.durationBrief(total)
|
||||
renderLegend(donut.unlabeled, total)
|
||||
|
||||
tvPeriod.text = periodLabel(from, to)
|
||||
applySegments()
|
||||
btnNext.alpha = if (canNext()) 1f else 0.2f
|
||||
btnPrev.alpha = if (canPrev()) 1f else 0.2f
|
||||
}
|
||||
|
||||
private fun periodLabel(from: Long, to: Long): String = when (scale) {
|
||||
|
||||
@@ -41,6 +41,7 @@ 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 cardType: PeriodDistributionCard
|
||||
private lateinit var cardProject: PeriodDistributionCard
|
||||
private lateinit var cardTask: PeriodDistributionCard
|
||||
private lateinit var summaryGrid: LinearLayout
|
||||
@@ -62,14 +63,18 @@ 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)
|
||||
cardType = view.findViewById(R.id.cardType)
|
||||
cardProject = view.findViewById(R.id.cardProject)
|
||||
cardTask = view.findViewById(R.id.cardTask)
|
||||
summaryGrid = view.findViewById(R.id.summaryGrid)
|
||||
|
||||
// 类型分布排在项目分布上方:先看"时间花在哪类事情上",再看具体项目
|
||||
cardType.cardTitle = getString(R.string.type_distribution_title)
|
||||
cardType.mode = PeriodDistributionCard.Mode.TYPE
|
||||
cardProject.cardTitle = getString(R.string.distribution_title)
|
||||
cardProject.byTask = false
|
||||
cardProject.mode = PeriodDistributionCard.Mode.PROJECT
|
||||
cardTask.cardTitle = getString(R.string.task_distribution_title)
|
||||
cardTask.byTask = true
|
||||
cardTask.mode = PeriodDistributionCard.Mode.TASK
|
||||
|
||||
buildHeatLegend()
|
||||
reload()
|
||||
@@ -90,7 +95,8 @@ class StatsFragment : Fragment(R.layout.fragment_stats) {
|
||||
renderToday()
|
||||
renderTrend()
|
||||
renderHeatmap()
|
||||
// 两张分布卡各自持有区间状态,回到页面只要重新取数
|
||||
// 三张分布卡各自持有区间状态,回到页面只要重新取数
|
||||
cardType.refresh()
|
||||
cardProject.refresh()
|
||||
cardTask.refresh()
|
||||
renderSummary()
|
||||
@@ -101,7 +107,8 @@ class StatsFragment : Fragment(R.layout.fragment_stats) {
|
||||
val stat = Store.todayStat(goal)
|
||||
todayRing.progress = stat.goalProgress
|
||||
todayRing.ringColor = col(if (stat.goalProgress >= 1f) R.color.rest else R.color.brand)
|
||||
tvGoalPct.text = "${(stat.goalProgress * 100).toInt()}%"
|
||||
// 目标达成允许超过 100%:圆环画满即可,数字必须是真实比例
|
||||
tvGoalPct.text = "${stat.goalPercent}%"
|
||||
tvGoalHint.text = getString(R.string.goal_short, goal)
|
||||
tvTodayMinutes.text = getString(R.string.stat_today_minutes, stat.minutes)
|
||||
tvTodayPomo.text = "${stat.pomodoros}"
|
||||
@@ -119,7 +126,7 @@ class StatsFragment : Fragment(R.layout.fragment_stats) {
|
||||
tvTrendTotal.text = if (totalMinutes <= 0) {
|
||||
getString(R.string.no_data)
|
||||
} else {
|
||||
"共${Dates.duration(totalMinutes * 60)}"
|
||||
getString(R.string.trend_total, Dates.duration(totalMinutes * 60))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -127,13 +134,13 @@ class StatsFragment : Fragment(R.layout.fragment_stats) {
|
||||
val series = Store.dailySeries(Dates.addDays(Dates.todayStart(), -83), 84)
|
||||
heatmap.setData(series)
|
||||
val activeDays = series.count { it.minutes > 0 }
|
||||
tvHeatHint.text = "近12周 · ${activeDays}天有记录"
|
||||
tvHeatHint.text = getString(R.string.heat_hint, activeDays)
|
||||
}
|
||||
|
||||
private fun buildHeatLegend() {
|
||||
val ctx = requireContext()
|
||||
heatLegend.removeAllViews()
|
||||
heatLegend.addView(label("少"))
|
||||
heatLegend.addView(label(getString(R.string.heat_less)))
|
||||
for (i in 0..4) {
|
||||
val box = View(ctx)
|
||||
val lp = LinearLayout.LayoutParams(dpi(11f), dpi(11f))
|
||||
@@ -143,7 +150,7 @@ class StatsFragment : Fragment(R.layout.fragment_stats) {
|
||||
box.background = ctx.roundBg(ctx.col(heatColorRes(i)), 3f)
|
||||
heatLegend.addView(box)
|
||||
}
|
||||
heatLegend.addView(label("多"))
|
||||
heatLegend.addView(label(getString(R.string.heat_more)))
|
||||
}
|
||||
|
||||
private fun heatColorRes(index: Int): Int = when (index) {
|
||||
|
||||
@@ -71,6 +71,25 @@ class TaskAdapter(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 标题与图标之间的间距:旧版用三个空格,视觉偏宽。
|
||||
* 改用无字形占位,宽度精确等于三个空格的一半,避免随字体变化忽大忽小。
|
||||
*/
|
||||
private fun appendIconGap(title: SpannableStringBuilder) {
|
||||
title.append(" ")
|
||||
title.setSpan(IconGapSpan(), title.length - 1, title.length, 0)
|
||||
}
|
||||
|
||||
/**
|
||||
* 间距与图标必须各占一个字符。若把两个 ReplacementSpan 套在同一字符上,
|
||||
* 后设置的图标会覆盖间距,视觉上就贴住了。
|
||||
*/
|
||||
private fun appendIconSpan(title: SpannableStringBuilder, span: Any) {
|
||||
appendIconGap(title)
|
||||
title.append(" ")
|
||||
title.setSpan(span, title.length - 1, title.length, 0)
|
||||
}
|
||||
|
||||
private inner class TaskViewHolder(v: View) : RecyclerView.ViewHolder(v) {
|
||||
private val tvTitle: TextView = v.findViewById(R.id.tvTitle)
|
||||
private val tvMeta: TextView = v.findViewById(R.id.tvMeta)
|
||||
@@ -85,23 +104,25 @@ class TaskAdapter(
|
||||
val ctx = itemView.context
|
||||
|
||||
// 标题右侧的属性图标,未完成与已完成都显示:
|
||||
// 重要度圆圈数字(③ 高 / ② 中 / ① 普通,颜色与紧急度同色系)→
|
||||
// 紧急度五角星 → 随时上箭头。
|
||||
// 各字形在字体里的字面尺寸不同:以圆圈数字 0.85 为基准,
|
||||
// 上箭头与圆圈同高;五角星 0.95 不作参照
|
||||
// 置顶圆圈箭头(「随时」未完成任务)→ 重要度圆圈数字 → 紧急度五角星。
|
||||
// 置顶与重要度两个圆圈统一自绘:同一尺寸(0.85 倍字号)、同一描边(s/10),
|
||||
// 保证粗细与高度完全一致;五角星仍用字形,0.95 倍不作参照。
|
||||
val title = SpannableStringBuilder(task.title)
|
||||
val iconSize = tvTitle.textSize * 0.85f
|
||||
|
||||
val (badge, badgeColor) = when (task.priority) {
|
||||
2 -> " ③" to R.color.urgent_high
|
||||
1 -> " ②" to R.color.urgent_mid
|
||||
else -> " ①" to R.color.urgent_low
|
||||
// 置顶图标前移到重要度圆圈之前(品牌蓝圆圈内向上箭头)
|
||||
if (task.repeatType == com.focusbox.app.model.Repeat.ANYTIME && !task.done) {
|
||||
appendIconSpan(title, PinIconSpan(ctx.col(R.color.brand), iconSize))
|
||||
}
|
||||
title.append(badge)
|
||||
title.setSpan(
|
||||
android.text.style.ForegroundColorSpan(ctx.col(badgeColor)),
|
||||
title.length - badge.length, title.length, 0
|
||||
)
|
||||
title.setSpan(RelativeSizeSpan(0.85f), title.length - badge.length, title.length, 0)
|
||||
|
||||
// 重要度圆圈:3 高 / 2 中 / 1 普通,颜色与紧急度同色系
|
||||
val (digit, badgeColor) = when (task.priority) {
|
||||
2 -> "3" to R.color.urgent_high
|
||||
1 -> "2" to R.color.urgent_mid
|
||||
else -> "1" to R.color.urgent_low
|
||||
}
|
||||
// 与标题、与置顶圆圈各留半个旧间距,避免图标贴在一起又不显得散
|
||||
appendIconSpan(title, PriorityBadgeSpan(ctx.col(badgeColor), iconSize, digit))
|
||||
|
||||
// 紧急度五角星:紧急三颗红 / 中两颗绿 / 不急一颗灰
|
||||
val (stars, starColor) = when (task.urgency) {
|
||||
@@ -116,17 +137,6 @@ class TaskAdapter(
|
||||
)
|
||||
title.setSpan(RelativeSizeSpan(0.95f), title.length - stars.length, title.length, 0)
|
||||
|
||||
// 「随时」任务:标题后带品牌蓝圆圈上箭头表示置顶,列表里排在未完成最前面。
|
||||
// 图标与重要度圆圈数字同规格(0.85 倍字号,圆圈里画向上箭头),
|
||||
// 圆圈与箭头同色(品牌蓝);前面的细空格(U+2009)保持与星标的间距一致。
|
||||
if (task.repeatType == com.focusbox.app.model.Repeat.ANYTIME && !task.done) {
|
||||
title.append("\u2009 ")
|
||||
title.setSpan(
|
||||
PinIconSpan(ctx.col(R.color.brand), tvTitle.textSize * 0.85f),
|
||||
title.length - 1, title.length, 0,
|
||||
)
|
||||
}
|
||||
|
||||
// 完成横线只画任务名本身(MidStrikeSpan 限定区间,且划线取文字墨迹
|
||||
// 的垂直中点——系统 StrikethroughSpan 用整字面半高定位,数字/汉字
|
||||
// 会让线显得偏下)。重要度/紧急度/置顶图标不跟着划线。
|
||||
@@ -167,6 +177,10 @@ class TaskAdapter(
|
||||
btnPlay.visible(!task.done)
|
||||
btnPlay.tint(ctx.col(R.color.brand))
|
||||
|
||||
// 完成记录行(一次专注一条)点一下 = 撤销这次完成:源任务回到待办、
|
||||
// 这条记录移除,专注时长仍留在统计里。
|
||||
// v3.19 起不再禁用点击:「全部 / 未完成」视图里一个任务只占一行,
|
||||
// 而这一行就是记录副本,锁住它就没有任何地方能把「完成」改回去。
|
||||
checkWrap.setOnClickListener { onToggle(task) }
|
||||
itemView.setOnClickListener { onEdit(task) }
|
||||
btnPlay.setOnClickListener { onStart(task) }
|
||||
@@ -206,6 +220,22 @@ class TaskAdapter(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 图标间距占位:宽度等于旧版三个空格的一半,且不绘制任何字形。
|
||||
* 用 ReplacementSpan 而不是固定 dp,间距会随字号等比缩放。
|
||||
*/
|
||||
private class IconGapSpan : android.text.style.ReplacementSpan() {
|
||||
|
||||
override fun getSize(
|
||||
paint: Paint, text: CharSequence, start: Int, end: Int, fm: Paint.FontMetricsInt?,
|
||||
): Int = (paint.measureText(" ") / 2f).toInt().coerceAtLeast(1)
|
||||
|
||||
override fun draw(
|
||||
canvas: android.graphics.Canvas, text: CharSequence, start: Int, end: Int,
|
||||
x: Float, top: Int, baseline: Int, bottom: Int, paint: Paint,
|
||||
) = Unit
|
||||
}
|
||||
|
||||
/**
|
||||
* 任务名删除线:系统 StrikethroughSpan 的划线位置按"字体半高"(baseline + ascent/2)
|
||||
* 计算,但数字/汉字的实际墨迹顶比字体 ascent 低不少,划线视觉上偏下。
|
||||
@@ -236,6 +266,61 @@ private class MidStrikeSpan : android.text.style.ReplacementSpan() {
|
||||
}
|
||||
}
|
||||
|
||||
/** 置顶与重要度共用的圆环绘制:同尺寸、同描边(s/10),保证两个圆圈粗细一致。 */
|
||||
private fun drawBadgeRing(
|
||||
canvas: android.graphics.Canvas, cx: Float, cy: Float, size: Float, ringColor: Int,
|
||||
) {
|
||||
val ring = android.graphics.Paint(android.graphics.Paint.ANTI_ALIAS_FLAG).apply {
|
||||
this.color = ringColor
|
||||
style = android.graphics.Paint.Style.STROKE
|
||||
strokeWidth = size / 10f
|
||||
strokeCap = android.graphics.Paint.Cap.ROUND
|
||||
}
|
||||
canvas.drawCircle(cx, cy, size / 2f - ring.strokeWidth / 2f, ring)
|
||||
}
|
||||
|
||||
/**
|
||||
* 重要度圆圈数字:自绘圆环 + 数字,与置顶圆圈共用 drawBadgeRing,
|
||||
* 高度(0.85 倍字号)与描边(s/10)严格一致,不再依赖系统字形 ①②③ 的墨迹差异。
|
||||
*/
|
||||
private class PriorityBadgeSpan(
|
||||
private val badgeColor: Int,
|
||||
private val size: Float,
|
||||
private val digit: String,
|
||||
) : android.text.style.ReplacementSpan() {
|
||||
|
||||
override fun getSize(
|
||||
paint: Paint, text: CharSequence, start: Int, end: Int, fm: Paint.FontMetricsInt?,
|
||||
): Int {
|
||||
val s = size.toInt()
|
||||
if (fm != null) {
|
||||
fm.ascent = -s
|
||||
fm.descent = 0
|
||||
fm.top = fm.ascent
|
||||
fm.bottom = fm.descent
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
override fun draw(
|
||||
canvas: android.graphics.Canvas, text: CharSequence, start: Int, end: Int,
|
||||
x: Float, top: Int, baseline: Int, bottom: Int, paint: Paint,
|
||||
) {
|
||||
val s = size
|
||||
val cy = baseline - s * 0.45f
|
||||
val cx = x + s / 2f
|
||||
drawBadgeRing(canvas, cx, cy, s, badgeColor)
|
||||
val num = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
this.color = badgeColor
|
||||
textSize = s * 0.60f
|
||||
typeface = Typeface.DEFAULT
|
||||
textAlign = Paint.Align.CENTER
|
||||
}
|
||||
val fm = num.fontMetrics
|
||||
canvas.drawText(digit, cx, cy - (fm.ascent + fm.descent) / 2f, num)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 置顶图标:圆圈内向上箭头。
|
||||
* 自绘而不是用字体字形——常用字体里没有"圆圈+箭头"的组合字符,
|
||||
@@ -270,13 +355,8 @@ private class PinIconSpan(
|
||||
// 圆心取基线上方 0.45 个图标高,比之前 0.50 略下移,底部不再"悬空"显偏上
|
||||
val cx = x + s / 2f
|
||||
val cy = baseline - s * 0.45f
|
||||
// 圈线与重要度圆圈数字的描边粗细一致(约 1/10 图标高)
|
||||
val ring = Paint(Paint.ANTI_ALIAS_FLAG)
|
||||
ring.color = iconColor
|
||||
ring.style = Paint.Style.STROKE
|
||||
ring.strokeWidth = s / 10f
|
||||
ring.strokeCap = Paint.Cap.ROUND
|
||||
canvas.drawCircle(cx, cy, s / 2f - ring.strokeWidth / 2f, ring)
|
||||
// 与重要度圆圈共用同一绘制函数:同尺寸、同 1/10 描边,粗细与高度严格一致
|
||||
drawBadgeRing(canvas, cx, cy, s, iconColor)
|
||||
|
||||
// 箭头比圈线更细(约 1/15 图标高),整体落在圆内
|
||||
val arrow = Paint(Paint.ANTI_ALIAS_FLAG)
|
||||
|
||||
@@ -8,7 +8,6 @@ import android.view.WindowManager
|
||||
import android.widget.EditText
|
||||
import android.widget.LinearLayout
|
||||
import android.widget.TextView
|
||||
import androidx.appcompat.app.AlertDialog
|
||||
import com.focusbox.app.R
|
||||
import com.focusbox.app.data.Store
|
||||
import com.focusbox.app.model.Repeat
|
||||
@@ -18,7 +17,9 @@ import com.focusbox.app.ui.SheetDialog
|
||||
import com.focusbox.app.util.Dates
|
||||
import com.focusbox.app.util.Prefs
|
||||
import com.focusbox.app.util.col
|
||||
import com.focusbox.app.util.dpi
|
||||
import com.focusbox.app.util.makeChip
|
||||
import com.focusbox.app.util.roundBg
|
||||
import com.focusbox.app.util.visible
|
||||
import java.util.Calendar
|
||||
|
||||
@@ -32,7 +33,7 @@ class TaskSheet(
|
||||
context: Context,
|
||||
private val existing: Task?,
|
||||
presetProjectId: Long,
|
||||
private val onSaved: () -> Unit,
|
||||
private val onSaved: (Long) -> Unit,
|
||||
) : SheetDialog(context) {
|
||||
|
||||
private val root = LayoutInflater.from(context).inflate(R.layout.sheet_task, null)
|
||||
@@ -57,7 +58,9 @@ class TaskSheet(
|
||||
// 旧数据的时长可能超出新范围(早先是"番茄数×25"),这里统一夹紧
|
||||
private var focusMin: Int = (existing?.focusMinutes ?: Prefs.focusMinutes)
|
||||
.coerceIn(TimerCore.MIN_MINUTES, TimerCore.MAX_MINUTES)
|
||||
private var due: Long = existing?.due ?: 0L
|
||||
// 新建任务默认截止今天:任务页默认按「今日」筛选,不给日期的任务会当场看不见。
|
||||
// 不想带日期就选「随时」,保存时会把日期清掉。
|
||||
private var due: Long = existing?.due ?: Dates.todayStart()
|
||||
private var repeatType: Int = existing?.repeatType ?: Repeat.NONE
|
||||
private var repeatEvery: Int = existing?.repeatEvery ?: 1
|
||||
|
||||
@@ -72,6 +75,8 @@ class TaskSheet(
|
||||
etTitle.setText(existing?.title ?: "")
|
||||
etNote.setText(existing?.note ?: "")
|
||||
renderFocus()
|
||||
// 点数字直接输入时长,微调按钮保留做快速微调
|
||||
tvFocus.setOnClickListener { inputFocus() }
|
||||
|
||||
root.findViewById<View>(R.id.btnFocusMinus).setOnClickListener {
|
||||
focusMin = (focusMin - 5).coerceAtLeast(TimerCore.MIN_MINUTES)
|
||||
@@ -99,22 +104,7 @@ class TaskSheet(
|
||||
|
||||
val btnDelete = root.findViewById<TextView>(R.id.btnDelete)
|
||||
btnDelete.visible(existing != null)
|
||||
btnDelete.setOnClickListener {
|
||||
AlertDialog.Builder(context)
|
||||
.setMessage(R.string.delete_task_confirm)
|
||||
.setNegativeButton(R.string.cancel, null)
|
||||
.setPositiveButton(R.string.delete) { _, _ ->
|
||||
existing?.let {
|
||||
Store.deleteTask(it.id)
|
||||
// 删除的正是当前选中任务时必须解除绑定:
|
||||
// 否则计时继续走,到点后完成记录会落成"未关联任务"
|
||||
if (TimerCore.taskId == it.id) TimerCore.setTask(0, 0)
|
||||
}
|
||||
onSaved()
|
||||
dismiss()
|
||||
}
|
||||
.show()
|
||||
}
|
||||
btnDelete.setOnClickListener { confirmDelete() }
|
||||
|
||||
root.findViewById<View>(R.id.btnSave).setOnClickListener { save() }
|
||||
|
||||
@@ -125,6 +115,48 @@ class TaskSheet(
|
||||
updateDue()
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除确认走自绘圆角弹层,与项目页的确认、本页其余弹层是同一套外观。
|
||||
* 之前这里单独用系统 AlertDialog:圆角、字号、按钮排布都是系统样式,
|
||||
* 夹在一堆自绘弹层里很扎眼。
|
||||
*/
|
||||
private fun confirmDelete() {
|
||||
val task = existing ?: return
|
||||
val ctx = context
|
||||
val sheet = SheetDialog(ctx)
|
||||
val panel = LayoutInflater.from(ctx).inflate(R.layout.sheet_project_actions, null)
|
||||
panel.findViewById<TextView>(R.id.actionsTitle).text = ctx.getString(R.string.delete)
|
||||
panel.findViewById<TextView>(R.id.actionsMessage).apply {
|
||||
text = ctx.getString(R.string.delete_task_confirm)
|
||||
visibility = View.VISIBLE
|
||||
}
|
||||
val list = panel.findViewById<LinearLayout>(R.id.actionsList)
|
||||
listOf(ctx.getString(R.string.cancel) to false, ctx.getString(R.string.delete) to true)
|
||||
.forEachIndexed { index, (label, destructive) ->
|
||||
val row = LayoutInflater.from(ctx).inflate(R.layout.item_action_row, list, false)
|
||||
val tv = row.findViewById<TextView>(R.id.actionLabel)
|
||||
tv.text = label
|
||||
if (destructive) tv.setTextColor(ctx.col(R.color.danger))
|
||||
row.setOnClickListener {
|
||||
sheet.dismiss()
|
||||
if (index == 1) deleteTask(task)
|
||||
}
|
||||
list.addView(row)
|
||||
}
|
||||
sheet.setContentView(panel)
|
||||
sheet.show()
|
||||
}
|
||||
|
||||
private fun deleteTask(task: Task) {
|
||||
// 删除会连同整个任务系列(重复实例 + 完成记录副本)及其专注记录一起删掉,
|
||||
// 只要当前计时绑在这一系列的任意一行上就要解绑,
|
||||
// 否则到点后完成记录会挂到一个已经不存在的任务上
|
||||
val removed = Store.deleteTask(task.id)
|
||||
if (TimerCore.taskId in removed) TimerCore.setTask(0, 0)
|
||||
onSaved(0L)
|
||||
dismiss()
|
||||
}
|
||||
|
||||
private fun renderProjects() {
|
||||
val ctx = context
|
||||
projectRow.removeAllViews()
|
||||
@@ -172,6 +204,88 @@ class TaskSheet(
|
||||
tvFocus.text = context.getString(R.string.minutes_value, focusMin)
|
||||
}
|
||||
|
||||
/**
|
||||
* 专注时长支持直接输入(与设置页「每日目标」同一套交互)。
|
||||
*
|
||||
* 微调按钮一次只有 5 分钟,25 → 90 要点十几次;
|
||||
* 输入后统一夹紧到 [TimerCore.MIN_MINUTES, TimerCore.MAX_MINUTES]。
|
||||
*/
|
||||
private fun inputFocus() {
|
||||
val ctx = context
|
||||
val dialog = android.app.Dialog(ctx)
|
||||
dialog.window?.setBackgroundDrawableResource(android.R.color.transparent)
|
||||
|
||||
val panel = LinearLayout(ctx).apply {
|
||||
orientation = LinearLayout.VERTICAL
|
||||
background = ctx.roundBg(ctx.col(R.color.surface), 16f, ctx.col(R.color.card_stroke), 1f)
|
||||
setPadding(dpi(20f), dpi(20f), dpi(20f), dpi(14f))
|
||||
}
|
||||
panel.addView(TextView(ctx).apply {
|
||||
text = ctx.getString(R.string.focus_duration)
|
||||
textSize = 16f
|
||||
typeface = android.graphics.Typeface.DEFAULT_BOLD
|
||||
setTextColor(ctx.col(R.color.text))
|
||||
})
|
||||
val et = EditText(ctx).apply {
|
||||
inputType = android.text.InputType.TYPE_CLASS_NUMBER
|
||||
setText(focusMin.toString())
|
||||
setSelection(text.length)
|
||||
textSize = 15f
|
||||
setTextColor(ctx.col(R.color.text))
|
||||
background = ctx.roundBg(ctx.col(R.color.surface_alt), 12f)
|
||||
setPadding(dpi(14f), dpi(12f), dpi(14f), dpi(12f))
|
||||
layoutParams = LinearLayout.LayoutParams(
|
||||
LinearLayout.LayoutParams.MATCH_PARENT,
|
||||
LinearLayout.LayoutParams.WRAP_CONTENT,
|
||||
).apply { topMargin = dpi(14f) }
|
||||
}
|
||||
panel.addView(et)
|
||||
|
||||
val btnRow = LinearLayout(ctx).apply {
|
||||
orientation = LinearLayout.HORIZONTAL
|
||||
gravity = android.view.Gravity.END
|
||||
setPadding(0, dpi(12f), 0, 0)
|
||||
}
|
||||
fun btn(labelRes: Int, onClick: () -> Unit) = TextView(ctx).apply {
|
||||
text = ctx.getString(labelRes)
|
||||
textSize = 14f
|
||||
typeface = android.graphics.Typeface.DEFAULT_BOLD
|
||||
gravity = android.view.Gravity.CENTER
|
||||
setTextColor(ctx.col(R.color.brand))
|
||||
background = ctx.roundBg(ctx.col(R.color.surface_alt), 12f)
|
||||
setPadding(dpi(22f), dpi(10f), dpi(22f), dpi(10f))
|
||||
setOnClickListener { onClick() }
|
||||
}
|
||||
btnRow.addView(btn(R.string.cancel) { dialog.dismiss() })
|
||||
btnRow.addView(
|
||||
btn(R.string.save) {
|
||||
val input = et.text.toString().trim().toIntOrNull()
|
||||
if (input == null) {
|
||||
et.error = " "
|
||||
} else {
|
||||
focusMin = input.coerceIn(TimerCore.MIN_MINUTES, TimerCore.MAX_MINUTES)
|
||||
renderFocus()
|
||||
dialog.dismiss()
|
||||
}
|
||||
},
|
||||
LinearLayout.LayoutParams(
|
||||
LinearLayout.LayoutParams.WRAP_CONTENT,
|
||||
LinearLayout.LayoutParams.WRAP_CONTENT,
|
||||
).apply { marginStart = dpi(10f) },
|
||||
)
|
||||
panel.addView(btnRow)
|
||||
|
||||
dialog.setContentView(panel)
|
||||
dialog.show()
|
||||
et.post {
|
||||
et.requestFocus()
|
||||
runCatching {
|
||||
(ctx.getSystemService(Context.INPUT_METHOD_SERVICE) as? android.view.inputmethod.InputMethodManager)
|
||||
?.showSoftInput(et, android.view.inputmethod.InputMethodManager.SHOW_IMPLICIT)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 重复单位五选一;只有真正的周期重复(天/周/月)才露出间隔步进器 */
|
||||
private fun renderRepeat() {
|
||||
val ctx = context
|
||||
@@ -258,7 +372,8 @@ class TaskSheet(
|
||||
periodic && due <= 0 -> Dates.todayStart()
|
||||
else -> due
|
||||
}
|
||||
if (existing == null) {
|
||||
// 回传任务 id:专注页「没有任务 → 立即创建」需要拿新行 id 自动选中
|
||||
val savedId = if (existing == null) {
|
||||
Store.addTask(title, note, projectId, priority, focusMin, effectiveDue, repeatType, every, urgency)
|
||||
} else {
|
||||
Store.updateTask(
|
||||
@@ -274,8 +389,9 @@ class TaskSheet(
|
||||
repeatEvery = every,
|
||||
)
|
||||
)
|
||||
existing.id
|
||||
}
|
||||
onSaved()
|
||||
onSaved(savedId)
|
||||
dismiss()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,8 +28,9 @@ import com.focusbox.app.util.visible
|
||||
*
|
||||
* 项目 / 时间 / 重要度 / 紧急度 / 状态,每栏单选,行内放不下自动换行。
|
||||
* 筛选面板默认收起,只显示一行当前条件摘要;点摘要展开,选中任意胶囊后自动收起。
|
||||
* 默认「项目=全部 · 时间=全部 · 重要度=全部 · 紧急度=全部 · 状态=未完成」,
|
||||
* 与旧版「完成后从列表消失」的行为一致;想看历史切到「已完成」。
|
||||
* 默认「项目=全部 · 时间=今日 · 重要度=全部 · 紧急度=全部 · 状态=全部」:
|
||||
* 只摊今天该做的(截止日早于明天,含逾期)和今天完成的记录。
|
||||
* 一个任务在「全部 / 未完成」里只占一行;每轮专注的独立记录在「已完成」里看。
|
||||
*/
|
||||
class TasksFragment : Fragment(R.layout.fragment_tasks) {
|
||||
|
||||
@@ -43,6 +44,11 @@ class TasksFragment : Fragment(R.layout.fragment_tasks) {
|
||||
const val TIME_WEEK = 3
|
||||
const val TIME_MONTH = 4
|
||||
const val TIME_ANYTIME = 5
|
||||
|
||||
// 状态栏:-1 全部 / 0 未完成 / 1 已完成
|
||||
const val STATUS_ALL = -1
|
||||
const val STATUS_PENDING = 0
|
||||
const val STATUS_DONE = 1
|
||||
}
|
||||
|
||||
private lateinit var recycler: RecyclerView
|
||||
@@ -66,6 +72,9 @@ class TasksFragment : Fragment(R.layout.fragment_tasks) {
|
||||
|
||||
private var projects: List<Project> = emptyList()
|
||||
|
||||
/** 上一次重建筛选面板时的条件指纹:没变就不重建,见 [renderFilters] */
|
||||
private var filterSignature: String? = null
|
||||
|
||||
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
|
||||
super.onViewCreated(view, savedInstanceState)
|
||||
recycler = view.findViewById(R.id.recycler)
|
||||
@@ -83,7 +92,20 @@ class TasksFragment : Fragment(R.layout.fragment_tasks) {
|
||||
adapter = TaskAdapter(
|
||||
onEdit = { openSheet(it) },
|
||||
onToggle = { task ->
|
||||
Store.setTaskDone(task.id, !task.done)
|
||||
if (isCompletionRecord(task)) {
|
||||
// 完成记录行:点一下 = 撤销这次完成。源任务回到待办、这条记录移除;
|
||||
// 已经产生的专注时长留在统计里(那段时间确实专注过)。
|
||||
Store.undoCompletion(task.id)
|
||||
} else if (task.done) {
|
||||
// 取消勾选:恢复这一行待办,撤掉「手动完成」标记
|
||||
Store.setTaskDone(task.id, false, markManual = true)
|
||||
} else {
|
||||
// 手动勾选完成:与专注完成同一口径——从未完成列表消失。
|
||||
// 勾的那行写「手动完成」备注,系列其余待办行一起收尾,
|
||||
// 否则重复任务勾掉实例后根还挂着,归并又会顶出同名行。
|
||||
// 不产生 session,不进累计与饼图(v3.14 口径)。
|
||||
Store.finishTaskManually(task.id)
|
||||
}
|
||||
reload()
|
||||
},
|
||||
onStart = { task -> (activity as? MainActivity)?.startFocusOn(task) },
|
||||
@@ -120,6 +142,11 @@ class TasksFragment : Fragment(R.layout.fragment_tasks) {
|
||||
fun reload() {
|
||||
if (view == null) return
|
||||
projects = Store.projects()
|
||||
// 项目被删掉后,上次选的筛选 id 会一直留在 Prefs 里:列表恒为空,
|
||||
// 摘要又因为找不到项目名回落成「全部」,看起来像"什么都没筛却什么都没有"
|
||||
if (filterProjectId > 0 && projects.none { it.id == filterProjectId }) {
|
||||
filterProjectId = 0L
|
||||
}
|
||||
renderFilters()
|
||||
renderFilterSummary()
|
||||
|
||||
@@ -128,28 +155,38 @@ class TasksFragment : Fragment(R.layout.fragment_tasks) {
|
||||
// 提前完成的任务:源任务行(无备注)隐藏,只显示带备注的独立完成记录
|
||||
val finishedIds = Store.completedSourceIds()
|
||||
|
||||
val matched = all.filter { matches(it) && !(it.done && it.id in finishedIds) }
|
||||
// 「全部 / 未完成」一个任务只占一行:先按当前条件筛出行,再按任务系列归并,
|
||||
// 系列里还有没做完的显示待办那一行,全做完了显示最近一次完成记录。
|
||||
// 每轮专注的独立记录属于历史,只在「已完成」里铺开,
|
||||
// 否则同一个任务会并列出现"未完成"和"已完成"两行。
|
||||
val matched = if (statusFilter == STATUS_DONE) {
|
||||
// 已完成视图看全量记录;被完成副本代表的源任务不重复出现
|
||||
all.filter { it.id !in finishedIds && matches(it) }
|
||||
} else {
|
||||
collapseSeries(all, all.filter { matches(it) })
|
||||
}
|
||||
val rows = ArrayList<TaskAdapter.Row>(matched.size)
|
||||
matched.forEach { rows.add(toRow(it, spans)) }
|
||||
|
||||
val pendingCount = matched.count { !it.done }
|
||||
val doneCount = matched.count { it.done }
|
||||
tvCount.text = when (statusFilter) {
|
||||
1 -> getString(R.string.task_count_done, doneCount)
|
||||
-1 -> getString(R.string.task_count_all, matched.size)
|
||||
STATUS_DONE -> getString(R.string.task_count_done, doneCount)
|
||||
STATUS_ALL -> getString(R.string.task_count_all, matched.size)
|
||||
else -> getString(R.string.task_count, pendingCount)
|
||||
}
|
||||
|
||||
adapter.submitList(rows)
|
||||
tvEmpty.setText(if (isFiltered()) R.string.empty_filtered else R.string.empty_tasks)
|
||||
tvEmpty.visible(rows.isEmpty())
|
||||
recycler.visible(rows.isNotEmpty())
|
||||
|
||||
// 当前筛选条件落盘,重建后恢复
|
||||
Prefs.uiFilterProject = filterProjectId
|
||||
Prefs.uiFilterTime = timeFilter
|
||||
Prefs.uiFilterPriority = priorityFilter
|
||||
Prefs.uiFilterUrgency = urgencyFilter
|
||||
Prefs.uiFilterStatus = statusFilter
|
||||
// 当前筛选条件落盘,重建后恢复。
|
||||
// 只在真的变了才写:reload 会被滚动、切页、onResume 频繁触发,
|
||||
// 逐项赋值等于每次刷新都往 SharedPreferences 写五遍
|
||||
if (Prefs.uiFilterDirty(filterProjectId, timeFilter, priorityFilter, urgencyFilter, statusFilter)) {
|
||||
Prefs.saveUiFilter(filterProjectId, timeFilter, priorityFilter, urgencyFilter, statusFilter)
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ 联动筛选
|
||||
@@ -161,26 +198,99 @@ class TasksFragment : Fragment(R.layout.fragment_tasks) {
|
||||
if (priorityFilter >= 0 && t.priority != priorityFilter) return false
|
||||
if (urgencyFilter >= 0 && t.urgency != urgencyFilter) return false
|
||||
when (statusFilter) {
|
||||
0 -> if (t.done) return false
|
||||
1 -> if (!t.done) return false
|
||||
STATUS_PENDING -> if (t.done) return false
|
||||
STATUS_DONE -> if (!t.done) return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/** 截止日落在所选区间内;随时 = 没有设置截止日 */
|
||||
/**
|
||||
* 时间栏口径,未完成与已完成的判断基准不同:
|
||||
* - 未完成:看截止日。今日 = 截止日早于明天(含已经逾期的),明天/本周/本月 = 落在区间内,
|
||||
* 随时 = 压根没有截止日;
|
||||
* - 已完成(含每轮专注的完成记录):看完成时刻。一条记录属于哪天,按它做完的那天算,
|
||||
* 不能拿源任务的截止日冒充,否则"昨天做完、截止日写的是下周"的记录会从今日里消失。
|
||||
*/
|
||||
private fun matchTime(t: Task): Boolean {
|
||||
val today = Dates.todayStart()
|
||||
if (t.done) {
|
||||
val at = t.doneAt
|
||||
if (at <= 0L) return false
|
||||
return when (timeFilter) {
|
||||
TIME_TODAY -> at >= today && at < Dates.addDays(today, 1)
|
||||
TIME_TOMORROW -> at >= Dates.addDays(today, 1) && at < Dates.addDays(today, 2)
|
||||
TIME_WEEK -> at >= Dates.weekStart() && at < Dates.addDays(Dates.weekStart(), 7)
|
||||
TIME_MONTH -> at >= Dates.monthStart() && at < Dates.addMonths(Dates.monthStart(), 1)
|
||||
TIME_ANYTIME -> false
|
||||
else -> true
|
||||
}
|
||||
}
|
||||
val due = t.due
|
||||
return when (timeFilter) {
|
||||
TIME_TODAY -> due >= today && due < Dates.addDays(today, 1)
|
||||
// 今日含逾期:截止日早于明天即算今天该做的
|
||||
TIME_TODAY -> due > 0 && due < Dates.addDays(today, 1)
|
||||
TIME_TOMORROW -> due >= Dates.addDays(today, 1) && due < Dates.addDays(today, 2)
|
||||
TIME_WEEK -> due >= Dates.weekStart() && due < Dates.addDays(Dates.weekStart(), 7)
|
||||
TIME_MONTH -> due >= Dates.monthStart() && due < Dates.addMonths(Dates.monthStart(), 1)
|
||||
TIME_WEEK -> due > 0 && due >= Dates.weekStart() && due < Dates.addDays(Dates.weekStart(), 7)
|
||||
TIME_MONTH -> due > 0 && due >= Dates.monthStart() && due < Dates.addMonths(Dates.monthStart(), 1)
|
||||
TIME_ANYTIME -> due <= 0L
|
||||
else -> true
|
||||
}
|
||||
}
|
||||
|
||||
/** 完成记录行(一次专注一条,origin 指回源任务):只作历史展示,不参与勾选 */
|
||||
private fun isCompletionRecord(t: Task): Boolean =
|
||||
t.done && t.originId > 0 && t.repeatType == com.focusbox.app.model.Repeat.NONE
|
||||
|
||||
/** 是否有任一条件偏离默认值(默认:项目全部 · 时间今日 · 其余全部) */
|
||||
private fun isFiltered(): Boolean =
|
||||
filterProjectId > 0L || timeFilter != TIME_TODAY ||
|
||||
priorityFilter >= 0 || urgencyFilter >= 0 || statusFilter != STATUS_ALL
|
||||
|
||||
/**
|
||||
* 同一任务系列只保留一行。
|
||||
*
|
||||
* 一次专注会生成一条独立完成记录(origin 指回源任务),原样铺进列表时同一个任务
|
||||
* 会并列出现"未完成"和"已完成"两行。规则:
|
||||
* - 系列里还有未完成的 → 取未完成的最新一条(重复任务当前这一轮);
|
||||
* - 全部完成 → 取最近一条完成记录(没有记录时退回最近完成的那一行);
|
||||
* - 顺序沿用 Store.tasks 的排序。
|
||||
*/
|
||||
private fun collapseSeries(all: List<Task>, list: List<Task>): List<Task> {
|
||||
if (list.size < 2) return list
|
||||
// 回溯系列根要用**全量**任务:系列根恰好不在当前筛选结果里时,
|
||||
// 只看候选行会让同一系列的几条完成记录各自成组,又铺成好几行。
|
||||
val byId = HashMap<Long, Task>(all.size)
|
||||
val order = HashMap<Long, Int>(all.size)
|
||||
all.forEachIndexed { i, t ->
|
||||
byId[t.id] = t
|
||||
order[t.id] = i
|
||||
}
|
||||
val groups = LinkedHashMap<Long, MutableList<Task>>()
|
||||
for (t in list) {
|
||||
// 沿 origin 链回溯到系列根;链条断在已被删除的行上时,当前行自身即根
|
||||
var root = t
|
||||
var guard = 0
|
||||
while (root.originId > 0 && guard++ < 16) {
|
||||
root = byId[root.originId] ?: break
|
||||
}
|
||||
groups.getOrPut(root.id) { ArrayList(2) }.add(t)
|
||||
}
|
||||
val out = ArrayList<Task>(groups.size)
|
||||
for (g in groups.values) {
|
||||
val pending = g.filter { !it.done }
|
||||
out.add(
|
||||
if (pending.isNotEmpty()) {
|
||||
pending.maxWith(compareBy<Task>({ it.due }, { it.id }))
|
||||
} else {
|
||||
val records = g.filter { isCompletionRecord(it) }
|
||||
(records.ifEmpty { g }).maxWith(compareBy<Task>({ it.doneAt }, { it.id }))
|
||||
}
|
||||
)
|
||||
}
|
||||
out.sortBy { order[it.id] ?: Int.MAX_VALUE }
|
||||
return out
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ 筛选面板
|
||||
|
||||
/**
|
||||
@@ -281,14 +391,30 @@ class TasksFragment : Fragment(R.layout.fragment_tasks) {
|
||||
tvFilterSummary.text = listOf(project, time, priority, urgency, status).joinToString(" · ")
|
||||
|
||||
// 有任一条件偏离默认值时摘要高亮,提示当前列表被筛过
|
||||
val filtered = filterProjectId > 0L || timeFilter != TIME_ALL ||
|
||||
priorityFilter >= 0 || urgencyFilter >= 0 || statusFilter != 0
|
||||
tvFilterSummary.setTextColor(
|
||||
ctx.col(if (filtered) R.color.brand else R.color.text_secondary)
|
||||
ctx.col(if (isFiltered()) R.color.brand else R.color.text_secondary)
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 筛选面板:项目集合或选中态没变时直接复用现有视图。
|
||||
*
|
||||
* 原来每次 reload 都 removeAllViews 重建全部胶囊,而 reload 会被滚动跨天、
|
||||
* 切页、onResume、保存任务反复触发;项目一多,重建就是可见的卡顿。
|
||||
*/
|
||||
private fun renderFilters() {
|
||||
val signature = buildString(96) {
|
||||
append(filterProjectId).append('|')
|
||||
append(timeFilter).append('|').append(priorityFilter).append('|')
|
||||
append(urgencyFilter).append('|').append(statusFilter)
|
||||
projects.forEach {
|
||||
append('|').append(it.id).append(':').append(it.name)
|
||||
append(':').append(if (it.archived) 1 else 0).append(':').append(it.color)
|
||||
}
|
||||
}
|
||||
if (signature == filterSignature && filterPanel.childCount > 0) return
|
||||
filterSignature = signature
|
||||
|
||||
filterPanel.removeAllViews()
|
||||
val ctx = requireContext()
|
||||
|
||||
@@ -382,7 +508,10 @@ class TasksFragment : Fragment(R.layout.fragment_tasks) {
|
||||
|
||||
private fun toRow(task: Task, spans: Map<Long, SessionSpan>): TaskAdapter.Row.Item {
|
||||
val project = projects.firstOrNull { it.id == task.projectId }
|
||||
val overdue = task.due > 0 && task.due < Dates.todayStart()
|
||||
// 重复任务按周期滚动,本轮没做不算逾期(下一轮生成时会自动结束旧实例);
|
||||
// 只有不重复的任务才标「已逾期」
|
||||
val overdue = task.due > 0 && task.due < Dates.todayStart() &&
|
||||
task.repeatType == com.focusbox.app.model.Repeat.NONE
|
||||
return TaskAdapter.Row.Item(
|
||||
task = task,
|
||||
projectName = project?.name ?: getString(R.string.inbox),
|
||||
@@ -398,23 +527,30 @@ class TasksFragment : Fragment(R.layout.fragment_tasks) {
|
||||
if (task.logSeconds > 0 && task.originId > 0 && task.doneAt > task.createdAt) {
|
||||
val range = "${Dates.dateWithWeek(task.createdAt)} " +
|
||||
"${Dates.hms(task.createdAt)}-${Dates.hms(task.doneAt)}"
|
||||
return "$range · 专注${Dates.duration(task.logSeconds)}"
|
||||
return getString(R.string.done_meta, range, Dates.duration(task.logSeconds))
|
||||
}
|
||||
val span = spans[task.id]
|
||||
if (span != null) {
|
||||
val range = "${Dates.dateWithWeek(span.startAt)} " +
|
||||
"${Dates.hms(span.startAt)}-${Dates.hms(span.endAt)}"
|
||||
// 记录里存的是实际专注秒数(不含暂停),不能拿起止时间差冒充
|
||||
return if (span.seconds > 0) "$range · 专注${Dates.duration(span.seconds)}" else range
|
||||
return if (span.seconds > 0) {
|
||||
getString(R.string.done_meta, range, Dates.duration(span.seconds))
|
||||
} else {
|
||||
range
|
||||
}
|
||||
}
|
||||
if (task.doneAt > 0) {
|
||||
return "${Dates.dateWithWeek(task.doneAt)} ${Dates.hms(task.doneAt)}"
|
||||
return getString(
|
||||
R.string.done_at_only,
|
||||
"${Dates.dateWithWeek(task.doneAt)} ${Dates.hms(task.doneAt)}",
|
||||
)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private fun openSheet(task: Task?) {
|
||||
// 新建任务时默认归到当前筛选的项目;全部/收件箱则不预选
|
||||
// 新建任务时默认归到当前筛选的项目;全部/未分类则不预选
|
||||
TaskSheet(requireContext(), task, filterProjectId.takeIf { it > 0 } ?: 0L) { reload() }.show()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.focusbox.app.util
|
||||
|
||||
import android.content.res.Resources
|
||||
import com.focusbox.app.R
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Calendar
|
||||
import java.util.Date
|
||||
@@ -8,13 +10,31 @@ import java.util.Locale
|
||||
/** 时间格式化与"自然日"边界计算,全局只此一份,避免各处口径不一。 */
|
||||
object Dates {
|
||||
|
||||
/**
|
||||
* 时长单位文案。之前「秒 / 分钟 / 小时 / 分」直接写在代码里,
|
||||
* 与"文案全在 strings.xml"的现状不一致;由 App 启动时注入一次资源即可。
|
||||
*/
|
||||
private lateinit var res: Resources
|
||||
|
||||
fun attach(resources: Resources) {
|
||||
res = resources
|
||||
}
|
||||
|
||||
private val keyFmt = SimpleDateFormat("yyyy-MM-dd", Locale.US)
|
||||
private val mdFmt = SimpleDateFormat("M/d", Locale.CHINA)
|
||||
private val mdFmt2 = SimpleDateFormat("M月d日", Locale.CHINA)
|
||||
private val hmFmt = SimpleDateFormat("HH:mm", Locale.CHINA)
|
||||
private val hmsFmt = SimpleDateFormat("HH:mm:ss", Locale.CHINA)
|
||||
|
||||
fun dayKey(ms: Long): String = keyFmt.format(Date(ms))
|
||||
/**
|
||||
* SimpleDateFormat 不是线程安全的。
|
||||
* 目前这些格式化全在主线程调用,但一旦挪到后台(通知、统计异步化)就会静默出错,
|
||||
* 所以统一走加锁的薄封装,成本只有一次监视器进出。
|
||||
*/
|
||||
private fun format(f: SimpleDateFormat, ms: Long): String =
|
||||
synchronized(f) { f.format(Date(ms)) }
|
||||
|
||||
fun dayKey(ms: Long): String = format(keyFmt, ms)
|
||||
|
||||
fun dayStart(ms: Long): Long {
|
||||
val c = Calendar.getInstance()
|
||||
@@ -26,7 +46,8 @@ object Dates {
|
||||
return c.timeInMillis
|
||||
}
|
||||
|
||||
fun dayStartOfKey(key: String): Long = keyFmt.parse(key)?.time ?: 0L
|
||||
fun dayStartOfKey(key: String): Long =
|
||||
synchronized(keyFmt) { keyFmt.parse(key)?.time } ?: 0L
|
||||
|
||||
fun todayStart(): Long = dayStart(System.currentTimeMillis())
|
||||
|
||||
@@ -91,22 +112,32 @@ object Dates {
|
||||
return c.timeInMillis
|
||||
}
|
||||
|
||||
/** 12:30 这种时钟显示;不足 10 分钟显示 09:30 两位分 */
|
||||
/**
|
||||
* 计时读数。不足 1 小时是 mm:ss,满 1 小时自动变 h:mm:ss。
|
||||
*
|
||||
* 原来固定按分:秒输出,正计时到 90 分钟会显示成 90:00,两小时就是三位数,
|
||||
* 把圆环和锁屏的固定排版挤变形(锁屏那套排版是写死 dp 的,不能自适应)。
|
||||
*/
|
||||
fun clock(ms: Long): String {
|
||||
val total = (ms / 1000).coerceAtLeast(0)
|
||||
val m = total / 60
|
||||
val h = total / 3600
|
||||
val m = total % 3600 / 60
|
||||
val s = total % 60
|
||||
return String.format(Locale.US, "%02d:%02d", m, s)
|
||||
return if (h > 0) {
|
||||
String.format(Locale.US, "%d:%02d:%02d", h, m, s)
|
||||
} else {
|
||||
String.format(Locale.US, "%02d:%02d", m, s)
|
||||
}
|
||||
}
|
||||
|
||||
/** 45m / 2h10m / 12.5h,统计里统一用这个口径 */
|
||||
fun duration(seconds: Int): String {
|
||||
if (seconds < 60) return "${seconds}秒"
|
||||
if (seconds < 60) return res.getString(R.string.dur_seconds, seconds)
|
||||
val minutes = seconds / 60
|
||||
if (minutes < 60) return "${minutes}分钟"
|
||||
if (minutes < 60) return res.getString(R.string.dur_minutes, minutes)
|
||||
val h = minutes / 60
|
||||
val m = minutes % 60
|
||||
return if (m == 0) "${h}小时" else "${h}小时${m}分"
|
||||
return if (m == 0) res.getString(R.string.dur_hours, h) else res.getString(R.string.dur_hm, h, m)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -123,19 +154,10 @@ object Dates {
|
||||
return if (m == 0) "${h}h" else "${h}h ${m}m"
|
||||
}
|
||||
|
||||
/** 图表坐标轴用的短格式:2h / 45m */
|
||||
fun shortDuration(seconds: Int): String {
|
||||
if (seconds <= 0) return "0"
|
||||
val minutes = seconds / 60
|
||||
if (minutes < 60) return "${minutes}m"
|
||||
val h = minutes / 60f
|
||||
return if (h >= 10) "${h.toInt()}h" else String.format(Locale.US, "%.1fh", h)
|
||||
}
|
||||
|
||||
fun md(ms: Long): String = mdFmt.format(Date(ms))
|
||||
fun mdLong(ms: Long): String = mdFmt2.format(Date(ms))
|
||||
fun hm(ms: Long): String = hmFmt.format(Date(ms))
|
||||
fun hms(ms: Long): String = hmsFmt.format(Date(ms))
|
||||
fun md(ms: Long): String = format(mdFmt, ms)
|
||||
fun mdLong(ms: Long): String = format(mdFmt2, ms)
|
||||
fun hm(ms: Long): String = format(hmFmt, ms)
|
||||
fun hms(ms: Long): String = format(hmsFmt, ms)
|
||||
|
||||
/** 周五 / 周一 */
|
||||
fun weekday(ms: Long): String {
|
||||
|
||||
@@ -1,9 +1,24 @@
|
||||
package com.focusbox.app.util
|
||||
|
||||
/** 项目配色。八色一组,两两之间在色相上有足够间距,圆点上也能分辨。 */
|
||||
/**
|
||||
* 项目配色:20 色。
|
||||
*
|
||||
* 取舍说明(改之前先读):
|
||||
* 1. 前 8 色是 v3.13 及以前就有的配色,色值与顺序**永不改动** ——
|
||||
* 老项目已经用了这些颜色,扩容不能让它整体位移;
|
||||
* 2. 20 个颜色要塞进一个色相环,平均只能分到 18°,所以「两两都不像」
|
||||
* 在数学上做不到。真正有效的区分手段是**同时拉开色相和明度**,
|
||||
* 这也是新增 12 色的挑选标准:亮的一档(L≈65)与暗的一档(L≈38)
|
||||
* 交替出现,相邻格子永远一亮一暗,不会出现「一排浅色看起来都一样」;
|
||||
* 3. 所有颜色两两之间 CIE ΔE00 ≥ 15(前 8 色里 #4C8C4A / #3F7F6E 那对 14.3
|
||||
* 是历史配色,不在本次调整范围)。上一版按「同色相浅色版」做的 8 个浅色
|
||||
* (浅粉/浅橙/浅黄…)虽然 ΔE 也够,但明度全挤在 70 附近,肉眼看着一样,已整体废弃;
|
||||
* 4. 排序按「暖 → 冷」铺开,同色相的深浅两档分到两排,避免同屏对比。
|
||||
*/
|
||||
object Palette {
|
||||
|
||||
val colors = intArrayOf(
|
||||
// ---- 原有 8 色(色值、顺序保持不变)
|
||||
0xFFC75B45.toInt(), // 陶土红
|
||||
0xFFD98324.toInt(), // 琥珀
|
||||
0xFFC9A227.toInt(), // 芥黄
|
||||
@@ -12,9 +27,23 @@ object Palette {
|
||||
0xFF3B7DD8.toInt(), // 靛蓝
|
||||
0xFF6C5CE7.toInt(), // 紫
|
||||
0xFFB7548E.toInt(), // 玫红
|
||||
// ---- 第一排剩下 2 个:亮青 + 亮黄,和上面的玫红、琥珀形成强反差
|
||||
0xFF56D3DC.toInt(), // 亮青
|
||||
0xFFE0D867.toInt(), // 亮黄
|
||||
// ---- 第二排 10 个:深/浅交替,相邻永远一亮一暗
|
||||
0xFF3523A9.toInt(), // 深蓝紫(深)
|
||||
0xFFA67DCA.toInt(), // 淡紫(浅)
|
||||
0xFF91743B.toInt(), // 卡其(深)
|
||||
0xFF97E067.toInt(), // 嫩绿(浅)
|
||||
0xFFA92347.toInt(), // 深红(深)
|
||||
0xFF43C79B.toInt(), // 薄荷(浅)
|
||||
0xFF9D26BA.toInt(), // 品红紫(深)
|
||||
0xFF91A63A.toInt(), // 橄榄绿(浅,偏中性)
|
||||
0xFFCA7D87.toInt(), // 灰粉(浅)
|
||||
0xFF3495AD.toInt(), // 湖蓝(深)
|
||||
)
|
||||
|
||||
/** 收件箱用中性灰,避免和自建项目争注意力 */
|
||||
/** 未分类用中性灰,避免和自建项目争注意力 */
|
||||
const val INBOX = 0xFF7A756C.toInt()
|
||||
|
||||
fun colorAt(index: Int): Int = colors[index.mod(colors.size)]
|
||||
|
||||
18
src/main/java/com/focusbox/app/util/Percent.kt
Normal file
18
src/main/java/com/focusbox/app/util/Percent.kt
Normal file
@@ -0,0 +1,18 @@
|
||||
package com.focusbox.app.util
|
||||
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
/**
|
||||
* 占比文案。环上的小字与环下方的明细必须共用这一个实现。
|
||||
*
|
||||
* 两处各写一套取整会打架:环上原来 `roundToInt().coerceAtLeast(1)` 把 0.6% 写成 1%,
|
||||
* 明细里判 `pct < 1` 写成「<1%」,同一块切片在两个地方显示两个数,
|
||||
* 看上去就像"排第 7 的牵了线、前 6 反而没牵"。
|
||||
*
|
||||
* 规则:四舍五入;不足 1% 统一写「<1%」。
|
||||
*/
|
||||
fun percentText(part: Int, total: Int): String {
|
||||
if (total <= 0) return "0%"
|
||||
val pct = part * 100.0 / total
|
||||
return if (pct < 1.0) "<1%" else "${pct.roundToInt()}%"
|
||||
}
|
||||
@@ -15,6 +15,23 @@ object Prefs {
|
||||
|
||||
fun init(context: Context) {
|
||||
sp = context.getSharedPreferences("focusbox", Context.MODE_PRIVATE)
|
||||
// 一次性把旧的默认「未完成」改为「全部」:任务页要同时看到逾期与完成记录。
|
||||
// 用户之后仍可手动切回「未完成」,迁移只执行一次。
|
||||
if (!sp.getBoolean("ui_filter_status_all_migrated", false)) {
|
||||
if (sp.getInt("ui_filter_status", 0) == 0) {
|
||||
sp.edit().putInt("ui_filter_status", -1).apply()
|
||||
}
|
||||
sp.edit().putBoolean("ui_filter_status_all_migrated", true).apply()
|
||||
}
|
||||
// 时间筛选默认改为「今日」:原来的默认「全部」会把明天、下周、下个月的任务
|
||||
// 全摊在今天的列表里,看起来像"没设过的任务自己冒出来"。迁移只执行一次,
|
||||
// 用户之后手动切回「全部」不会被改回去。
|
||||
if (!sp.getBoolean("ui_filter_time_today_migrated", false)) {
|
||||
if (sp.getInt("ui_filter_time", 0) == 0) {
|
||||
sp.edit().putInt("ui_filter_time", 1).apply()
|
||||
}
|
||||
sp.edit().putBoolean("ui_filter_time_today_migrated", true).apply()
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 时长 ----
|
||||
@@ -61,6 +78,18 @@ object Prefs {
|
||||
get() = sp.getBoolean("lock_fullscreen", true)
|
||||
set(v) = sp.edit().putBoolean("lock_fullscreen", v).apply()
|
||||
|
||||
/**
|
||||
* 锁屏倒计时页最近一次真正显示出来的时刻。
|
||||
*
|
||||
* 华为/鸿蒙的「应用启动管理」没有公开查询接口,但它拦截后台拉起页面是
|
||||
* **静默**的:被拦截时 LockScreenActivity 的 onCreate/onStart 根本不会执行。
|
||||
* 所以这个时间戳就是"锁屏显示权限确实生效"的实证 —— 从来没有值,
|
||||
* 说明一次都没成功盖到锁屏上。
|
||||
*/
|
||||
var lockShownAt: Long
|
||||
get() = sp.getLong("lock_shown_at", 0L)
|
||||
set(v) = sp.edit().putLong("lock_shown_at", v).apply()
|
||||
|
||||
// ---- 目标 ----
|
||||
// 无上限:输入多大存多大(下限 15 防止误输 0/负数把目标显示搞崩)
|
||||
var dailyGoalMinutes: Int
|
||||
@@ -72,6 +101,39 @@ object Prefs {
|
||||
get() = sp.getInt("theme_mode", 0)
|
||||
set(v) = sp.edit().putInt("theme_mode", v).apply()
|
||||
|
||||
// ---- 项目类型 ----
|
||||
|
||||
/** 内置默认类型:设置页没改过时用它,保证新建项目一打开就有可选值 */
|
||||
val defaultProjectTypes = listOf("工作", "学习", "娱乐", "提升")
|
||||
|
||||
/**
|
||||
* 可选的项目类型,落盘为英文逗号分隔的一行。
|
||||
*
|
||||
* 保存时统一去空格、去空项、去重(保序),避免「工作, 工作 ,」这种输入
|
||||
* 在项目弹层里生成重复胶囊、在类型饼图里被拆成两块。
|
||||
* 清空后回落到默认四项——没有类型可选会让「类型」字段变成死字段。
|
||||
*/
|
||||
var projectTypes: List<String>
|
||||
get() {
|
||||
val raw = sp.getString("project_types", "").orEmpty()
|
||||
// v3.22 起存 JSON 数组:类型名里带英文逗号也不会被拆成两个。
|
||||
// 旧版本存的是逗号拼接的纯文本,读到不是 '[' 开头的一律按旧格式解析,
|
||||
// 用户不用重新录一遍类型。
|
||||
val parsed = if (raw.trimStart().startsWith("[")) {
|
||||
runCatching {
|
||||
val arr = org.json.JSONArray(raw)
|
||||
(0 until arr.length()).map { arr.optString(it) }
|
||||
}.getOrDefault(emptyList())
|
||||
} else {
|
||||
raw.split(',')
|
||||
}.map { it.trim() }.filter { it.isNotEmpty() }.distinct()
|
||||
return parsed.ifEmpty { defaultProjectTypes }
|
||||
}
|
||||
set(v) {
|
||||
val cleaned = v.map { it.trim() }.filter { it.isNotEmpty() }.distinct()
|
||||
sp.edit().putString("project_types", org.json.JSONArray(cleaned).toString()).apply()
|
||||
}
|
||||
|
||||
// ---- 计时状态 ----
|
||||
var timerMode: Int
|
||||
get() = sp.getInt("t_mode", 0)
|
||||
@@ -153,7 +215,7 @@ object Prefs {
|
||||
set(v) = sp.edit().putLong("ui_filter_project", v).apply()
|
||||
|
||||
var uiFilterTime: Int
|
||||
get() = sp.getInt("ui_filter_time", 0)
|
||||
get() = sp.getInt("ui_filter_time", 1)
|
||||
set(v) = sp.edit().putInt("ui_filter_time", v).apply()
|
||||
|
||||
var uiFilterPriority: Int
|
||||
@@ -165,24 +227,99 @@ object Prefs {
|
||||
set(v) = sp.edit().putInt("ui_filter_urgency", v).apply()
|
||||
|
||||
var uiFilterStatus: Int
|
||||
get() = sp.getInt("ui_filter_status", 0)
|
||||
get() = sp.getInt("ui_filter_status", -1)
|
||||
set(v) = sp.edit().putInt("ui_filter_status", v).apply()
|
||||
|
||||
var uiFilterExpanded: Boolean
|
||||
get() = sp.getBoolean("ui_filter_expanded", false)
|
||||
set(v) = sp.edit().putBoolean("ui_filter_expanded", v).apply()
|
||||
|
||||
/** 五栏筛选一次提交:任务页每次 reload 都逐项赋值会连触发五次 apply */
|
||||
fun saveUiFilter(project: Long, time: Int, priority: Int, urgency: Int, status: Int) {
|
||||
sp.edit()
|
||||
.putLong("ui_filter_project", project)
|
||||
.putInt("ui_filter_time", time)
|
||||
.putInt("ui_filter_priority", priority)
|
||||
.putInt("ui_filter_urgency", urgency)
|
||||
.putInt("ui_filter_status", status)
|
||||
.apply()
|
||||
}
|
||||
|
||||
/** 当前落盘值与内存值是否一致,用于跳过无意义的写盘 */
|
||||
fun uiFilterDirty(project: Long, time: Int, priority: Int, urgency: Int, status: Int): Boolean =
|
||||
uiFilterProject != project || uiFilterTime != time || uiFilterPriority != priority ||
|
||||
uiFilterUrgency != urgency || uiFilterStatus != status
|
||||
|
||||
/**
|
||||
* 计时状态的批量落盘:TimerCore 每次状态变更要写十几个字段,
|
||||
* 逐个属性 setter 会走十几次 Editor.apply()(十几次磁盘写入);
|
||||
* 这里合成一次提交,语义完全相同。
|
||||
*/
|
||||
fun saveTimer(
|
||||
mode: Int,
|
||||
running: Boolean,
|
||||
countUp: Boolean,
|
||||
totalMs: Long,
|
||||
remainingMs: Long,
|
||||
endAt: Long,
|
||||
endElapsed: Long,
|
||||
clockOffset: Long,
|
||||
pauseReason: String,
|
||||
roundNotes: String,
|
||||
pauseStartAt: Long,
|
||||
pauseTaskId: Long,
|
||||
startedAt: Long,
|
||||
taskId: Long,
|
||||
projectId: Long,
|
||||
round: Int,
|
||||
accumMs: Long,
|
||||
) {
|
||||
sp.edit()
|
||||
.putInt("t_mode", mode)
|
||||
.putBoolean("t_running", running)
|
||||
.putBoolean("t_countup", countUp)
|
||||
.putLong("t_total", totalMs)
|
||||
.putLong("t_remaining", remainingMs)
|
||||
.putLong("t_end", endAt)
|
||||
.putLong("t_end_elapsed", endElapsed)
|
||||
.putLong("t_clock_offset", clockOffset)
|
||||
.putString("t_pause_reason", pauseReason)
|
||||
.putString("t_round_notes", roundNotes)
|
||||
.putLong("t_pause_start", pauseStartAt)
|
||||
.putLong("t_pause_task", pauseTaskId)
|
||||
.putLong("t_started", startedAt)
|
||||
.putLong("t_task", taskId)
|
||||
.putLong("t_project", projectId)
|
||||
.putInt("t_round", round)
|
||||
.putLong("t_accum", accumMs)
|
||||
.apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* 清空所有数据时复位计时状态。
|
||||
*
|
||||
* 必须连任务绑定一起清:只清运行态的话,TimerCore 内存里的 taskId 和这里的
|
||||
* t_task / t_project / t_total 都还指着已经被删掉的行,下一轮专注写出来的
|
||||
* session 立刻变成「未关联记录」。
|
||||
*/
|
||||
fun clearTimer() {
|
||||
sp.edit()
|
||||
.putInt("t_mode", 0)
|
||||
.putBoolean("t_running", false)
|
||||
.putBoolean("t_countup", false)
|
||||
.putLong("t_total", 0L)
|
||||
.putLong("t_remaining", 0L)
|
||||
.putLong("t_end", 0L)
|
||||
.putLong("t_end_elapsed", 0L)
|
||||
.putLong("t_clock_offset", 0L)
|
||||
.putString("t_pause_reason", "")
|
||||
.putString("t_round_notes", "")
|
||||
.putLong("t_pause_start", 0L)
|
||||
.putLong("t_pause_task", 0L)
|
||||
.putLong("t_started", 0L)
|
||||
.putLong("t_task", 0L)
|
||||
.putLong("t_project", 0L)
|
||||
.putInt("t_round", 0)
|
||||
.putLong("t_accum", 0L)
|
||||
.apply()
|
||||
}
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
package com.focusbox.app.util
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Typeface
|
||||
import android.graphics.drawable.GradientDrawable
|
||||
import android.text.Spannable
|
||||
import android.text.SpannableString
|
||||
import android.text.style.ForegroundColorSpan
|
||||
import android.text.style.StyleSpan
|
||||
import android.util.TypedValue
|
||||
import android.view.View
|
||||
import android.widget.ImageView
|
||||
@@ -9,6 +14,8 @@ import android.widget.TextView
|
||||
import androidx.annotation.ColorRes
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.core.graphics.drawable.DrawableCompat
|
||||
import com.focusbox.app.R
|
||||
import com.focusbox.app.model.Project
|
||||
|
||||
fun Context.dpf(v: Float): Float = v * resources.displayMetrics.density
|
||||
|
||||
@@ -95,3 +102,38 @@ fun View.pad(h: Float, v: Float) {
|
||||
fun TextView.setAlphaCompat(a: Float) {
|
||||
alpha = a
|
||||
}
|
||||
|
||||
/**
|
||||
* 项目统计行文案,项目页卡片与专注页「选任务」第一步共用,口径必须一致:
|
||||
* 类型(项目色加粗,超 6 字截断) · N个任务 · 已完成M次 · 累计时长
|
||||
*
|
||||
* 统计口径(全周期累计,不是今日,也没有时间上限):
|
||||
* 任务数 = 项目下创建的任务本体(不含重复实例/完成记录副本);
|
||||
* 已完成 = 真实跑完的专注次数(sessions.completed = 1 的条数),
|
||||
* 手动勾选完成、周期滚动时的自动完成都没有专注记录,不计入;
|
||||
* 时长 = 该项目全部专注记录秒数之和,不足 1 分钟不显示。
|
||||
* 未设置类型时不占位。
|
||||
*/
|
||||
fun Context.projectMetaLine(p: Project): CharSequence {
|
||||
// 类型名过长会把后面的「N个任务 / 已完成 / 时长」挤出屏幕(meta 行是单行省略),
|
||||
// 所以先按字符数截断类型名,保证计数始终可见
|
||||
val typeRaw = p.type.trim()
|
||||
val typeText = if (typeRaw.length > 6) typeRaw.take(6) + "…" else typeRaw
|
||||
val parts = ArrayList<String>(4)
|
||||
if (typeText.isNotEmpty()) parts.add(typeText)
|
||||
parts.add(getString(R.string.project_tasks_total, p.totalTasks))
|
||||
if (p.pomodoros > 0) parts.add(getString(R.string.project_tasks_done, p.pomodoros))
|
||||
if (p.focusSeconds >= 60) parts.add(Dates.duration(p.focusSeconds))
|
||||
val line = SpannableString(parts.joinToString(" · "))
|
||||
if (typeText.isNotEmpty()) {
|
||||
line.setSpan(
|
||||
ForegroundColorSpan(p.color), 0, typeText.length,
|
||||
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE,
|
||||
)
|
||||
line.setSpan(
|
||||
StyleSpan(Typeface.BOLD), 0, typeText.length,
|
||||
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE,
|
||||
)
|
||||
}
|
||||
return line
|
||||
}
|
||||
|
||||
@@ -8,7 +8,6 @@ import android.util.AttributeSet
|
||||
import android.view.View
|
||||
import com.focusbox.app.R
|
||||
import com.focusbox.app.model.DayPoint
|
||||
import com.focusbox.app.model.ProjectSlice
|
||||
import com.focusbox.app.util.Dates
|
||||
import com.focusbox.app.util.col
|
||||
import com.focusbox.app.util.dpf
|
||||
@@ -180,71 +179,3 @@ class HeatmapView @JvmOverloads constructor(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 项目占比环:中间显示总时长,环上按项目分色。 */
|
||||
class DonutView @JvmOverloads constructor(
|
||||
context: Context,
|
||||
attrs: AttributeSet? = null,
|
||||
) : View(context, attrs) {
|
||||
|
||||
private var slices: List<ProjectSlice> = emptyList()
|
||||
|
||||
private val arcPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
style = Paint.Style.STROKE
|
||||
strokeWidth = context.dpf(16f)
|
||||
strokeCap = Paint.Cap.BUTT
|
||||
}
|
||||
private val trackPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
style = Paint.Style.STROKE
|
||||
strokeWidth = context.dpf(16f)
|
||||
color = context.col(R.color.ring_track)
|
||||
}
|
||||
private val valuePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
textSize = context.spf(19f)
|
||||
color = context.col(R.color.title)
|
||||
textAlign = Paint.Align.CENTER
|
||||
isFakeBoldText = true
|
||||
}
|
||||
private val labelPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
textSize = context.spf(10f)
|
||||
color = context.col(R.color.text_tertiary)
|
||||
textAlign = Paint.Align.CENTER
|
||||
}
|
||||
|
||||
fun setSlices(list: List<ProjectSlice>) {
|
||||
slices = list
|
||||
invalidate()
|
||||
}
|
||||
|
||||
/** 环中心的说明文字(项目分布 / 任务分布共用这个控件) */
|
||||
var caption: String = ""
|
||||
set(value) {
|
||||
field = value
|
||||
invalidate()
|
||||
}
|
||||
|
||||
override fun onDraw(canvas: Canvas) {
|
||||
val r = minOf(width, height) / 2f - arcPaint.strokeWidth / 2f - context.dpf(2f)
|
||||
val cx = width / 2f
|
||||
val cy = height / 2f
|
||||
canvas.drawCircle(cx, cy, r, trackPaint)
|
||||
|
||||
val box = RectF(cx - r, cy - r, cx + r, cy + r)
|
||||
val total = slices.sumOf { it.seconds }
|
||||
if (total > 0) {
|
||||
var start = -90f
|
||||
val gapDeg = if (slices.size > 1) 2.4f else 0f
|
||||
slices.forEach { s ->
|
||||
val sweep = s.seconds.toFloat() / total * 360f
|
||||
arcPaint.color = if (s.color == -1) context.col(R.color.text_tertiary) else s.color
|
||||
canvas.drawArc(box, start + gapDeg / 2f, (sweep - gapDeg).coerceAtLeast(0.6f), false, arcPaint)
|
||||
start += sweep
|
||||
}
|
||||
}
|
||||
|
||||
val centerText = if (total <= 0) "0m" else Dates.shortDuration(total)
|
||||
canvas.drawText(centerText, cx, cy + context.dpf(2f), valuePaint)
|
||||
val cap = if (caption.isEmpty()) "总专注" else caption
|
||||
canvas.drawText(cap, cx, cy + context.dpf(18f), labelPaint)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ 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.percentText
|
||||
import com.focusbox.app.util.spf
|
||||
import kotlin.math.cos
|
||||
import kotlin.math.sin
|
||||
@@ -43,9 +44,28 @@ class LabelDonutView @JvmOverloads constructor(
|
||||
invalidate()
|
||||
}
|
||||
|
||||
/** 最多画几条引线标注,多出来的合并成「其他」,避免标注挤成一团 */
|
||||
/**
|
||||
* 环上最多给几条切片牵引线标注(取占比最高的若干条)。
|
||||
*
|
||||
* 超出部分**不再合并成「其他」**:环本身照旧把每一块都按真实占比画出来,
|
||||
* 只是没牵到线的切片记进 [unlabeled],由调用方在图表下方完整列出。
|
||||
* 6 条(每侧 3 条)在 222dp 高度里间距仍舒展,再往上夹逼会把相邻标注压到一起。
|
||||
*/
|
||||
var maxLabels: Int = 6
|
||||
|
||||
/** 扇区张角小于该值时不牵线:引线会叠在同一个点上,约 0.8% 以下的占比 */
|
||||
private val minLabelSweep = 3f
|
||||
|
||||
/**
|
||||
* 环上没能牵线的切片(占比排在 [maxLabels] 之外,或扇区太窄),按占比从高到低。
|
||||
* 调用方必须把它们全部列在图表下方,否则这些任务/项目在视觉上就"消失"了。
|
||||
*/
|
||||
var unlabeled: List<Slice> = emptyList()
|
||||
private set
|
||||
|
||||
/** 已经牵到线的切片,按同一套规则算出,供绘制使用 */
|
||||
private var labeled: List<Slice> = emptyList()
|
||||
|
||||
private val strokeW = context.dpf(28f)
|
||||
|
||||
private val arcPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
@@ -83,9 +103,44 @@ class LabelDonutView @JvmOverloads constructor(
|
||||
|
||||
fun setSlices(list: List<Slice>) {
|
||||
slices = list
|
||||
plan(list)
|
||||
// 纯 Canvas 自绘,读屏拿不到任何内容,这里补一句汇总描述
|
||||
contentDescription = a11yText(list)
|
||||
invalidate()
|
||||
}
|
||||
|
||||
/** 「共 N 项,占比最高的是 X(Y%)」:给无障碍服务的一句话概括 */
|
||||
private fun a11yText(list: List<Slice>): String {
|
||||
val total = list.sumOf { it.seconds }
|
||||
val top = list.maxByOrNull { it.seconds }
|
||||
if (total <= 0 || top == null) return context.getString(R.string.no_record)
|
||||
return context.getString(
|
||||
R.string.donut_a11y,
|
||||
list.size,
|
||||
top.name,
|
||||
percentText(top.seconds, total),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 标注计划:按占比排序,前 [maxLabels] 名里扇区够宽的才牵线,
|
||||
* 其余(含前 N 名但太窄的)全部落到 [unlabeled]。
|
||||
*/
|
||||
private fun plan(list: List<Slice>) {
|
||||
val total = list.sumOf { it.seconds }
|
||||
val sorted = list.sortedByDescending { it.seconds }
|
||||
val head = if (total <= 0) emptyList() else sorted.take(maxLabels).filter {
|
||||
it.seconds.toFloat() / total * 360f >= minLabelSweep
|
||||
}
|
||||
labeled = head
|
||||
// 用「逐个摘除」而不是 toSet 差集:同名同色同时长的两条切片也能各算一次
|
||||
val left = head.toMutableList()
|
||||
unlabeled = sorted.filter { s ->
|
||||
val i = left.indexOf(s)
|
||||
if (i >= 0) { left.removeAt(i); false } else true
|
||||
}
|
||||
}
|
||||
|
||||
private data class Tag(
|
||||
val slice: Slice,
|
||||
val midDeg: Float,
|
||||
@@ -110,21 +165,24 @@ class LabelDonutView @JvmOverloads constructor(
|
||||
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
|
||||
// 不再合并「其他」后切片可能有几十条,固定 2.2° 的缝隙累计起来会吃掉小半个环
|
||||
// (40 条就是 88°),因此按条数摊薄,总缝隙不超过约 14°
|
||||
val gapDeg = if (slices.size > 1) minOf(2.2f, 14f / slices.size) else 0f
|
||||
|
||||
// ---- 弧与百分比
|
||||
// ---- 弧与百分比:每一块都按真实占比画,绝不合并
|
||||
var start = -90f
|
||||
val tags = ArrayList<Tag>(shown.size)
|
||||
shown.forEach { s ->
|
||||
val tags = ArrayList<Tag>(labeled.size)
|
||||
val pending = labeled.toMutableList()
|
||||
slices.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)
|
||||
canvas.drawArc(box, start + gapDeg / 2f, (sweep - gapDeg).coerceAtLeast(0.2f), false, arcPaint)
|
||||
|
||||
val arcLen = sweep / 360f * (2 * Math.PI.toFloat() * r)
|
||||
val pct = "${(s.seconds * 100f / total).toInt().coerceAtLeast(1)}%"
|
||||
// 与下方明细共用 percentText:两处各写一套会把 0.6% 显示成 1% 和 <1% 两个数
|
||||
val pct = percentText(s.seconds, total)
|
||||
// 环加粗后百分比必须完整落在色带里:按实测字宽缩字号,两侧各留 5dp 边距
|
||||
var pctSize = 11f
|
||||
pctPaint.textSize = context.spf(pctSize)
|
||||
@@ -141,14 +199,16 @@ class LabelDonutView @JvmOverloads constructor(
|
||||
canvas.drawText(pct, px, py - (fm.ascent + fm.descent) / 2f, pctPaint)
|
||||
}
|
||||
|
||||
// 太薄的扇区不牵线,否则几条线会叠在同一个点上
|
||||
if (sweep >= 5f) {
|
||||
// 只有进了标注计划的切片才牵线;pending 逐个摘除,重复切片也各算一次
|
||||
if (sweep >= minLabelSweep && pending.remove(s)) {
|
||||
val cosA = cos(radians(midDeg))
|
||||
val sinA = sin(radians(midDeg))
|
||||
tags.add(
|
||||
Tag(
|
||||
slice = s,
|
||||
midDeg = midDeg,
|
||||
// 只看扇区中线在左半还是右半:标注就该贴在自己那块色旁边。
|
||||
// v3.14 试过强行左右均分,被分到对面的扇区引线必然横穿圆环,已撤回。
|
||||
side = if (cosA >= 0.0) 1 else -1,
|
||||
anchorY = cy + ((r + strokeW) * sinA).toFloat(),
|
||||
)
|
||||
@@ -164,17 +224,6 @@ class LabelDonutView @JvmOverloads constructor(
|
||||
|
||||
private fun radians(deg: Float): Double = Math.toRadians(deg.toDouble())
|
||||
|
||||
private fun collapse(list: List<Slice>): List<Slice> {
|
||||
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),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 环中心只画一行:累计时间(或空态提示)。
|
||||
* 之前按 cy + 2dp 硬偏移定位,字面重心偏下;改为按字体度量
|
||||
@@ -245,7 +294,8 @@ class LabelDonutView @JvmOverloads constructor(
|
||||
|
||||
linePaint.color = color
|
||||
linePaint.alpha = 200
|
||||
// 从环外缘斜出到折点,再水平指向外侧圆点
|
||||
// 标注永远在扇区自己那一侧,从环外缘斜出到折点,再水平指向外侧圆点,
|
||||
// 引线不会跨过圆环(v3.14 的三段式是为强制左右均分服务的,已随均分一起撤回)。
|
||||
canvas.drawLine(startX, startY, kneeX, tag.y, linePaint)
|
||||
canvas.drawLine(kneeX, tag.y, dotX, tag.y, linePaint)
|
||||
|
||||
|
||||
11
src/main/res/drawable/bg_filter_header.xml
Normal file
11
src/main/res/drawable/bg_filter_header.xml
Normal file
@@ -0,0 +1,11 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- 筛选卡片头部的按压态:圆角与 bg_card(18dp)一致,
|
||||
否则点击摘要行时水波纹是直角,会盖出卡片圆角以外的区域 -->
|
||||
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:color="?attr/colorControlHighlight">
|
||||
<item>
|
||||
<shape android:shape="rectangle">
|
||||
<corners android:radius="18dp" />
|
||||
</shape>
|
||||
</item>
|
||||
</ripple>
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user