diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..504f508 --- /dev/null +++ b/.gitignore @@ -0,0 +1,34 @@ +# Dependencies and build output +node_modules/ +vendor/ +dist/ +build/ +out/ +main.js +*.apk +*.idsig + +# Build tools and IDE +.gradle/ +.idea/ +*.iml +gradle/ +gradlew +gradlew.bat + +# Environment and secrets +.env +.env.* +keystore.properties +*.jks +*.keystore +credentials*.json + +# Runtime data and backups +data/ +备份/ +*.log +*.bak +*.tmp +.DS_Store +Thumbs.db diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..83afedc --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,50 @@ +# 变更记录 + +## 2026-11-27 · v0.2.0(versionCode 2):交互重构、重复任务、任务分布 + +首版反馈的集中修订。数据库 v1 → v2 自动迁移,旧数据保留。 + +### 首页(原「专注」) + +- 圆环区支持左右滑动切换两种模式:第 1 页倒计时(默认 25 分钟),第 2 页正计时(从 `00:00` 起)。 +- 圆环支持上下滑动调整本轮时长,范围 5–180 分钟,中心数字实时跟随;拖动过程不落盘,抬手才写入。 +- 选中任务后圆环自动切换为该任务设定的专注时长,之后仍可滑动增减。 +- 手势在同一容器内统一裁决:先判主方向,纵向调时长(约 9dp ≈ 1 分钟),横向翻页,避免两种手势互相抢事件。 + +### 任务 + +- 新增「专注时长(分钟)」与「重复」设置:按每 N 天 / 每 N 周 / 每 N 月重复。 +- 重复任务勾选完成后自动生成下一周期,截止日顺延(月末按 `Calendar` 收敛,不溢出到次月)。 +- 列表改为显示专注分钟数,不再显示番茄数;有备注的任务在「项目 · 日期」下一行单独显示备注。 +- 已完成任务显示真实专注时段:`11月27日 周五 09:12:03-09:37:03`,取自该任务最近一条会话记录。 +- 筛选胶囊顺序调整为「全部 / 今日 / 已完成」+ 各项目;今日口径为截止日落在今天的待办。 +- 底部折叠文案改为「显示已完成 / 隐藏已完成」,居中且去掉右侧箭头图标。 + +### 项目 + +- 卡片去掉番茄数,右侧增加「⋯」入口(编辑 / 归档 / 删除),原长按菜单保留。 +- 删除项目时任务回收至「收件箱」,历史专注记录保留归属,统计不出现断档。 + +### 统计 + +- 新增「任务分布」环形图,与「项目分布」共用同一绘制控件,按所选区间统计。 + +### 通知与锁屏 + +- 锁屏 / 息屏下通知时间静止的问题修复:常驻通知改用系统 `Chronometer`(`setUsesChronometer` + `setWhen` + `setChronometerCountDown`),不再依赖每秒 `notify()`——第三方高频刷新在息屏会被系统限流。 +- 通知去掉「专注中 / 休息中」文案,只保留时间;暂停、结束改为纯图标操作;小图标替换为透明图标,左侧不再出现应用图标。 +- 正计时不再持有 `WakeLock`、不再轮询,改为按 `startedAt + accumMs` 现算,长时正计时不额外耗电。 + +### 导航与主题 + +- 底部导航「专注」改为「首页」。 +- 修复切换深浅色后首页与设置页内容重叠:根因是 `recreate()` 后 FragmentManager 恢复出全部片段,而记录当前页的变量被重置为 `-1`,仅隐藏「上一页」等于未隐藏。改为 `onSaveInstanceState` 保存当前页 + `showTab(index, force = true)` 显式隐藏其余片段。 + +## 2026-11-27 · v0.1.0(versionCode 1):首个可用版本 + +- 五个模块:首页计时、任务、项目、统计、设置。 +- 计时内核只保存结束时间戳,剩余时间现算;进程被杀后若该轮已跑满九成按完成补记,否则不补,避免虚增统计。 +- `TimerService` 以前台服务承载计时,息屏、锁屏、切后台继续走时;结束响铃、振动并发送通知。 +- 单文件 SQLite 三表(`projects` / `tasks` / `sessions`),不引入 Room,规避注解处理编译链。 +- 图表全部 Canvas 自绘:圆环、柱状图、热力图、环形图。 +- 使用工程固定签名密钥,保证跨机器构建可覆盖升级、数据不丢。 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..1b730f4 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,20 @@ +# 贡献指南 + +欢迎对本应用提出改进建议或提交代码。 + +## 提交前检查 + +- 仅提交应用实现代码、资源与必要文档,不提交依赖目录、编译产物(`build/`、`dist/`、`*.apk`)、运行时数据或备份文件。 +- 不提交签名材料与构建配置(`*.jks`、`keystore.properties`、`local.properties`)。 +- 保持现有目录结构:源码位于 `src/main/`。 + +## 提交流程 + +1. Fork 仓库并创建功能分支。 +2. 完成修改后提交 Pull Request,说明改动目的与影响范围。 +3. 面向用户的变更请同步更新 `CHANGELOG.md`。 +4. 涉及数据库结构的改动需提供升级迁移,保证旧版本数据可继续使用。 + +## 问题反馈 + +请通过仓库 Issue 反馈问题,并尽可能提供机型、系统版本、应用版本与复现步骤。 diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..68e8c20 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 石头厝 / XIGE + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index fb0b1e8..8423603 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,39 @@ -# FocusBox +# FocusBox(专注盒子) +> 仓库:`FocusBox` · 类型:Android 应用 · 版本:`0.2.0` · 作者:石头厝 / XIGE + +自用安卓番茄钟与任务清单:专注计时(倒计时 / 正计时)、任务与重复计划、项目核算、统计图表。 + +本仓库同步自本地应用源码,**仅包含应用实现代码与必要资源**;不包含依赖、构建工具、编译产物、签名材料、环境配置或备份数据。 + +## 目录结构 + +- `src/main/` — Android 源码(`java/` 与 `res/`) + +## 特性概览 + +- **首页**:圆环左右滑动切换倒计时与正计时;圆环上下滑动调整本轮时长(5–180 分钟);选中任务后自动套用该任务的专注时长。 +- **任务**:标题、备注、项目、优先级、专注时长、截止日期、按天/周/月重复;筛选「全部 / 今日 / 已完成」;已完成显示日期、星期与起止时刻。 +- **项目**:八色标记,卡片显示待办数、完成数、累计时长、完成率;支持编辑、归档、删除,删除时任务回收至收件箱。 +- **统计**:今日目标环、周/月/全部趋势、12 周打卡热力图、项目分布与任务分布环形图、累计四项。 +- **计时可靠性**:只保存结束时间戳,剩余时间现算;前台服务 + 系统 Chronometer 通知,息屏、锁屏、切后台均继续走时。 + +目标机型:华为 P30 / HarmonyOS 4.0(Android 12 / API 31),minSdk 24、targetSdk 34,无 Google 服务依赖。 + +## 构建说明 + +1. 按 Android 项目结构将 `src/main/` 放回 `app/src/main/`,自行补齐 `build.gradle.kts`、`settings.gradle.kts` 与 Gradle Wrapper。 +2. 依赖为纯 AndroidX(appcompat / activity-ktx / lifecycle-runtime-ktx / recyclerview / coroutines),界面全部自绘,不使用 Material 与 Room。 +3. 构建配置、签名密钥与 `keystore.properties` 不在本仓库内,请使用自有签名后构建安装;换签名将导致无法覆盖升级。 + +## 开发与贡献 + +详见 [CONTRIBUTING.md](CONTRIBUTING.md)。 + +## 授权 + +授权条款见 [LICENSE](LICENSE)(MIT License)。 + +## 变更记录 + +详见 [CHANGELOG.md](CHANGELOG.md)。 diff --git a/src/main/AndroidManifest.xml b/src/main/AndroidManifest.xml new file mode 100644 index 0000000..58377f7 --- /dev/null +++ b/src/main/AndroidManifest.xml @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/java/com/focusbox/app/App.kt b/src/main/java/com/focusbox/app/App.kt new file mode 100644 index 0000000..4c616b0 --- /dev/null +++ b/src/main/java/com/focusbox/app/App.kt @@ -0,0 +1,31 @@ +package com.focusbox.app + +import android.app.Application +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.Prefs + +class App : Application() { + + override fun onCreate() { + super.onCreate() + Prefs.init(this) + Store.init(this) + Notif.createChannels(this) + applyTheme() + TimerCore.init(this) + } + + /** 深色模式在 Activity 创建前定好,避免首帧闪一下浅色再跳深色 */ + fun applyTheme() { + AppCompatDelegate.setDefaultNightMode( + when (Prefs.themeMode) { + 1 -> AppCompatDelegate.MODE_NIGHT_NO + 2 -> AppCompatDelegate.MODE_NIGHT_YES + else -> AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM + } + ) + } +} diff --git a/src/main/java/com/focusbox/app/model/Models.kt b/src/main/java/com/focusbox/app/model/Models.kt new file mode 100644 index 0000000..dc02755 --- /dev/null +++ b/src/main/java/com/focusbox/app/model/Models.kt @@ -0,0 +1,81 @@ +package com.focusbox.app.model + +/** 项目(清单)。收件箱固定 id=1,不可删除。 */ +data class Project( + val id: Long, + val name: String, + val color: Int, + val archived: Boolean, + val sort: Int, + val openTasks: Int, + val doneTasks: Int, + val focusSeconds: Int, + val pomodoros: Int, +) { + val totalTasks: Int get() = openTasks + doneTasks + val progress: Float get() = if (totalTasks == 0) 0f else doneTasks.toFloat() / totalTasks +} + +/** 重复规则。间隔数量存在 Task.repeatEvery 里,这里只定义单位。 */ +object Repeat { + const val NONE = 0 + const val DAY = 1 + const val WEEK = 2 + const val MONTH = 3 +} + +data class Task( + val id: Long, + val title: String, + val note: String, + val projectId: Long, + val priority: Int, // 0 低 / 1 中 / 2 高 + val focusMinutes: Int, // 单轮专注时长,选中任务后圆环直接用这个值 + val donePomodoros: Int, + val due: Long, // 0 表示不设 + val done: Boolean, + val doneAt: Long, + val createdAt: Long, + val sort: Int, + val repeatType: Int, // Repeat.NONE / DAY / WEEK / MONTH + val repeatEvery: Int, // 每 N 天 / 周 / 月 +) { + val repeating: Boolean get() = repeatType != Repeat.NONE && repeatEvery > 0 +} + +/** 一条专注记录的起止时刻,用于在已完成任务上显示实际工作时段。 */ +data class SessionSpan(val startAt: Long, val endAt: Long) + +data class DayPoint( + val key: String, // yyyy-MM-dd + val label: String, // 坐标轴短标签 + val minutes: Int, + val pomodoros: Int, +) + +/** 占比环的一片:项目分布与任务分布共用同一结构,避免两套绘制代码。 */ +data class ProjectSlice( + val projectId: Long, + val name: String, + val color: Int, + val seconds: Int, + val pomodoros: Int, +) + +data class Totals( + val seconds: Int = 0, + val pomodoros: Int = 0, + val doneTasks: Int = 0, + val streak: Int = 0, +) + +/** 统计页顶部"今日"卡片的一次性数据 */ +data class TodayStat( + val minutes: Int = 0, + val pomodoros: Int = 0, + val doneTasks: Int = 0, + val goalMinutes: Int = 120, +) { + val goalProgress: Float + get() = if (goalMinutes <= 0) 0f else (minutes.toFloat() / goalMinutes).coerceIn(0f, 1f) +} diff --git a/src/main/java/com/focusbox/app/service/Notif.kt b/src/main/java/com/focusbox/app/service/Notif.kt new file mode 100644 index 0000000..ac3bfde --- /dev/null +++ b/src/main/java/com/focusbox/app/service/Notif.kt @@ -0,0 +1,167 @@ +package com.focusbox.app.service + +import android.app.Notification +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.PendingIntent +import android.content.Context +import android.content.Intent +import android.os.Build +import androidx.core.app.NotificationCompat +import androidx.core.app.NotificationManagerCompat +import com.focusbox.app.R +import com.focusbox.app.ui.MainActivity +import com.focusbox.app.util.Dates + +/** + * 通知构建集中在这里:常驻计时通知 + 结束提醒,两条通道用途不同。 + * + * 常驻通知的时间交给系统 Chronometer 渲染,而不是每秒重发一条通知: + * 锁屏与息屏时第三方进程常被限流,自己刷新文本会"冻住", + * 系统级计时器的走时不受这个限制。 + */ +object Notif { + + const val CHANNEL_TIMER = "timer_ongoing" + const val CHANNEL_ALERT = "timer_alert" + + const val ID_ONGOING = 1001 + private const val ID_ALERT = 1002 + + fun createChannels(context: Context) { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return + val nm = context.getSystemService(NotificationManager::class.java) ?: return + + val ongoing = NotificationChannel( + CHANNEL_TIMER, + context.getString(R.string.notif_channel), + NotificationManager.IMPORTANCE_LOW, + ).apply { + description = context.getString(R.string.notif_channel_desc) + setShowBadge(false) + enableVibration(false) + setSound(null, null) + } + nm.createNotificationChannel(ongoing) + + // 提醒通道交给我们自己播放声音与振动,这里保持静默,避免"响两遍"。 + val alert = NotificationChannel( + CHANNEL_ALERT, + "计时结束提醒", + NotificationManager.IMPORTANCE_HIGH, + ).apply { + enableVibration(false) + setSound(null, null) + setShowBadge(true) + } + nm.createNotificationChannel(alert) + } + + private fun contentIntent(context: Context): PendingIntent { + val i = Intent(context, MainActivity::class.java).apply { + flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP + putExtra(MainActivity.EXTRA_TAB, MainActivity.TAB_FOCUS) + } + return PendingIntent.getActivity( + context, 0, i, + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, + ) + } + + private fun serviceAction(context: Context, action: String, requestCode: Int): PendingIntent { + val i = Intent(context, TimerService::class.java).setAction(action) + return PendingIntent.getService( + context, requestCode, i, + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, + ) + } + + fun buildOngoing(context: Context): Notification { + val running = TimerCore.running + val countUp = TimerCore.countUp + val taskName = if (TimerCore.taskId > 0) { + com.focusbox.app.data.Store.task(TimerCore.taskId)?.title + } else null + + val b = NotificationCompat.Builder(context, CHANNEL_TIMER) + // 透明小图标:状态栏与通知左侧不再出现应用图标 + .setSmallIcon(R.drawable.ic_notif_blank) + .setContentIntent(contentIntent(context)) + .setOngoing(true) + .setOnlyAlertOnce(true) + .setPriority(NotificationCompat.PRIORITY_LOW) + .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) + .setSilent(true) + + if (running) { + b.setUsesChronometer(true) + if (countUp) { + // 正计时:系统计时器从"已用时"往前推起点,界面上就是一直往上走 + b.setWhen(System.currentTimeMillis() - TimerCore.displayNow()) + b.setChronometerCountDown(false) + } else { + // 倒计时:渲染到结束时刻,系统自己一秒一秒减 + b.setWhen(TimerCore.endAtMs()) + b.setChronometerCountDown(true) + } + // 不再出现"专注中/休息中"字样,标题只留任务名(无任务则空白) + b.setContentTitle(taskName ?: " ") + } else { + b.setShowWhen(false) + b.setContentTitle(Dates.clock(TimerCore.displayNow())) + b.setContentText(taskName ?: "") + } + + val toggleIcon = if (running) R.drawable.ic_pause else R.drawable.ic_play + b.addAction( + NotificationCompat.Action( + toggleIcon, "", + serviceAction( + context, + if (running) TimerService.ACTION_PAUSE else TimerService.ACTION_RESUME, + 11, + ), + ) + ) + b.addAction( + NotificationCompat.Action( + R.drawable.ic_stop, "", + serviceAction(context, TimerService.ACTION_STOP, 13), + ) + ) + return b.build() + } + + fun updateOngoing(context: Context) { + if (!NotificationManagerCompat.from(context).areNotificationsEnabled()) return + runCatching { + NotificationManagerCompat.from(context).notify(ID_ONGOING, buildOngoing(context)) + } + } + + fun showCompletion(context: Context, finishedMode: Int, breakMinutes: Int) { + if (!NotificationManagerCompat.from(context).areNotificationsEnabled()) return + val focusDone = finishedMode == TimerCore.MODE_FOCUS + val title = context.getString( + if (focusDone) R.string.notif_focus_done else R.string.notif_break_done + ) + val text = if (focusDone) { + context.getString(R.string.notif_focus_done_text, breakMinutes) + } else { + context.getString(R.string.notif_break_done_text) + } + val n = NotificationCompat.Builder(context, CHANNEL_ALERT) + .setSmallIcon(R.drawable.ic_check) + .setContentTitle(title) + .setContentText(text) + .setContentIntent(contentIntent(context)) + .setAutoCancel(true) + .setPriority(NotificationCompat.PRIORITY_HIGH) + .build() + runCatching { NotificationManagerCompat.from(context).notify(ID_ALERT, n) } + } + + fun cancelOngoing(context: Context) { + runCatching { NotificationManagerCompat.from(context).cancel(ID_ONGOING) } + } +} diff --git a/src/main/java/com/focusbox/app/service/TimerCore.kt b/src/main/java/com/focusbox/app/service/TimerCore.kt new file mode 100644 index 0000000..d96b3bb --- /dev/null +++ b/src/main/java/com/focusbox/app/service/TimerCore.kt @@ -0,0 +1,449 @@ +package com.focusbox.app.service + +import android.content.Context +import android.media.RingtoneManager +import android.os.Build +import android.os.VibrationEffect +import android.os.Vibrator +import com.focusbox.app.data.Store +import com.focusbox.app.util.Prefs +import java.util.concurrent.CopyOnWriteArrayList + +/** + * 计时的唯一状态源。 + * + * 设计要点: + * 1. 倒计时只存"结束时间点 endAt",剩余时间每次现算;息屏、掉帧、进程被挂起都不累积误差。 + * 2. 正计时只存"开始时间点 startedAt + 已累计 accumMs",暂停时把差值折进累计值。 + * 3. 所有状态变更立刻落盘,进程被杀后重新打开能接着走同一轮。 + * 4. UI 只读不写;按钮调用这里的函数,由这里通知监听者刷新。 + */ +object TimerCore { + + const val MODE_FOCUS = 0 + const val MODE_SHORT = 1 + const val MODE_LONG = 2 + + /** 圆环可拖动的时长范围 */ + const val MIN_MINUTES = 5 + const val MAX_MINUTES = 180 + + private lateinit var ctx: Context + + var mode = MODE_FOCUS + private set + + var running = false + private set + + /** 正计时(秒表):与番茄倒计时互斥,从 00:00 往上走 */ + var countUp = false + private set + + /** 倒计时总时长;正计时时无意义 */ + var totalMs = 25 * 60_000L + private set + + /** 倒计时:剩余毫秒 */ + var remainingMs = totalMs + private set + + /** 正计时:已累计毫秒(暂停时的快照) */ + var accumMs = 0L + private set + + var taskId = 0L + private set + var projectId = 0L + private set + + /** 当前循环内已完成的专注轮数 */ + var round = 0 + private set + + private var endAt = 0L + private var startedAt = 0L + + private val listeners = CopyOnWriteArrayList<() -> Unit>() + + fun addListener(l: () -> Unit) { + if (!listeners.contains(l)) listeners.add(l) + } + + fun removeListener(l: () -> Unit) { + listeners.remove(l) + } + + private fun notifyChanged() { + listeners.forEach { runCatching { it() } } + } + + fun init(context: Context) { + ctx = context.applicationContext + mode = Prefs.timerMode + round = Prefs.timerRound + taskId = Prefs.timerTaskId + projectId = Prefs.timerProjectId + countUp = Prefs.timerCountUp + totalMs = Prefs.timerTotalMs.takeIf { it > 0 } ?: durationFor(mode) + remainingMs = Prefs.timerRemainingMs + accumMs = Prefs.timerAccumMs + running = Prefs.timerRunning + endAt = Prefs.timerEndAt + startedAt = Prefs.timerStartedAt + + if (running) { + if (countUp) { + // 正计时没有终点,只要开始点还在就接着累计 + if (startedAt <= 0L) running = false + } else { + val left = endAt - System.currentTimeMillis() + if (left <= 0) { + // 进程在计时期间被杀,回来时这轮已经超时: + // 时间够长就按完成补记,不够就当没发生过,绝不虚增统计。 + val elapsed = System.currentTimeMillis() - startedAt + running = false + if (mode == MODE_FOCUS && startedAt > 0 && elapsed >= totalMs * 9 / 10) { + record((totalMs / 1000).toInt(), completed = true) + round += 1 + } + remainingMs = durationFor(mode) + startedAt = 0 + endAt = 0 + accReset() + save() + } else { + remainingMs = left + } + } + } + if (!countUp && (remainingMs <= 0 || remainingMs > totalMs)) remainingMs = totalMs + if (countUp && accumMs < 0) accumMs = 0 + } + + fun durationFor(m: Int): Long = when (m) { + MODE_SHORT -> Prefs.shortBreakMinutes + MODE_LONG -> Prefs.longBreakMinutes + else -> Prefs.focusMinutes + } * 60_000L + + // ------------------------------------------------------------------ 读数 + + /** 界面与通知显示的数字:倒计时是剩余,正计时是已用时 */ + fun displayNow(): Long = if (countUp) { + if (running) (accumMs + (System.currentTimeMillis() - startedAt)).coerceAtLeast(0) else accumMs + } else { + remainingNow() + } + + fun remainingNow(): Long = + if (running && !countUp) (endAt - System.currentTimeMillis()).coerceAtLeast(0) else remainingMs + + /** 本轮已专注时长,用于写记录 */ + fun elapsedNow(): Long = + if (countUp) displayNow() else (totalMs - remainingNow()).coerceAtLeast(0) + + fun progress(): Float = if (countUp) { + // 正计时没有"总量",用一小时的活环表达节奏:每满 60 分钟走完一圈 + val cycle = 60 * 60_000L + (displayNow() % cycle).toFloat() / cycle + } else if (totalMs <= 0) { + 0f + } else { + (1f - remainingNow().toFloat() / totalMs).coerceIn(0f, 1f) + } + + fun durationMinutes(): Int = (totalMs / 60_000L).toInt() + + fun endAtMs(): Long = endAt + + fun startedAtMs(): Long = startedAt + + // ------------------------------------------------------------------ 操作 + + /** 切换倒计时/正计时。只在未开始时允许,避免中途改变计时语义。 */ + fun setCountUp(on: Boolean) { + if (running || countUp == on) return + countUp = on + if (on) { + mode = MODE_FOCUS + accReset() + } else { + totalMs = durationFor(mode) + remainingMs = totalMs + } + startedAt = 0 + endAt = 0 + save() + notifyChanged() + } + + /** 圆环拖动。拖动过程中 persist=false,抬手时才落盘,避免每帧写一次 SharedPreferences。 */ + fun setDurationMinutes(minutes: Int, persist: Boolean = true) { + if (running || countUp) return + val m = minutes.coerceIn(MIN_MINUTES, MAX_MINUTES) + if (m * 60_000L == totalMs && remainingMs == totalMs) return + totalMs = m * 60_000L + remainingMs = totalMs + startedAt = 0 + endAt = 0 + if (persist) save() + notifyChanged() + } + + /** 设置里改了默认时长:空闲时立刻套用,不打断正在进行的计时 */ + fun applyDefaultDuration() { + if (running || countUp) return + totalMs = durationFor(mode) + remainingMs = totalMs + save() + notifyChanged() + } + + /** 切换模式时保留已选任务;专注/休息时长按各自设置重新取 */ + fun setMode(m: Int, keepRemaining: Boolean = false) { + if (running) return + countUp = false + mode = m + totalMs = durationFor(m) + remainingMs = if (keepRemaining) remainingMs.coerceAtMost(totalMs) else totalMs + startedAt = 0 + endAt = 0 + accReset() + save() + notifyChanged() + } + + /** + * 选中任务。任务自带专注时长时,圆环直接切过去; + * 传 0 表示取消选择,不动当前时长。 + */ + fun setTask(id: Long, pid: Long, focusMinutes: Int = 0) { + taskId = id + projectId = pid + if (id > 0 && focusMinutes in MIN_MINUTES..MAX_MINUTES && !running && !countUp) { + mode = MODE_FOCUS + totalMs = focusMinutes * 60_000L + remainingMs = totalMs + startedAt = 0 + endAt = 0 + } + save() + notifyChanged() + } + + fun start() { + if (running) return + if (countUp) { + if (startedAt == 0L) startedAt = System.currentTimeMillis() + } else { + if (remainingMs <= 0) remainingMs = totalMs + if (startedAt == 0L) startedAt = System.currentTimeMillis() + endAt = System.currentTimeMillis() + remainingMs + } + running = true + save() + TimerService.ensureRunning(ctx) + notifyChanged() + } + + fun pause() { + if (!running) return + if (countUp) { + accumMs += (System.currentTimeMillis() - startedAt).coerceAtLeast(0) + startedAt = 0 + } else { + remainingMs = (endAt - System.currentTimeMillis()).coerceAtLeast(0) + } + running = false + endAt = 0 + save() + TimerService.refresh(ctx) + notifyChanged() + } + + fun resume() = start() + + /** 回到本轮起点,不记记录。倒计时保留当前设定的时长,正计时归零。 */ + fun reset() { + running = false + endAt = 0 + startedAt = 0 + if (countUp) { + accReset() + } else { + remainingMs = totalMs + } + save() + // 先让监听者把界面/通知刷成新状态,再停服务; + // 反过来的话服务销毁后不会再有人撤掉刚被重新贴上的常驻通知。 + notifyChanged() + TimerService.stop(ctx) + } + + /** 结束本轮:专注时长够 1 分钟才记一条(completed=false),避免留下碎片记录 */ + fun stopEarly() { + if (countUp) { + val elapsed = (displayNow() / 1000).toInt() + if (elapsed >= 60) record(elapsed, completed = false) + running = false + endAt = 0 + startedAt = 0 + accReset() + } else { + if (mode == MODE_FOCUS) { + val elapsed = elapsedSec() + if (elapsed >= 60 && startedAt > 0) record(elapsed, completed = false) + } + running = false + endAt = 0 + startedAt = 0 + totalMs = if (totalMs > 0) totalMs else durationFor(mode) + remainingMs = totalMs + } + save() + notifyChanged() + 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(countRound = false) + } else { + running = false + endAt = 0 + startedAt = 0 + mode = MODE_FOCUS + totalMs = durationFor(MODE_FOCUS) + remainingMs = totalMs + } + save() + notifyChanged() + TimerService.stop(ctx) + } + + /** 由前台服务每秒调用 */ + fun tick() { + if (!running || countUp) return + val left = endAt - System.currentTimeMillis() + if (left <= 0) { + remainingMs = 0 + complete() + } else { + remainingMs = left + } + } + + private fun elapsedSec(): Int { + val elapsedMs = if (running) totalMs - remainingNow() else totalMs - remainingMs + return (elapsedMs / 1000).toInt().coerceIn(0, (totalMs / 1000).toInt()) + } + + private fun complete() { + if (countUp) return + val wasFocus = mode == MODE_FOCUS + val elapsed = if (wasFocus) (totalMs / 1000).toInt() else elapsedSec() + running = false + endAt = 0 + + if (wasFocus) { + if (elapsed >= 60) record(elapsed, completed = true) + round += 1 + } + + alert() + val finishedMode = mode + if (wasFocus) { + advanceFromFocus(countRound = true) + } else { + mode = MODE_FOCUS + totalMs = durationFor(MODE_FOCUS) + remainingMs = totalMs + } + startedAt = 0 + save() + Notif.showCompletion(ctx, finishedMode, Prefs.shortBreakMinutes) + notifyChanged() + + // 自动衔接时不要先停服务再重启:Android 12 起后台启动前台服务会被系统拒绝, + // 服务连续存活才不会走进那个限制。 + val autoNext = if (wasFocus) Prefs.autoStartBreak else Prefs.autoStartFocus + if (autoNext) start() else TimerService.stop(ctx) + } + + private fun advanceFromFocus(countRound: Boolean) { + val every = Prefs.longBreakEvery.coerceAtLeast(2) + mode = if (round > 0 && round % every == 0) MODE_LONG else MODE_SHORT + totalMs = durationFor(mode) + remainingMs = totalMs + startedAt = 0 + endAt = 0 + } + + private fun record(elapsedSec: Int, completed: Boolean) { + val end = System.currentTimeMillis() + val start = if (startedAt > 0) startedAt else end - elapsedSec * 1000L + Store.addSession(taskId, projectId, start, end, elapsedSec, completed) + } + + private fun accReset() { + accumMs = 0 + Prefs.timerAccumMs = 0 + } + + private fun save() { + Prefs.timerMode = mode + Prefs.timerRunning = running + Prefs.timerCountUp = countUp + Prefs.timerTotalMs = totalMs + Prefs.timerRemainingMs = remainingMs + Prefs.timerEndAt = endAt + Prefs.timerStartedAt = startedAt + Prefs.timerTaskId = taskId + Prefs.timerProjectId = projectId + Prefs.timerRound = round + Prefs.timerAccumMs = accumMs + } + + fun resetRound() { + round = 0 + save() + notifyChanged() + } + + private fun alert() { + if (Prefs.soundOn) { + runCatching { + val uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION) + RingtoneManager.getRingtone(ctx, uri)?.play() + } + } + if (Prefs.vibrateOn) { + runCatching { + val v = ctx.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + v.vibrate(VibrationEffect.createWaveform(longArrayOf(0, 130, 90, 130), -1)) + } else { + @Suppress("DEPRECATION") + v.vibrate(320) + } + } + } + } + + fun modeLabelRes(): Int = when (mode) { + MODE_SHORT -> com.focusbox.app.R.string.mode_break + MODE_LONG -> com.focusbox.app.R.string.mode_long_break + else -> com.focusbox.app.R.string.mode_focus + } +} diff --git a/src/main/java/com/focusbox/app/service/TimerService.kt b/src/main/java/com/focusbox/app/service/TimerService.kt new file mode 100644 index 0000000..e49200b --- /dev/null +++ b/src/main/java/com/focusbox/app/service/TimerService.kt @@ -0,0 +1,152 @@ +package com.focusbox.app.service + +import android.app.Service +import android.content.Context +import android.content.Intent +import android.os.Handler +import android.os.IBinder +import android.os.Looper +import android.os.PowerManager +import androidx.core.content.ContextCompat + +/** + * 计时前台服务。 + * + * 之所以必须用前台服务而不是页面里的 Handler:息屏后 Activity 会被暂停、 + * 进程随时可能被回收,只有带常驻通知的前台服务能稳定维持计时与到时提醒。 + * + * 真正的计时逻辑在 [TimerCore],这里只做三件事:撑住进程、每秒推进、刷新通知。 + */ +class TimerService : Service() { + + companion object { + const val ACTION_SYNC = "com.focusbox.app.SYNC" + const val ACTION_PAUSE = "com.focusbox.app.PAUSE" + const val ACTION_RESUME = "com.focusbox.app.RESUME" + const val ACTION_STOP = "com.focusbox.app.STOP" + + fun ensureRunning(context: Context) { + val intent = Intent(context, TimerService::class.java).setAction(ACTION_SYNC) + runCatching { ContextCompat.startForegroundService(context, intent) } + } + + fun refresh(context: Context) { + Notif.updateOngoing(context) + } + + fun stop(context: Context) { + runCatching { context.stopService(Intent(context, TimerService::class.java)) } + Notif.cancelOngoing(context) + } + } + + private val handler = Handler(Looper.getMainLooper()) + private var wakeLock: PowerManager.WakeLock? = null + + private val ticker = object : Runnable { + override fun run() { + // 只推进状态,不再每秒重发通知:通知里的时间是系统的 Chronometer 在走, + // 每秒 notify 反而会让锁屏上的计时被系统限流后"冻住"。 + TimerCore.tick() + handler.postDelayed(this, 1000L) + } + } + + override fun onCreate() { + super.onCreate() + TimerCore.addListener(onStateChanged) + } + + private val onStateChanged: () -> Unit = { + Notif.updateOngoing(this) + syncWakeLock() + } + + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + when (intent?.action) { + ACTION_PAUSE -> { + TimerCore.pause() + stopTicker() + } + ACTION_RESUME -> { + TimerCore.resume() + syncTicker() + } + ACTION_STOP -> { + TimerCore.stopEarly() + stopTicker() + stopSelf() + return START_NOT_STICKY + } + else -> Unit + } + + // 必须在启动后立即进入前台,否则 5 秒内会被系统判定为 ANR 级违规 + startForegroundCompat() + syncTicker() + syncWakeLock() + Notif.updateOngoing(this) + return START_NOT_STICKY + } + + /** + * 只有倒计时需要每秒推进(判断是否到点)。 + * 正计时靠时间戳现算、通知靠系统 Chronometer 走时, + * 既不用轮询也不用占着 WakeLock,长时间正计时不会白耗电。 + */ + private fun syncTicker() { + if (TimerCore.running && !TimerCore.countUp) startTicker() else stopTicker() + } + + private fun startForegroundCompat() { + val notification = Notif.buildOngoing(this) + runCatching { + // 两参版本会读清单里声明的前台服务类型(dataSync)。 + // 不用三参 + SPECIAL_USE:该类型 Android 14 才引入, + // 在 P30 的 Android 12 上传进去会直接抛 IllegalArgumentException。 + startForeground(Notif.ID_ONGOING, notification) + }.onFailure { + // 前台服务被系统拒绝(省电策略/权限)时退化为普通服务, + // 计时本身仍在 TimerCore 里走,只是通知可能不显示。 + stopSelf() + } + } + + private fun startTicker() { + handler.removeCallbacks(ticker) + handler.postDelayed(ticker, 1000L) + } + + private fun stopTicker() { + handler.removeCallbacks(ticker) + } + + private fun syncWakeLock() { + if (TimerCore.running && !TimerCore.countUp) { + if (wakeLock?.isHeld != true) { + val pm = getSystemService(Context.POWER_SERVICE) as PowerManager + wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "FocusBox:timer").apply { + setReferenceCounted(false) + // 超时兜底:正常路径会主动释放,这里防止异常退出后一直亮着 CPU + acquire(4 * 60 * 60 * 1000L) + } + } + } else { + releaseWakeLock() + } + } + + private fun releaseWakeLock() { + runCatching { if (wakeLock?.isHeld == true) wakeLock?.release() } + wakeLock = null + } + + override fun onBind(intent: Intent?): IBinder? = null + + override fun onDestroy() { + stopTicker() + releaseWakeLock() + TimerCore.removeListener(onStateChanged) + super.onDestroy() + } +} diff --git a/src/main/java/com/focusbox/app/ui/MainActivity.kt b/src/main/java/com/focusbox/app/ui/MainActivity.kt new file mode 100644 index 0000000..0c3812e --- /dev/null +++ b/src/main/java/com/focusbox/app/ui/MainActivity.kt @@ -0,0 +1,218 @@ +package com.focusbox.app.ui + +import android.content.Intent +import android.graphics.Typeface +import android.os.Bundle +import android.view.Gravity +import android.widget.FrameLayout +import android.widget.ImageView +import android.widget.LinearLayout +import android.widget.TextView +import androidx.appcompat.app.AppCompatActivity +import androidx.fragment.app.Fragment +import com.focusbox.app.R +import com.focusbox.app.model.Task +import com.focusbox.app.service.TimerCore +import com.focusbox.app.ui.focus.FocusFragment +import com.focusbox.app.ui.projects.ProjectsFragment +import com.focusbox.app.ui.settings.SettingsFragment +import com.focusbox.app.ui.stats.StatsFragment +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 + +/** + * 单 Activity + 五个常驻 Fragment。 + * + * 用 show/hide 而不是 replace:切回"任务"时滚动位置与筛选状态都还在, + * 这对一个随手要记一笔的工具来说比省内存重要。 + * + * 注意:切换主题会把 Activity 重建,FragmentManager 会恢复出全部片段。 + * 因此这里必须把"当前页"存进 savedInstanceState,并在 [showTab] 里显式隐藏 + * 其余所有片段——只隐藏"上一次的 current"在重建后是 null,会造成两页重叠。 + */ +class MainActivity : AppCompatActivity() { + + companion object { + const val EXTRA_TAB = "extra_tab" + const val TAB_FOCUS = 0 + const val TAB_TASKS = 1 + const val TAB_PROJECTS = 2 + const val TAB_STATS = 3 + const val TAB_SETTINGS = 4 + private const val KEY_TAB = "current_tab" + private const val TAB_COUNT = 5 + } + + private lateinit var container: FrameLayout + private lateinit var navBar: LinearLayout + + private val fragments = arrayOfNulls(TAB_COUNT) + private val navIcons = ArrayList() + private val navLabels = ArrayList() + private var current = -1 + + private val tabLabels = intArrayOf( + R.string.nav_focus, R.string.nav_tasks, R.string.nav_projects, + R.string.nav_stats, R.string.nav_settings, + ) + private val tabIcons = intArrayOf( + R.drawable.ic_focus, R.drawable.ic_task, R.drawable.ic_project, + R.drawable.ic_stats, R.drawable.ic_settings, + ) + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_main) + container = findViewById(R.id.container) + navBar = findViewById(R.id.navBar) + + buildNav() + + val restored = savedInstanceState?.getInt(KEY_TAB, -1) ?: -1 + val fromIntent = intent?.getIntExtra(EXTRA_TAB, -1) ?: -1 + val start = when { + restored in 0 until TAB_COUNT -> restored + fromIntent in 0 until TAB_COUNT -> fromIntent + else -> TAB_FOCUS + } + showTab(start, force = true) + } + + override fun onSaveInstanceState(outState: Bundle) { + outState.putInt(KEY_TAB, current) + super.onSaveInstanceState(outState) + } + + override fun onNewIntent(intent: Intent?) { + super.onNewIntent(intent) + val tab = intent?.getIntExtra(EXTRA_TAB, -1) ?: -1 + if (tab in 0 until TAB_COUNT) showTab(tab, force = true) + } + + private fun buildNav() { + for (i in 0 until TAB_COUNT) { + val item = LinearLayout(this).apply { + orientation = LinearLayout.VERTICAL + gravity = Gravity.CENTER + layoutParams = LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1f) + } + val icon = ImageView(this).apply { + setImageResource(tabIcons[i]) + layoutParams = LinearLayout.LayoutParams(dpi(21f), dpi(21f)) + } + val label = TextView(this).apply { + text = getString(tabLabels[i]) + textSize = 10f + includeFontPadding = false + gravity = Gravity.CENTER + val lp = LinearLayout.LayoutParams( + LinearLayout.LayoutParams.WRAP_CONTENT, + LinearLayout.LayoutParams.WRAP_CONTENT, + ) + lp.topMargin = dpi(3f) + layoutParams = lp + } + item.addView(icon) + item.addView(label) + item.setOnClickListener { showTab(i) } + navBar.addView(item) + navIcons.add(icon) + navLabels.add(label) + } + } + + private fun createFragment(index: Int): Fragment = when (index) { + 0 -> FocusFragment() + 1 -> TasksFragment() + 2 -> ProjectsFragment() + 3 -> StatsFragment() + else -> SettingsFragment() + } + + fun showTab(index: Int) { + showTab(index, force = false) + } + + /** + * @param force 忽略"已在当前页"判断。重建、通知跳转时必须强制走一遍, + * 否则恢复出来的其他片段不会被隐藏。 + */ + private fun showTab(index: Int, force: Boolean) { + if (index !in 0 until TAB_COUNT) return + if (!force && index == current && fragments[index] != null) return + + val fm = supportFragmentManager + val tx = fm.beginTransaction() + for (i in 0 until TAB_COUNT) { + val tag = "tab$i" + var f = fragments[i] + if (f != null && f.isRemoving) f = null + if (f == null) f = fm.findFragmentByTag(tag) + if (i == index) { + if (f == null) { + f = createFragment(i) + tx.add(R.id.container, f, tag) + } else { + tx.show(f) + } + fragments[i] = f + } else if (f != null) { + fragments[i] = f + tx.hide(f) + } + } + tx.commitNowAllowingStateLoss() + current = index + updateNav() + } + + private fun updateNav() { + navIcons.forEachIndexed { i, icon -> + val selected = i == current + icon.tint(col(if (selected) R.color.brand else R.color.text_tertiary)) + navLabels[i].setTextColor(col(if (selected) R.color.brand else R.color.text_tertiary)) + navLabels[i].typeface = if (selected) Typeface.DEFAULT_BOLD else Typeface.DEFAULT + icon.alpha = if (selected) 1f else 0.85f + } + } + + /** 项目页点进去看任务:切到任务页并套用该项目的筛选 */ + fun openProjectTasks(projectId: Long) { + showTab(TAB_TASKS, force = true) + (fragments[TAB_TASKS] as? TasksFragment)?.applyProjectFilter(projectId) + } + + /** 任务行的播放键:把该任务设为当前任务并回到首页,圆环套用任务时长 */ + fun startFocusOn(task: Task) { + TimerCore.setCountUp(false) + TimerCore.setTask(task.id, task.projectId, task.focusMinutes) + if (!TimerCore.running && TimerCore.mode != TimerCore.MODE_FOCUS) { + TimerCore.setMode(TimerCore.MODE_FOCUS) + } + showTab(TAB_FOCUS) + } + + fun goFocus() = showTab(TAB_FOCUS) + + override fun onBackPressed() { + if (current != TAB_FOCUS) { + showTab(TAB_FOCUS) + } else { + @Suppress("DEPRECATION") + super.onBackPressed() + } + } + + /** 设置改动后(清空数据、改主题)统一刷新其余页面 */ + fun refreshAll() { + for (f in fragments) { + when (f) { + is TasksFragment -> f.reload() + is ProjectsFragment -> f.reload() + is StatsFragment -> f.reload() + } + } + } +} diff --git a/src/main/java/com/focusbox/app/ui/SheetDialog.kt b/src/main/java/com/focusbox/app/ui/SheetDialog.kt new file mode 100644 index 0000000..35e8871 --- /dev/null +++ b/src/main/java/com/focusbox/app/ui/SheetDialog.kt @@ -0,0 +1,42 @@ +package com.focusbox.app.ui + +import android.app.Dialog +import android.content.Context +import android.graphics.Color +import android.graphics.drawable.ColorDrawable +import android.view.Gravity +import android.view.View +import android.view.ViewGroup +import android.view.WindowManager +import com.focusbox.app.R + +/** + * 从底部升起的弹层。 + * + * 不用 Material 的 BottomSheetDialog:本工程刻意不引 Material 依赖(离线构建体积与 + * 主题冲突都省了),而这里只需要"贴底 + 圆角 + 键盘顶起"三件事,自己写反而可控。 + */ +open class SheetDialog(context: Context) : Dialog(context, R.style.SheetDialog) { + + init { + window?.apply { + setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT)) + setGravity(Gravity.BOTTOM) + setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE) + attributes = attributes.apply { + width = ViewGroup.LayoutParams.MATCH_PARENT + dimAmount = 0.45f + } + } + } + + override fun setContentView(view: View) { + super.setContentView(view) + (view.parent as? View)?.setBackgroundColor(Color.TRANSPARENT) + } + + override fun show() { + super.show() + window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) + } +} diff --git a/src/main/java/com/focusbox/app/ui/focus/FocusFragment.kt b/src/main/java/com/focusbox/app/ui/focus/FocusFragment.kt new file mode 100644 index 0000000..5a21f60 --- /dev/null +++ b/src/main/java/com/focusbox/app/ui/focus/FocusFragment.kt @@ -0,0 +1,456 @@ +package com.focusbox.app.ui.focus + +import android.Manifest +import android.content.pm.PackageManager +import android.os.Build +import android.os.Bundle +import android.os.Handler +import android.os.Looper +import android.view.MotionEvent +import android.view.View +import android.view.ViewConfiguration +import android.view.WindowManager +import android.widget.ImageView +import android.widget.LinearLayout +import android.widget.TextView +import android.widget.Toast +import androidx.appcompat.app.AlertDialog +import androidx.core.content.ContextCompat +import androidx.fragment.app.Fragment +import com.focusbox.app.R +import com.focusbox.app.data.Store +import com.focusbox.app.model.Project +import com.focusbox.app.model.Task +import com.focusbox.app.service.TimerCore +import com.focusbox.app.util.Dates +import com.focusbox.app.util.Prefs +import com.focusbox.app.util.circleBg +import com.focusbox.app.util.col +import com.focusbox.app.util.dpi +import com.focusbox.app.util.roundBg +import com.focusbox.app.util.tint +import com.focusbox.app.util.visible +import com.focusbox.app.widget.RingView +import kotlin.math.abs + +/** + * 首页。 + * + * 圆环有两种计时语义,靠左右滑动切换: + * 1. 倒计时(默认取设置里的专注时长,可用圆环上下拖动临时增减) + * 2. 正计时(从 00:00 往上走,用于不设目标的专注) + * + * 手势都在 [dialWrap] 上统一处理:先判断主方向,纵向调时长,横向切页。 + */ +class FocusFragment : Fragment(R.layout.fragment_focus) { + + private lateinit var ring: RingView + private lateinit var tvTime: TextView + private lateinit var tvModeLabel: TextView + private lateinit var tvDialHint: TextView + private lateinit var dots: LinearLayout + private lateinit var pageDots: LinearLayout + private lateinit var dialWrap: View + private lateinit var modeSwitch: View + private lateinit var btnMain: TextView + private lateinit var btnReset: ImageView + private lateinit var btnSkip: ImageView + private lateinit var tvTask: TextView + private lateinit var tvTaskMeta: TextView + private lateinit var tvTaskAction: TextView + private lateinit var taskDot: View + private lateinit var segFocus: TextView + private lateinit var segBreak: TextView + + private val handler = Handler(Looper.getMainLooper()) + private var keepScreen = false + + // 手势状态:0 未定 / 1 纵向调时长 / 2 横向翻页 / 3 忽略 + private var touchMode = 0 + private var downX = 0f + private var downY = 0f + private var dragStartMinutes = 25 + private var dragging = false + private var slop = 12 + + // 当前任务缓存:render() 每 250ms 跑一次,不能每次都查库 + private var cachedTaskId = Long.MIN_VALUE + private var cachedTask: Task? = null + private var cachedProject: Project? = null + + private val ticker = object : Runnable { + override fun run() { + // 兜底推进:万一前台服务被系统限流没起来,只要页面还在前台, + // 计时与到时结算仍然准确。 + if (TimerCore.running) TimerCore.tick() + render() + handler.postDelayed(this, 250L) + } + } + + private val onTimerChanged: () -> Unit = { if (isAdded && view != null) render() } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + ring = view.findViewById(R.id.ring) + tvTime = view.findViewById(R.id.tvTime) + tvModeLabel = view.findViewById(R.id.tvModeLabel) + tvDialHint = view.findViewById(R.id.tvDialHint) + dots = view.findViewById(R.id.dots) + pageDots = view.findViewById(R.id.pageDots) + dialWrap = view.findViewById(R.id.dialWrap) + modeSwitch = view.findViewById(R.id.modeSwitch) + btnMain = view.findViewById(R.id.btnMain) + btnReset = view.findViewById(R.id.btnReset) + btnSkip = view.findViewById(R.id.btnSkip) + tvTask = view.findViewById(R.id.tvTask) + tvTaskMeta = view.findViewById(R.id.tvTaskMeta) + tvTaskAction = view.findViewById(R.id.tvTaskAction) + taskDot = view.findViewById(R.id.taskDot) + segFocus = view.findViewById(R.id.segFocus) + segBreak = view.findViewById(R.id.segBreak) + + slop = ViewConfiguration.get(requireContext()).scaledTouchSlop + btnReset.tint(col(R.color.text_secondary)) + btnSkip.tint(col(R.color.text_secondary)) + + btnMain.setOnClickListener { + if (TimerCore.running) { + TimerCore.pause() + } else { + requestNotifPermissionIfNeeded() + TimerCore.start() + } + render() + } + btnReset.setOnClickListener { + TimerCore.reset() + render() + } + btnSkip.setOnClickListener { + TimerCore.skip() + render() + } + view.findViewById(R.id.taskCard).setOnClickListener { pickTask() } + segFocus.setOnClickListener { + if (!TimerCore.running) { + TimerCore.setMode(TimerCore.MODE_FOCUS) + render() + } + } + segBreak.setOnClickListener { + if (!TimerCore.running) { + val every = Prefs.longBreakEvery.coerceAtLeast(2) + val long = TimerCore.round > 0 && TimerCore.round % every == 0 + TimerCore.setMode(if (long) TimerCore.MODE_LONG else TimerCore.MODE_SHORT) + render() + } + } + + buildPageDots() + dialWrap.setOnTouchListener { _, ev -> handleDialTouch(ev) } + render() + } + + override fun onResume() { + super.onResume() + cachedTaskId = Long.MIN_VALUE // 任务可能被改名/改时长,回到页面强制重读 + TimerCore.addListener(onTimerChanged) + render() + handler.removeCallbacks(ticker) + // show/hide 模式下所有片段都处于 resumed,隐藏的页面不该继续跑 250ms 刷新 + if (!isHidden) handler.post(ticker) + } + + override fun onPause() { + super.onPause() + TimerCore.removeListener(onTimerChanged) + handler.removeCallbacks(ticker) + applyKeepScreen(false) + } + + override fun onHiddenChanged(hidden: Boolean) { + super.onHiddenChanged(hidden) + if (hidden) { + handler.removeCallbacks(ticker) + applyKeepScreen(false) + } else { + render() + handler.removeCallbacks(ticker) + handler.post(ticker) + } + } + + // ------------------------------------------------------------------ 绘制 + + private fun buildPageDots() { + pageDots.removeAllViews() + repeat(2) { + val v = View(requireContext()) + val lp = LinearLayout.LayoutParams(dpi(6f), dpi(6f)) + lp.marginStart = dpi(3f) + lp.marginEnd = dpi(3f) + v.layoutParams = lp + pageDots.addView(v) + } + } + + private fun render() { + if (view == null) return + val display = TimerCore.displayNow() + val focusMode = TimerCore.mode == TimerCore.MODE_FOCUS + val accent = col(if (focusMode) R.color.brand else R.color.rest) + + tvTime.text = Dates.clock(display) + ring.ringColor = accent + ring.trackColor = col(R.color.ring_track) + // 拖动时圆环按"选了多长"实时长出来,松手回到本轮进度 + ring.progress = if (dragging) { + (TimerCore.durationMinutes() / 60f).coerceIn(0f, 1f) + } else { + TimerCore.progress() + } + + tvModeLabel.text = when { + TimerCore.countUp -> getString(R.string.count_up) + TimerCore.mode == TimerCore.MODE_SHORT -> getString(R.string.mode_break) + TimerCore.mode == TimerCore.MODE_LONG -> getString(R.string.mode_long_break) + else -> getString(R.string.count_down) + } + + btnMain.text = when { + TimerCore.running -> getString(R.string.pause) + TimerCore.countUp -> if (display > 0) getString(R.string.resume) else getString(R.string.start_timing) + display < TimerCore.totalMs -> getString(R.string.resume) + focusMode -> getString(R.string.start) + else -> getString(R.string.start_break) + } + // 按钮底色随模式变,但每 250ms 新建一个 drawable 会造成无谓的 GC, + // 用 tag 记住当前颜色,只有真的变了才换。 + if (btnMain.tag != accent) { + btnMain.tag = accent + btnMain.background = requireContext().roundBg(accent, 100f) + } + + modeSwitch.visible(!TimerCore.countUp) + applySegments(focusMode) + renderPageDots() + renderDots(accent) + renderTask() + renderHint() + applyKeepScreen(TimerCore.running && Prefs.keepScreenOn) + } + + private fun renderHint() { + val text = when { + TimerCore.running -> "" + TimerCore.countUp -> getString(R.string.dial_hint_count_up) + // 休息时长属于设置项,不引导用户在休息环上拖动 + TimerCore.mode == TimerCore.MODE_FOCUS -> getString(R.string.dial_hint) + else -> "" + } + tvDialHint.text = text + tvDialHint.visible(text.isNotEmpty()) + } + + private fun renderPageDots() { + val active = if (TimerCore.countUp) 1 else 0 + val accent = col(R.color.brand) + val idle = col(R.color.ring_track) + for (i in 0 until pageDots.childCount) { + val v = pageDots.getChildAt(i) + val lp = v.layoutParams as LinearLayout.LayoutParams + lp.width = dpi(if (i == active) 16f else 6f) + v.layoutParams = lp + v.background = requireContext().roundBg(if (i == active) accent else idle, 100f) + } + } + + private fun applySegments(focusMode: Boolean) { + val onText = col(R.color.title) + val offText = col(R.color.text_secondary) + fun style(tv: TextView, selected: Boolean) { + tv.background = if (selected) ContextCompat.getDrawable(requireContext(), R.drawable.bg_segment_on) else null + tv.setTextColor(if (selected) onText else offText) + tv.typeface = if (selected) android.graphics.Typeface.DEFAULT_BOLD else android.graphics.Typeface.DEFAULT + tv.alpha = if (selected) 1f else 0.9f + } + style(segFocus, focusMode) + style(segBreak, !focusMode) + segFocus.isEnabled = !TimerCore.running + segBreak.isEnabled = !TimerCore.running + } + + private fun renderDots(accent: Int) { + val every = Prefs.longBreakEvery.coerceAtLeast(2) + dots.visible(!TimerCore.countUp) + if (TimerCore.countUp) return + if (dots.childCount != every) { + dots.removeAllViews() + repeat(every) { + val v = View(requireContext()) + val lp = LinearLayout.LayoutParams(dpi(7f), dpi(7f)) + lp.marginStart = dpi(4f) + lp.marginEnd = dpi(4f) + v.layoutParams = lp + dots.addView(v) + } + } + val filled = if (TimerCore.round > 0 && TimerCore.round % every == 0) every else TimerCore.round % every + for (i in 0 until every) { + dots.getChildAt(i).background = circleBg( + if (i < filled) accent else col(R.color.ring_track) + ) + } + } + + private fun renderTask() { + if (TimerCore.taskId != cachedTaskId) { + cachedTaskId = TimerCore.taskId + cachedTask = if (TimerCore.taskId > 0) Store.task(TimerCore.taskId) else null + cachedProject = cachedTask?.let { Store.project(it.projectId) } + } + val task = cachedTask + if (task == null) { + taskDot.visible(false) + tvTask.text = getString(R.string.no_task) + tvTaskMeta.text = getString(R.string.current_task) + tvTaskAction.text = getString(R.string.pick_task) + return + } + val project = cachedProject + taskDot.visible(true) + taskDot.background = circleBg(project?.color ?: 0xFF7A756C.toInt()) + tvTask.text = task.title + val projectName = project?.name ?: getString(R.string.inbox) + tvTaskMeta.text = "$projectName · ${task.focusMinutes} 分钟 · 已完成 ${task.donePomodoros} 次" + tvTaskAction.text = getString(R.string.pick_task) + } + + // ------------------------------------------------------------------ 手势 + + private fun handleDialTouch(ev: MotionEvent): Boolean { + when (ev.actionMasked) { + MotionEvent.ACTION_DOWN -> { + downX = ev.x + downY = ev.y + touchMode = 0 + dragging = false + dragStartMinutes = TimerCore.durationMinutes() + } + + MotionEvent.ACTION_MOVE -> { + val dx = ev.x - downX + val dy = ev.y - downY + if (touchMode == 0) { + if (abs(dx) > slop || abs(dy) > slop) { + touchMode = when { + abs(dx) > abs(dy) -> 2 + TimerCore.running || TimerCore.countUp -> 3 + else -> 1 + } + } + } + if (touchMode == 1) { + val pxPerMinute = dpi(9f).toFloat().coerceAtLeast(1f) + val delta = ((downY - ev.y) / pxPerMinute).toInt() + val target = (dragStartMinutes + delta) + .coerceIn(TimerCore.MIN_MINUTES, TimerCore.MAX_MINUTES) + if (target != TimerCore.durationMinutes()) { + dragging = true + // 拖动过程不落盘,抬手时统一保存 + TimerCore.setDurationMinutes(target, persist = false) + render() + } + } + } + + MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { + if (touchMode == 1 && dragging) { + dragging = false + TimerCore.setDurationMinutes(TimerCore.durationMinutes(), persist = true) + render() + } else if (touchMode == 2) { + val dx = ev.x - downX + if (abs(dx) > dpi(44f)) switchPage(dx < 0) + } + touchMode = 0 + } + } + return true + } + + /** 左滑进正计时,右滑回倒计时;计时中不允许切,否则语义会打架 */ + private fun switchPage(toCountUp: Boolean) { + if (TimerCore.running) { + Toast.makeText(requireContext(), R.string.timer_busy, Toast.LENGTH_SHORT).show() + return + } + if (TimerCore.countUp == toCountUp) return + val dir = if (toCountUp) -1f else 1f + val shift = dpi(36f).toFloat() + dialWrap.animate() + .translationX(dir * shift) + .alpha(0f) + .setDuration(110) + .withEndAction { + if (view == null) return@withEndAction + TimerCore.setCountUp(toCountUp) + render() + dialWrap.translationX = -dir * shift + dialWrap.animate().translationX(0f).alpha(1f).setDuration(140).start() + } + .start() + } + + // ------------------------------------------------------------------ 任务 + + private fun pickTask() { + val tasks = Store.tasks(includeDone = false) + if (tasks.isEmpty()) { + AlertDialog.Builder(requireContext()) + .setMessage(R.string.no_task_to_pick) + .setPositiveButton(R.string.save, null) + .show() + return + } + val names = tasks.map { t -> + val p = Store.project(t.projectId) + (p?.name?.let { "$it · " } ?: "") + t.title + } + getString(R.string.no_task) + val current = tasks.indexOfFirst { it.id == TimerCore.taskId } + AlertDialog.Builder(requireContext()) + .setTitle(R.string.pick_task) + .setSingleChoiceItems(names.toTypedArray(), current) { d, which -> + if (which == tasks.size) { + TimerCore.setTask(0, 0) + } else { + val t = tasks[which] + // 选中任务后回到倒计时,并把圆环切到该任务设定的时长 + TimerCore.setCountUp(false) + TimerCore.setTask(t.id, t.projectId, t.focusMinutes) + } + d.dismiss() + render() + } + .show() + } + + private fun applyKeepScreen(on: Boolean) { + if (keepScreen == on) return + keepScreen = on + val w = requireActivity().window + if (on) w.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) + else w.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) + } + + private fun requestNotifPermissionIfNeeded() { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return + val ctx = context ?: return + if (ContextCompat.checkSelfPermission(ctx, Manifest.permission.POST_NOTIFICATIONS) + != PackageManager.PERMISSION_GRANTED + ) { + requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), 101) + } + } +} diff --git a/src/main/java/com/focusbox/app/ui/projects/ProjectAdapter.kt b/src/main/java/com/focusbox/app/ui/projects/ProjectAdapter.kt new file mode 100644 index 0000000..d2a3bd4 --- /dev/null +++ b/src/main/java/com/focusbox/app/ui/projects/ProjectAdapter.kt @@ -0,0 +1,71 @@ +package com.focusbox.app.ui.projects + +import android.content.res.ColorStateList +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.ImageView +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.util.Dates +import com.focusbox.app.util.col +import com.focusbox.app.util.roundBg +import com.focusbox.app.util.tint + +class ProjectAdapter( + private val onClick: (Project) -> Unit, + private val onLongClick: (Project) -> Unit, + private val onMore: (Project) -> Unit, +) : RecyclerView.Adapter() { + + private var items: List = emptyList() + + fun submit(list: List) { + items = list + notifyDataSetChanged() + } + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH = + VH(LayoutInflater.from(parent.context).inflate(R.layout.item_project, parent, false)) + + override fun getItemCount(): Int = items.size + + override fun onBindViewHolder(holder: VH, position: Int) = holder.bind(items[position]) + + inner class VH(v: View) : RecyclerView.ViewHolder(v) { + private val name: TextView = v.findViewById(R.id.tvName) + private val meta: TextView = v.findViewById(R.id.tvMeta) + 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) + + fun bind(p: Project) { + val ctx = itemView.context + name.text = p.name + colorBar.background = ctx.roundBg(p.color, 2f) + + // 只看任务与时长,不再显示番茄数 + val parts = ArrayList(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(" · ") + + progress.progress = (p.progress * 100).toInt() + progress.progressTintList = ColorStateList.valueOf(p.color) + progress.progressBackgroundTintList = ColorStateList.valueOf(ctx.col(R.color.ring_track)) + + more.tint(ctx.col(R.color.text_tertiary)) + more.setOnClickListener { onMore(p) } + + itemView.setOnClickListener { onClick(p) } + itemView.setOnLongClickListener { + onLongClick(p) + true + } + } + } +} diff --git a/src/main/java/com/focusbox/app/ui/projects/ProjectSheet.kt b/src/main/java/com/focusbox/app/ui/projects/ProjectSheet.kt new file mode 100644 index 0000000..6ea1715 --- /dev/null +++ b/src/main/java/com/focusbox/app/ui/projects/ProjectSheet.kt @@ -0,0 +1,99 @@ +package com.focusbox.app.ui.projects + +import android.content.Context +import android.graphics.Color +import android.view.Gravity +import android.view.LayoutInflater +import android.view.View +import android.widget.EditText +import android.widget.FrameLayout +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.Project +import com.focusbox.app.ui.SheetDialog +import com.focusbox.app.util.Palette +import com.focusbox.app.util.circleBg +import com.focusbox.app.util.dpi +import com.focusbox.app.util.roundBg +import com.focusbox.app.util.visible + +class ProjectSheet( + context: Context, + private val existing: Project?, + private val onSaved: () -> Unit, +) : SheetDialog(context) { + + private val root = LayoutInflater.from(context).inflate(R.layout.sheet_project, null) + private val etName: EditText = root.findViewById(R.id.etName) + private val colorRow: LinearLayout = root.findViewById(R.id.colorRow) + + private var color: Int = existing?.color ?: Palette.colorAt(0) + + init { + setContentView(root) + root.findViewById(R.id.sheetTitle).setText( + if (existing == null) R.string.add_project else R.string.edit + ) + etName.setText(existing?.name ?: "") + renderColors() + + val btnDelete = root.findViewById(R.id.btnDelete) + val deletable = existing != null && existing.id != Store.INBOX_ID + btnDelete.visible(deletable) + btnDelete.setOnClickListener { + existing ?: return@setOnClickListener + AlertDialog.Builder(context) + .setMessage(context.getString(R.string.delete_project_confirm, existing.name)) + .setNegativeButton(R.string.cancel, null) + .setPositiveButton(R.string.delete) { _, _ -> + Store.deleteProject(existing.id) + onSaved() + dismiss() + } + .show() + } + + root.findViewById(R.id.btnSave).setOnClickListener { + val name = etName.text.toString().trim() + if (name.isEmpty()) { + etName.error = context.getString(R.string.project_name_hint) + return@setOnClickListener + } + if (existing == null) { + Store.addProject(name, color) + } else { + Store.updateProject(existing.id, name, color, existing.archived) + } + onSaved() + dismiss() + } + } + + 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 + + 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) + + wrap.setOnClickListener { + color = c + renderColors() + } + colorRow.addView(wrap) + } + } +} diff --git a/src/main/java/com/focusbox/app/ui/projects/ProjectsFragment.kt b/src/main/java/com/focusbox/app/ui/projects/ProjectsFragment.kt new file mode 100644 index 0000000..356da0e --- /dev/null +++ b/src/main/java/com/focusbox/app/ui/projects/ProjectsFragment.kt @@ -0,0 +1,118 @@ +package com.focusbox.app.ui.projects + +import android.os.Bundle +import android.view.View +import android.widget.TextView +import androidx.appcompat.app.AlertDialog +import androidx.fragment.app.Fragment +import androidx.recyclerview.widget.LinearLayoutManager +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.ui.MainActivity +import com.focusbox.app.util.visible + +class ProjectsFragment : Fragment(R.layout.fragment_projects) { + + private lateinit var recycler: RecyclerView + private lateinit var tvSummary: TextView + private lateinit var tvEmpty: TextView + private lateinit var btnArchived: TextView + private lateinit var adapter: ProjectAdapter + + private var showArchived = false + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + recycler = view.findViewById(R.id.recycler) + tvSummary = view.findViewById(R.id.tvSummary) + tvEmpty = view.findViewById(R.id.tvEmpty) + btnArchived = view.findViewById(R.id.btnArchived) + + adapter = ProjectAdapter( + onClick = { p -> (activity as? MainActivity)?.openProjectTasks(p.id) }, + onLongClick = { p -> showActions(p) }, + onMore = { p -> showActions(p) }, + ) + recycler.layoutManager = LinearLayoutManager(requireContext()) + recycler.adapter = adapter + recycler.itemAnimator = null + + view.findViewById(R.id.btnAdd).setOnClickListener { + ProjectSheet(requireContext(), null) { reload() }.show() + } + btnArchived.setOnClickListener { + showArchived = !showArchived + reload() + } + reload() + } + + override fun onResume() { + super.onResume() + if (view != null) reload() + } + + override fun onHiddenChanged(hidden: Boolean) { + super.onHiddenChanged(hidden) + if (!hidden && view != null) reload() + } + + fun reload() { + if (view == null) return + val all = Store.projects(includeArchived = true) + val active = all.filter { !it.archived } + val archived = all.filter { it.archived } + + val shown = if (showArchived) all else active + adapter.submit(shown) + + tvSummary.text = getString( + R.string.project_summary, active.size, active.sumOf { it.openTasks } + ) + tvEmpty.visible(shown.isEmpty()) + + if (archived.isEmpty()) { + btnArchived.visible(false) + } else { + btnArchived.visible(true) + btnArchived.text = if (showArchived) "隐藏已归档" else "已归档 ${archived.size}" + } + } + + private fun showActions(p: Project) { + val isInbox = p.id == Store.INBOX_ID + val actions = ArrayList() + actions.add(getString(R.string.edit)) + if (!isInbox) { + actions.add(getString(if (p.archived) R.string.unarchive else R.string.archive)) + actions.add(getString(R.string.delete)) + } + + AlertDialog.Builder(requireContext()) + .setTitle(p.name) + .setItems(actions.toTypedArray()) { _, which -> + when { + which == 0 -> ProjectSheet(requireContext(), p) { reload() }.show() + which == 1 && !isInbox -> { + Store.updateProject(p.id, p.name, p.color, !p.archived) + reload() + } + which == 2 && !isInbox -> confirmDelete(p) + } + } + .show() + } + + private fun confirmDelete(p: Project) { + AlertDialog.Builder(requireContext()) + .setMessage(getString(R.string.delete_project_confirm, p.name)) + .setNegativeButton(R.string.cancel, null) + .setPositiveButton(R.string.delete) { _, _ -> + Store.deleteProject(p.id) + reload() + } + .show() + } +} diff --git a/src/main/java/com/focusbox/app/ui/settings/SettingsFragment.kt b/src/main/java/com/focusbox/app/ui/settings/SettingsFragment.kt new file mode 100644 index 0000000..12ca5d7 --- /dev/null +++ b/src/main/java/com/focusbox/app/ui/settings/SettingsFragment.kt @@ -0,0 +1,305 @@ +package com.focusbox.app.ui.settings + +import android.graphics.Typeface +import android.os.Bundle +import android.view.Gravity +import android.view.View +import android.widget.LinearLayout +import android.widget.TextView +import androidx.appcompat.app.AlertDialog +import androidx.appcompat.widget.SwitchCompat +import androidx.core.content.ContextCompat +import androidx.fragment.app.Fragment +import com.focusbox.app.App +import com.focusbox.app.R +import com.focusbox.app.data.Store +import com.focusbox.app.service.TimerCore +import com.focusbox.app.ui.MainActivity +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.tint + +/** + * 设置页全部用代码搭。这里都是同构的行(标题 + 值/开关/步进器), + * 写进 XML 会得到五个几乎一样的布局文件,改一处字号要同步五遍。 + */ +class SettingsFragment : Fragment(R.layout.fragment_settings) { + + private lateinit var container: LinearLayout + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + container = view.findViewById(R.id.container) + build() + } + + override fun onResume() { + super.onResume() + if (view != null) build() + } + + private fun build() { + container.removeAllViews() + + section(R.string.section_duration) + card( + stepper( + getString(R.string.duration_focus), + getString(R.string.value_minutes, Prefs.focusMinutes), + ) { delta -> + Prefs.focusMinutes += delta * 5 + if (!TimerCore.running && TimerCore.mode == TimerCore.MODE_FOCUS) TimerCore.applyDefaultDuration() + build() + }, + stepper( + getString(R.string.duration_short), + getString(R.string.value_minutes, Prefs.shortBreakMinutes), + ) { delta -> + Prefs.shortBreakMinutes += delta + if (!TimerCore.running && TimerCore.mode == TimerCore.MODE_SHORT) TimerCore.applyDefaultDuration() + build() + }, + stepper( + getString(R.string.duration_long), + getString(R.string.value_minutes, Prefs.longBreakMinutes), + ) { delta -> + Prefs.longBreakMinutes += delta * 5 + if (!TimerCore.running && TimerCore.mode == TimerCore.MODE_LONG) TimerCore.applyDefaultDuration() + build() + }, + stepper( + getString(R.string.long_every), + getString(R.string.value_rounds, Prefs.longBreakEvery), + ) { delta -> + Prefs.longBreakEvery += delta + build() + }, + ) + + section(R.string.section_auto) + card( + toggle(getString(R.string.auto_start_break), Prefs.autoStartBreak) { + Prefs.autoStartBreak = it + }, + toggle(getString(R.string.auto_start_focus), Prefs.autoStartFocus) { + Prefs.autoStartFocus = it + }, + ) + + section(R.string.section_alert) + card( + toggle(getString(R.string.sound), Prefs.soundOn) { Prefs.soundOn = it }, + toggle(getString(R.string.vibrate), Prefs.vibrateOn) { Prefs.vibrateOn = it }, + toggle(getString(R.string.keep_screen_on), Prefs.keepScreenOn) { Prefs.keepScreenOn = it }, + ) + + section(R.string.section_goal) + card( + stepper( + getString(R.string.daily_goal), + getString(R.string.value_minutes, Prefs.dailyGoalMinutes), + ) { delta -> + Prefs.dailyGoalMinutes += delta * 15 + build() + }, + ) + + section(R.string.section_appearance) + card( + action( + getString(R.string.theme), + getString( + when (Prefs.themeMode) { + 1 -> R.string.theme_light + 2 -> R.string.theme_dark + else -> R.string.theme_follow + } + ), + ) { pickTheme() }, + ) + + section(R.string.section_data) + card( + action(getString(R.string.clear_data), "", danger = true) { confirmClear() }, + ) + + container.addView(TextView(requireContext()).apply { + text = getString(R.string.about_version, VERSION) + textSize = 11f + gravity = Gravity.CENTER + setTextColor(col(R.color.text_tertiary)) + setPadding(0, dpi(26f), 0, dpi(10f)) + }) + } + + // ------------------------------------------------------------ 行构造 + + private fun section(titleRes: Int) { + container.addView(TextView(requireContext()).apply { + setText(titleRes) + textSize = 12f + typeface = Typeface.DEFAULT_BOLD + letterSpacing = 0.06f + setTextColor(col(R.color.text_secondary)) + setPadding(dpi(4f), dpi(20f), 0, dpi(6f)) + }) + } + + private fun card(vararg rows: View) { + val ctx = requireContext() + val card = LinearLayout(ctx).apply { + orientation = LinearLayout.VERTICAL + background = ContextCompat.getDrawable(ctx, R.drawable.bg_card) + setPadding(dpi(16f), 0, dpi(16f), 0) + } + rows.forEachIndexed { index, row -> + if (index > 0) card.addView(divider()) + card.addView(row) + } + container.addView(card, LinearLayout.LayoutParams( + LinearLayout.LayoutParams.MATCH_PARENT, + LinearLayout.LayoutParams.WRAP_CONTENT, + )) + } + + private fun divider(): View = View(requireContext()).apply { + layoutParams = LinearLayout.LayoutParams( + LinearLayout.LayoutParams.MATCH_PARENT, 1, + ) + setBackgroundColor(col(R.color.divider)) + } + + private fun stepper(title: String, value: String, onChange: (Int) -> Unit): View { + val ctx = requireContext() + val row = LinearLayout(ctx).apply { + orientation = LinearLayout.HORIZONTAL + gravity = Gravity.CENTER_VERTICAL + minimumHeight = dpi(54f) + } + row.addView(TextView(ctx).apply { + text = title + textSize = 15f + setTextColor(col(R.color.text)) + layoutParams = LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f) + }) + row.addView(stepButton("−") { onChange(-1) }) + row.addView(TextView(ctx).apply { + text = value + textSize = 14f + typeface = Typeface.DEFAULT_BOLD + gravity = Gravity.CENTER + setTextColor(col(R.color.title)) + layoutParams = LinearLayout.LayoutParams(dpi(74f), LinearLayout.LayoutParams.WRAP_CONTENT) + }) + row.addView(stepButton("+") { onChange(1) }) + return row + } + + private fun stepButton(text: String, onClick: () -> Unit): TextView { + val ctx = requireContext() + return TextView(ctx).apply { + this.text = text + textSize = 16f + gravity = Gravity.CENTER + setTextColor(col(R.color.text)) + background = ctx.getDrawable(R.drawable.bg_chip_off) + layoutParams = LinearLayout.LayoutParams(dpi(30f), dpi(30f)) + setOnClickListener { onClick() } + } + } + + private fun toggle(title: String, checked: Boolean, onChange: (Boolean) -> Unit): View { + val ctx = requireContext() + val row = LinearLayout(ctx).apply { + orientation = LinearLayout.HORIZONTAL + gravity = Gravity.CENTER_VERTICAL + minimumHeight = dpi(54f) + setPadding(0, dpi(4f), 0, dpi(4f)) + } + val label = TextView(ctx).apply { + text = title + textSize = 15f + setTextColor(col(R.color.text)) + layoutParams = LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f) + } + val sw = SwitchCompat(ctx).apply { + isChecked = checked + setOnCheckedChangeListener { _, value -> onChange(value) } + } + row.addView(label) + row.addView(sw) + return row + } + + private fun action(title: String, value: String, danger: Boolean = false, onClick: () -> Unit): View { + val ctx = requireContext() + val row = LinearLayout(ctx).apply { + orientation = LinearLayout.HORIZONTAL + gravity = Gravity.CENTER_VERTICAL + minimumHeight = dpi(54f) + setOnClickListener { onClick() } + } + row.addView(TextView(ctx).apply { + text = title + textSize = 15f + setTextColor(col(if (danger) R.color.danger else R.color.text)) + layoutParams = LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f) + }) + if (value.isNotEmpty()) { + row.addView(TextView(ctx).apply { + text = value + textSize = 13f + setTextColor(col(R.color.text_secondary)) + setPadding(0, 0, dpi(6f), 0) + }) + } + row.addView(android.widget.ImageView(ctx).apply { + setImageResource(R.drawable.ic_chevron_right) + tint(col(R.color.text_tertiary)) + layoutParams = LinearLayout.LayoutParams(dpi(15f), dpi(15f)) + }) + return row + } + + // ------------------------------------------------------------ 交互 + + private fun pickTheme() { + val labels = arrayOf( + getString(R.string.theme_follow), + getString(R.string.theme_light), + getString(R.string.theme_dark), + ) + AlertDialog.Builder(requireContext()) + .setTitle(R.string.theme) + .setSingleChoiceItems(labels, Prefs.themeMode) { dialog, which -> + Prefs.themeMode = which + (requireActivity().application as App).applyTheme() + dialog.dismiss() + requireActivity().recreate() + } + .show() + } + + private fun confirmClear() { + AlertDialog.Builder(requireContext()) + .setTitle(R.string.clear_data) + .setMessage(R.string.clear_confirm) + .setNegativeButton(R.string.cancel, null) + .setPositiveButton(R.string.delete) { _, _ -> + TimerCore.reset() + Store.clearAll() + Prefs.clearTimer() + Prefs.timerRound = 0 + TimerCore.resetRound() + (activity as? MainActivity)?.refreshAll() + build() + } + .show() + } + + companion object { + const val VERSION = "0.2.0" + } +} diff --git a/src/main/java/com/focusbox/app/ui/stats/StatsFragment.kt b/src/main/java/com/focusbox/app/ui/stats/StatsFragment.kt new file mode 100644 index 0000000..15483cf --- /dev/null +++ b/src/main/java/com/focusbox/app/ui/stats/StatsFragment.kt @@ -0,0 +1,340 @@ +package com.focusbox.app.ui.stats + +import android.graphics.Typeface +import android.graphics.drawable.GradientDrawable +import android.os.Bundle +import android.view.Gravity +import android.view.View +import android.widget.LinearLayout +import android.widget.TextView +import androidx.core.content.ContextCompat +import androidx.fragment.app.Fragment +import com.focusbox.app.R +import com.focusbox.app.data.Store +import com.focusbox.app.model.ProjectSlice +import com.focusbox.app.util.Dates +import com.focusbox.app.util.Prefs +import com.focusbox.app.util.circleBg +import com.focusbox.app.util.col +import com.focusbox.app.util.dpi +import com.focusbox.app.util.roundBg +import com.focusbox.app.util.visible +import com.focusbox.app.widget.BarChartView +import com.focusbox.app.widget.DonutView +import com.focusbox.app.widget.HeatmapView +import com.focusbox.app.widget.RingView +import java.util.Calendar + +/** + * 统计页。 + * + * 三层信息:今天(我要不要现在开始)→ 本周趋势(这周还行不行)→ 累计与项目分布 + * (时间到底花在哪)。三个区间的切换只影响趋势与分布,不改变"今日"卡片。 + */ +class StatsFragment : Fragment(R.layout.fragment_stats) { + + private lateinit var todayRing: RingView + private lateinit var tvGoalPct: TextView + private lateinit var tvGoalHint: TextView + private lateinit var tvTodayMinutes: TextView + private lateinit var tvTodayPomo: TextView + private lateinit var tvTodayDone: TextView + private lateinit var tvStreak: TextView + private lateinit var barChart: BarChartView + private lateinit var tvTrendTotal: TextView + private lateinit var heatmap: HeatmapView + private lateinit var tvHeatHint: TextView + private lateinit var heatLegend: LinearLayout + private lateinit var donut: DonutView + private lateinit var donutLegend: LinearLayout + private lateinit var donutTask: DonutView + private lateinit var taskLegend: LinearLayout + private lateinit var summaryGrid: LinearLayout + private lateinit var segWeek: TextView + private lateinit var segMonth: TextView + private lateinit var segAll: TextView + + private var range = 0 + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + todayRing = view.findViewById(R.id.todayRing) + tvGoalPct = view.findViewById(R.id.tvGoalPct) + tvGoalHint = view.findViewById(R.id.tvGoalHint) + tvTodayMinutes = view.findViewById(R.id.tvTodayMinutes) + tvTodayPomo = view.findViewById(R.id.tvTodayPomo) + tvTodayDone = view.findViewById(R.id.tvTodayDone) + tvStreak = view.findViewById(R.id.tvStreak) + barChart = view.findViewById(R.id.barChart) + tvTrendTotal = view.findViewById(R.id.tvTrendTotal) + heatmap = view.findViewById(R.id.heatmap) + tvHeatHint = view.findViewById(R.id.tvHeatHint) + heatLegend = view.findViewById(R.id.heatLegend) + donut = view.findViewById(R.id.donut) + donutLegend = view.findViewById(R.id.donutLegend) + donutTask = view.findViewById(R.id.donutTask) + taskLegend = view.findViewById(R.id.taskLegend) + summaryGrid = view.findViewById(R.id.summaryGrid) + segWeek = view.findViewById(R.id.segWeek) + segMonth = view.findViewById(R.id.segMonth) + segAll = view.findViewById(R.id.segAll) + + segWeek.setOnClickListener { switchRange(0) } + segMonth.setOnClickListener { switchRange(1) } + segAll.setOnClickListener { switchRange(2) } + + buildHeatLegend() + reload() + } + + override fun onResume() { + super.onResume() + if (view != null) reload() + } + + override fun onHiddenChanged(hidden: Boolean) { + super.onHiddenChanged(hidden) + if (!hidden && view != null) reload() + } + + private fun switchRange(r: Int) { + if (range == r) return + range = r + reload() + } + + fun reload() { + if (view == null || !isAdded) return + applySegments() + renderToday() + renderTrend() + renderHeatmap() + renderDistribution() + renderTaskDistribution() + renderSummary() + } + + private fun applySegments() { + val ctx = requireContext() + val onText = ctx.col(R.color.title) + val offText = ctx.col(R.color.text_secondary) + listOf(segWeek, segMonth, segAll).forEachIndexed { i, tv -> + val selected = i == range + tv.background = if (selected) { + ContextCompat.getDrawable(ctx, R.drawable.bg_segment_on) + } else null + tv.setTextColor(if (selected) onText else offText) + tv.typeface = if (selected) Typeface.DEFAULT_BOLD else Typeface.DEFAULT + } + } + + private fun renderToday() { + val goal = Prefs.dailyGoalMinutes + val stat = Store.todayStat(goal) + todayRing.progress = stat.goalProgress + todayRing.ringColor = col(if (stat.goalProgress >= 1f) R.color.rest else R.color.brand) + tvGoalPct.text = "${(stat.goalProgress * 100).toInt()}%" + tvGoalHint.text = "目标 ${goal}m" + tvTodayMinutes.text = "${stat.minutes} 分钟" + tvTodayPomo.text = "${stat.pomodoros}" + tvTodayDone.text = "${stat.doneTasks}" + val streak = Store.streak() + tvStreak.text = "连续打卡 ${streak} 天 · 目标 ${goal} 分钟" + } + + private fun rangeStart(): Long = when (range) { + 0 -> Dates.weekStart() + 1 -> Store.monthStart() + else -> 0L + } + + private fun renderTrend() { + val from: Long + val days: Int + when (range) { + 0 -> { + from = Dates.weekStart() + days = (((Dates.todayStart() - from) / 86_400_000L).toInt() + 1).coerceIn(1, 7) + } + 1 -> { + from = Store.monthStart() + val c = Calendar.getInstance() + days = c.get(Calendar.DAY_OF_MONTH).coerceIn(1, 31) + } + else -> { + from = Dates.addDays(Dates.todayStart(), -29) + days = 30 + } + } + val series = Store.dailySeries(from, days) + barChart.setData(series) + val totalMinutes = series.sumOf { it.minutes } + tvTrendTotal.text = if (totalMinutes <= 0) { + getString(R.string.no_data) + } else { + "共 ${Dates.duration(totalMinutes * 60)}" + } + } + + private fun renderHeatmap() { + val series = Store.dailySeries(Dates.addDays(Dates.todayStart(), -83), 84) + heatmap.setData(series) + val activeDays = series.count { it.minutes > 0 } + tvHeatHint.text = "近 12 周 · $activeDays 天有记录" + } + + private fun buildHeatLegend() { + val ctx = requireContext() + heatLegend.removeAllViews() + heatLegend.addView(label("少")) + for (i in 0..4) { + val box = View(ctx) + val lp = LinearLayout.LayoutParams(dpi(11f), dpi(11f)) + lp.marginStart = dpi(3f) + lp.marginEnd = dpi(3f) + box.layoutParams = lp + box.background = ctx.roundBg(ctx.col(heatColorRes(i)), 3f) + heatLegend.addView(box) + } + heatLegend.addView(label("多")) + } + + private fun heatColorRes(index: Int): Int = when (index) { + 0 -> R.color.heat0 + 1 -> R.color.heat1 + 2 -> R.color.heat2 + 3 -> R.color.heat3 + else -> R.color.heat4 + } + + private fun label(text: String): TextView = TextView(requireContext()).apply { + this.text = text + textSize = 10f + setTextColor(col(R.color.text_tertiary)) + gravity = Gravity.CENTER_VERTICAL + } + + private fun renderDistribution() { + val slices = Store.distribution(rangeStart()) + donut.caption = getString(R.string.total_focus) + donut.setSlices(slices) + fillLegend(donutLegend, slices, R.string.more_projects) + } + + /** 任务分布:同样一张占比环,数据换成按任务分组 */ + private fun renderTaskDistribution() { + val slices = Store.taskSlices(rangeStart()) + donutTask.caption = getString(R.string.task_share) + donutTask.setSlices(slices) + fillLegend(taskLegend, slices, R.string.more_tasks) + } + + private fun fillLegend(container: LinearLayout, slices: List, moreRes: Int) { + container.removeAllViews() + if (slices.isEmpty()) { + container.addView(TextView(requireContext()).apply { + text = getString(R.string.no_data) + textSize = 13f + setTextColor(col(R.color.text_tertiary)) + }) + return + } + val total = slices.sumOf { it.seconds }.coerceAtLeast(1) + slices.take(5).forEach { s -> container.addView(legendRow(s, total)) } + if (slices.size > 5) { + container.addView(TextView(requireContext()).apply { + text = getString(moreRes, slices.size - 5) + textSize = 11f + setTextColor(col(R.color.text_tertiary)) + setPadding(0, dpi(4f), 0, 0) + }) + } + } + + private fun legendRow(slice: ProjectSlice, total: Int): LinearLayout { + val ctx = requireContext() + val row = LinearLayout(ctx).apply { + orientation = LinearLayout.HORIZONTAL + gravity = Gravity.CENTER_VERTICAL + setPadding(0, dpi(4f), 0, dpi(4f)) + } + val dot = View(ctx) + val dlp = LinearLayout.LayoutParams(dpi(8f), dpi(8f)) + dlp.marginEnd = dpi(7f) + dot.layoutParams = dlp + dot.background = circleBg(if (slice.color == -1) ctx.col(R.color.text_tertiary) else slice.color) + + val name = TextView(ctx).apply { + text = slice.name + textSize = 12.5f + setTextColor(col(R.color.text)) + maxLines = 1 + ellipsize = android.text.TextUtils.TruncateAt.END + } + val nameLp = LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f) + name.layoutParams = nameLp + + val pct = (slice.seconds * 100 / total).coerceAtLeast(1) + val value = TextView(ctx).apply { + text = "$pct%" + textSize = 12f + setTextColor(col(R.color.text_secondary)) + } + row.addView(dot) + row.addView(name) + row.addView(value) + return row + } + + private fun renderSummary() { + val totals = Store.totals() + summaryGrid.removeAllViews() + summaryGrid.addView( + statPair( + getString(R.string.total_focus), Dates.duration(totals.seconds), + getString(R.string.total_pomo), "${totals.pomodoros}", + ) + ) + summaryGrid.addView( + statPair( + getString(R.string.total_done_tasks), "${totals.doneTasks}", + getString(R.string.streak_days), getString(R.string.streak_value, totals.streak), + ) + ) + } + + private fun statPair(k1: String, v1: String, k2: String, v2: String): LinearLayout { + val row = LinearLayout(requireContext()).apply { + orientation = LinearLayout.HORIZONTAL + } + row.addView(cell(k1, v1), LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f)) + row.addView(cell(k2, v2), LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f).apply { + marginStart = dpi(12f) + }) + val lp = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT) + lp.bottomMargin = dpi(10f) + row.layoutParams = lp + return row + } + + private fun cell(key: String, value: String): LinearLayout { + val ctx = requireContext() + return LinearLayout(ctx).apply { + orientation = LinearLayout.VERTICAL + background = ctx.roundBg(ctx.col(R.color.surface_alt), 12f) + setPadding(dpi(12f), dpi(10f), dpi(12f), dpi(10f)) + addView(TextView(ctx).apply { + text = value + textSize = 17f + typeface = Typeface.DEFAULT_BOLD + setTextColor(col(R.color.title)) + }) + addView(TextView(ctx).apply { + text = key + textSize = 11f + setTextColor(col(R.color.text_tertiary)) + setPadding(0, dpi(2f), 0, 0) + }) + } + } +} diff --git a/src/main/java/com/focusbox/app/ui/tasks/TaskAdapter.kt b/src/main/java/com/focusbox/app/ui/tasks/TaskAdapter.kt new file mode 100644 index 0000000..82edcd6 --- /dev/null +++ b/src/main/java/com/focusbox/app/ui/tasks/TaskAdapter.kt @@ -0,0 +1,154 @@ +package com.focusbox.app.ui.tasks + +import android.graphics.Paint +import android.graphics.Typeface +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.ImageView +import android.widget.TextView +import androidx.recyclerview.widget.RecyclerView +import com.focusbox.app.R +import com.focusbox.app.model.Task +import com.focusbox.app.util.Dates +import com.focusbox.app.util.circleBg +import com.focusbox.app.util.col +import com.focusbox.app.util.roundBg +import com.focusbox.app.util.tint +import com.focusbox.app.util.visible + +class TaskAdapter( + private val onEdit: (Task) -> Unit, + private val onToggle: (Task) -> Unit, + private val onStart: (Task) -> Unit, + private val onFooterClick: () -> Unit, +) : RecyclerView.Adapter() { + + sealed class Row { + data class Item( + val task: Task, + val projectName: String, + val projectColor: Int, + val overdue: Boolean, + /** 已完成任务的"日期 星期 起-止",无记录时为 null */ + val doneRange: String? = null, + ) : Row() + + data class Footer(val text: String) : Row() + } + + private var rows: List = emptyList() + + fun submit(list: List) { + rows = list + notifyDataSetChanged() + } + + override fun getItemViewType(position: Int): Int = + if (rows[position] is Row.Footer) TYPE_FOOTER else TYPE_TASK + + override fun getItemCount(): Int = rows.size + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { + val inflater = LayoutInflater.from(parent.context) + return if (viewType == TYPE_FOOTER) { + FooterViewHolder(inflater.inflate(R.layout.item_footer, parent, false)) + } else { + TaskViewHolder(inflater.inflate(R.layout.item_task, parent, false)) + } + } + + override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { + when (val row = rows[position]) { + is Row.Item -> (holder as TaskViewHolder).bind(row) + is Row.Footer -> (holder as FooterViewHolder).bind(row) + } + } + + 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) + private val tvNote: TextView = v.findViewById(R.id.tvNote) + private val checkCircle: View = v.findViewById(R.id.checkCircle) + private val checkMark: ImageView = v.findViewById(R.id.checkMark) + private val checkWrap: View = v.findViewById(R.id.checkWrap) + private val btnPlay: ImageView = v.findViewById(R.id.btnPlay) + + fun bind(row: Row.Item) { + val task = row.task + val ctx = itemView.context + + tvTitle.text = task.title + tvTitle.paintFlags = if (task.done) { + tvTitle.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG + } else { + tvTitle.paintFlags and Paint.STRIKE_THRU_TEXT_FLAG.inv() + } + tvTitle.setTextColor(ctx.col(if (task.done) R.color.text_tertiary else R.color.text)) + tvTitle.typeface = if (task.priority >= 2 && !task.done) Typeface.DEFAULT_BOLD else Typeface.DEFAULT + + if (task.done) { + checkCircle.background = ctx.circleBg(ctx.col(R.color.brand)) + checkMark.visible(true) + checkMark.tint(ctx.col(R.color.on_brand)) + } else { + checkCircle.background = ctx.roundBg( + android.graphics.Color.TRANSPARENT, 100f, ctx.col(R.color.field_stroke), 1.5f + ) + checkMark.visible(false) + } + + tvMeta.text = buildMeta(row) + tvMeta.setTextColor( + ctx.col( + when { + row.overdue && !task.done -> R.color.brand + else -> R.color.text_tertiary + } + ) + ) + + // 备注单独一行,跟在"项目 · 日期"下面,避免挤在元信息里被截断 + tvNote.text = task.note + tvNote.visible(task.note.isNotBlank()) + + btnPlay.visible(!task.done) + btnPlay.tint(ctx.col(R.color.text_tertiary)) + + checkWrap.setOnClickListener { onToggle(task) } + itemView.setOnClickListener { onEdit(task) } + btnPlay.setOnClickListener { onStart(task) } + } + + private fun buildMeta(row: Row.Item): String { + val task = row.task + val parts = ArrayList(4) + parts.add(row.projectName) + if (task.done) { + row.doneRange?.let { parts.add(it) } + return parts.joinToString(" · ") + } + parts.add("${task.focusMinutes} 分钟") + if (task.due > 0) { + val label = Dates.dueLabel(task.due) + parts.add(if (row.overdue) "已逾期 · $label" else label) + } + if (task.priority >= 2) parts.add("高优先") + return parts.joinToString(" · ") + } + } + + private inner class FooterViewHolder(v: View) : RecyclerView.ViewHolder(v) { + private val tv: TextView = v.findViewById(R.id.tvFooter) + + fun bind(row: Row.Footer) { + tv.text = row.text + itemView.setOnClickListener { onFooterClick() } + } + } + + companion object { + private const val TYPE_TASK = 0 + private const val TYPE_FOOTER = 1 + } +} diff --git a/src/main/java/com/focusbox/app/ui/tasks/TaskSheet.kt b/src/main/java/com/focusbox/app/ui/tasks/TaskSheet.kt new file mode 100644 index 0000000..bd97d96 --- /dev/null +++ b/src/main/java/com/focusbox/app/ui/tasks/TaskSheet.kt @@ -0,0 +1,233 @@ +package com.focusbox.app.ui.tasks + +import android.app.DatePickerDialog +import android.content.Context +import android.view.LayoutInflater +import android.view.View +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 +import com.focusbox.app.model.Task +import com.focusbox.app.service.TimerCore +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.makeChip +import com.focusbox.app.util.visible +import java.util.Calendar + +/** + * 新建 / 编辑任务。 + * + * 项目、优先级、重复单位都用互斥胶囊,而不是下拉菜单—— + * 常用项不超过 8 个,一屏点完比"打开选择器再确认"少两次操作。 + */ +class TaskSheet( + context: Context, + private val existing: Task?, + presetProjectId: Long, + private val onSaved: () -> Unit, +) : SheetDialog(context) { + + private val root = LayoutInflater.from(context).inflate(R.layout.sheet_task, null) + + private val etTitle: EditText = root.findViewById(R.id.etTitle) + private val etNote: EditText = root.findViewById(R.id.etNote) + private val projectRow: LinearLayout = root.findViewById(R.id.projectRow) + private val priorityRow: LinearLayout = root.findViewById(R.id.priorityRow) + private val repeatRow: LinearLayout = root.findViewById(R.id.repeatRow) + private val repeatEveryRow: View = root.findViewById(R.id.repeatEveryRow) + private val tvFocus: TextView = root.findViewById(R.id.tvFocus) + private val tvEvery: TextView = root.findViewById(R.id.tvEvery) + private val btnDue: TextView = root.findViewById(R.id.btnDue) + private val btnClearDue: View = root.findViewById(R.id.btnClearDue) + + private var projectId: Long = existing?.projectId + ?: if (presetProjectId > 0) presetProjectId else Store.INBOX_ID + private var priority: Int = existing?.priority ?: 1 + // 旧数据的时长可能超出新范围(早先是"番茄数×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 repeatType: Int = existing?.repeatType ?: Repeat.NONE + private var repeatEvery: Int = existing?.repeatEvery ?: 1 + + init { + setContentView(root) + window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE) + + root.findViewById(R.id.sheetTitle).setText( + if (existing == null) R.string.add_task else R.string.edit + ) + + etTitle.setText(existing?.title ?: "") + etNote.setText(existing?.note ?: "") + renderFocus() + + root.findViewById(R.id.btnFocusMinus).setOnClickListener { + focusMin = (focusMin - 5).coerceAtLeast(TimerCore.MIN_MINUTES) + renderFocus() + } + root.findViewById(R.id.btnFocusPlus).setOnClickListener { + focusMin = (focusMin + 5).coerceAtMost(TimerCore.MAX_MINUTES) + renderFocus() + } + + root.findViewById(R.id.btnEveryMinus).setOnClickListener { + repeatEvery = (repeatEvery - 1).coerceAtLeast(1) + renderRepeat() + } + root.findViewById(R.id.btnEveryPlus).setOnClickListener { + repeatEvery = (repeatEvery + 1).coerceAtMost(30) + renderRepeat() + } + + btnDue.setOnClickListener { pickDate() } + btnClearDue.setOnClickListener { + due = 0L + updateDue() + } + + val btnDelete = root.findViewById(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) } + onSaved() + dismiss() + } + .show() + } + + root.findViewById(R.id.btnSave).setOnClickListener { save() } + + renderProjects() + renderPriority() + renderRepeat() + updateDue() + } + + private fun renderProjects() { + val ctx = context + projectRow.removeAllViews() + Store.projects().filter { !it.archived || it.id == projectId }.forEach { p -> + val chip = ctx.makeChip(p.name, p.id == projectId, p.color) + chip.setOnClickListener { + projectId = p.id + renderProjects() + } + projectRow.addView(chip) + } + } + + private fun renderPriority() { + val ctx = context + priorityRow.removeAllViews() + val labels = listOf(R.string.p_low, R.string.p_mid, R.string.p_high) + labels.forEachIndexed { index, res -> + val chip = ctx.makeChip(ctx.getString(res), index == priority) + chip.setOnClickListener { + priority = index + renderPriority() + } + priorityRow.addView(chip) + } + } + + private fun renderFocus() { + tvFocus.text = context.getString(R.string.minutes_value, focusMin) + } + + /** 重复单位四选一;选了非"不重复"才露出间隔步进器 */ + private fun renderRepeat() { + val ctx = context + repeatRow.removeAllViews() + val labels = listOf( + Repeat.NONE to R.string.repeat_none, + Repeat.DAY to R.string.repeat_day, + Repeat.WEEK to R.string.repeat_week, + Repeat.MONTH to R.string.repeat_month, + ) + labels.forEach { (type, res) -> + val chip = ctx.makeChip(ctx.getString(res), repeatType == type) + chip.setOnClickListener { + repeatType = type + renderRepeat() + } + repeatRow.addView(chip) + } + val repeating = repeatType != Repeat.NONE + repeatEveryRow.visible(repeating) + if (repeating) { + val unit = ctx.getString( + when (repeatType) { + Repeat.WEEK -> R.string.repeat_week_unit + Repeat.MONTH -> R.string.repeat_month_unit + else -> R.string.repeat_day_unit + } + ) + tvEvery.text = "$repeatEvery $unit" + } + } + + private fun updateDue() { + btnDue.text = if (due > 0) Dates.mdLong(due) else context.getString(R.string.no_due) + btnDue.setTextColor(context.col(if (due > 0) R.color.text else R.color.text_secondary)) + btnClearDue.visible(due > 0) + } + + private fun pickDate() { + val c = Calendar.getInstance() + if (due > 0) c.timeInMillis = due + DatePickerDialog( + context, + { _, y, m, d -> + val cal = Calendar.getInstance() + cal.set(y, m, d, 0, 0, 0) + cal.set(Calendar.MILLISECOND, 0) + due = cal.timeInMillis + updateDue() + }, + c.get(Calendar.YEAR), + c.get(Calendar.MONTH), + c.get(Calendar.DAY_OF_MONTH), + ).show() + } + + private fun save() { + val title = etTitle.text.toString().trim() + if (title.isEmpty()) { + etTitle.error = context.getString(R.string.task_title_hint) + return + } + val note = etNote.text.toString().trim() + val every = if (repeatType == Repeat.NONE) 1 else repeatEvery.coerceAtLeast(1) + if (existing == null) { + Store.addTask(title, note, projectId, priority, focusMin, due, repeatType, every) + } else { + Store.updateTask( + existing.copy( + title = title, + note = note, + projectId = projectId, + priority = priority, + focusMinutes = focusMin, + due = due, + repeatType = repeatType, + repeatEvery = every, + ) + ) + } + onSaved() + dismiss() + } +} diff --git a/src/main/java/com/focusbox/app/ui/tasks/TasksFragment.kt b/src/main/java/com/focusbox/app/ui/tasks/TasksFragment.kt new file mode 100644 index 0000000..29c5266 --- /dev/null +++ b/src/main/java/com/focusbox/app/ui/tasks/TasksFragment.kt @@ -0,0 +1,212 @@ +package com.focusbox.app.ui.tasks + +import android.os.Bundle +import android.view.View +import android.widget.LinearLayout +import android.widget.TextView +import androidx.fragment.app.Fragment +import androidx.recyclerview.widget.LinearLayoutManager +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.SessionSpan +import com.focusbox.app.model.Task +import com.focusbox.app.ui.MainActivity +import com.focusbox.app.util.Dates +import com.focusbox.app.util.makeChip +import com.focusbox.app.util.visible + +/** + * 任务页。 + * + * 顶部胶囊分两组: + * - 视图:全部 / 今日 / 已完成 + * - 项目:收件箱与各项目 + * 视图与项目互斥,选了项目就回到"全部",避免出现"今日 + 某项目"这种没人能解释的组合。 + */ +class TasksFragment : Fragment(R.layout.fragment_tasks) { + + private enum class ViewFilter { ALL, TODAY, DONE } + + private lateinit var recycler: RecyclerView + private lateinit var tvCount: TextView + private lateinit var tvEmpty: TextView + private lateinit var chipRow: LinearLayout + + private lateinit var adapter: TaskAdapter + + private var filterProjectId = 0L + private var viewFilter = ViewFilter.ALL + private var expandedDone = false + private var projects: List = emptyList() + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + recycler = view.findViewById(R.id.recycler) + tvCount = view.findViewById(R.id.tvCount) + tvEmpty = view.findViewById(R.id.tvEmpty) + chipRow = view.findViewById(R.id.chipRow) + + adapter = TaskAdapter( + onEdit = { openSheet(it) }, + onToggle = { task -> + Store.setTaskDone(task.id, !task.done) + reload() + }, + onStart = { task -> (activity as? MainActivity)?.startFocusOn(task) }, + onFooterClick = { + expandedDone = !expandedDone + reload() + }, + ) + recycler.layoutManager = LinearLayoutManager(requireContext()) + recycler.adapter = adapter + recycler.itemAnimator = null + + view.findViewById(R.id.btnAdd).setOnClickListener { + TaskSheet(requireContext(), null, filterProjectId) { reload() }.show() + } + reload() + } + + override fun onResume() { + super.onResume() + if (view != null) reload() + } + + override fun onHiddenChanged(hidden: Boolean) { + super.onHiddenChanged(hidden) + if (!hidden && view != null) reload() + } + + /** 从项目页点进来:只看这个项目的全部任务 */ + fun applyProjectFilter(projectId: Long) { + filterProjectId = projectId + viewFilter = ViewFilter.ALL + if (view != null) reload() + } + + fun reload() { + if (view == null) return + projects = Store.projects() + renderChips() + + val all = Store.tasks(filterProjectId, includeDone = true) + val pending = all.filter { !it.done } + val done = all.filter { it.done } + val spans = if (done.isEmpty()) emptyMap() else Store.lastSessions() + + val rows = ArrayList() + + when (viewFilter) { + ViewFilter.ALL -> { + pending.forEach { rows.add(toRow(it, spans)) } + tvCount.text = getString(R.string.task_count, pending.size) + tvEmpty.setText(R.string.empty_tasks) + if (done.isNotEmpty()) { + if (expandedDone) done.forEach { rows.add(toRow(it, spans)) } + rows.add( + TaskAdapter.Row.Footer( + getString(if (expandedDone) R.string.hide_done else R.string.show_done) + ) + ) + } + } + + ViewFilter.TODAY -> { + val from = Dates.todayStart() + val to = Dates.addDays(from, 1) + val today = pending.filter { it.due >= from && it.due < to } + today.forEach { rows.add(toRow(it, spans)) } + tvCount.text = getString(R.string.task_count_today, today.size) + tvEmpty.setText(R.string.empty_today) + } + + ViewFilter.DONE -> { + done.forEach { rows.add(toRow(it, spans)) } + tvCount.text = getString(R.string.task_count_done, done.size) + tvEmpty.setText(R.string.empty_done) + } + } + + adapter.submit(rows) + tvEmpty.visible(rows.isEmpty()) + recycler.visible(rows.isNotEmpty()) + } + + private fun toRow(task: Task, spans: Map): TaskAdapter.Row.Item { + val project = projects.firstOrNull { it.id == task.projectId } + val overdue = task.due > 0 && task.due < Dates.todayStart() + return TaskAdapter.Row.Item( + task = task, + projectName = project?.name ?: getString(R.string.inbox), + projectColor = project?.color ?: 0xFF7A756C.toInt(), + overdue = overdue, + doneRange = if (task.done) doneRange(task, spans) else null, + ) + } + + /** 11月27日 周五 09:12:03-09:37:03 */ + private fun doneRange(task: Task, spans: Map): String? { + val span = spans[task.id] + if (span != null) { + return "${Dates.dateWithWeek(span.startAt)} " + + "${Dates.hms(span.startAt)}-${Dates.hms(span.endAt)}" + } + if (task.doneAt > 0) { + return "${Dates.dateWithWeek(task.doneAt)} ${Dates.hms(task.doneAt)}" + } + return null + } + + private fun renderChips() { + chipRow.removeAllViews() + val allSelected = viewFilter == ViewFilter.ALL && filterProjectId == 0L + chipRow.addView( + requireContext().makeChip(getString(R.string.filter_all), allSelected) + .also { + it.setOnClickListener { + viewFilter = ViewFilter.ALL + filterProjectId = 0L + reload() + } + } + ) + chipRow.addView( + requireContext().makeChip(getString(R.string.filter_today), viewFilter == ViewFilter.TODAY) + .also { + it.setOnClickListener { + viewFilter = ViewFilter.TODAY + filterProjectId = 0L + reload() + } + } + ) + chipRow.addView( + requireContext().makeChip(getString(R.string.filter_done), viewFilter == ViewFilter.DONE) + .also { + it.setOnClickListener { + viewFilter = ViewFilter.DONE + filterProjectId = 0L + reload() + } + } + ) + projects.forEach { p -> + if (p.archived) return@forEach + val selected = viewFilter == ViewFilter.ALL && filterProjectId == p.id + val chip = requireContext().makeChip(p.name, selected, p.color) + chip.setOnClickListener { + viewFilter = ViewFilter.ALL + filterProjectId = p.id + reload() + } + chipRow.addView(chip) + } + } + + private fun openSheet(task: Task?) { + TaskSheet(requireContext(), task, filterProjectId) { reload() }.show() + } +} diff --git a/src/main/java/com/focusbox/app/util/Chips.kt b/src/main/java/com/focusbox/app/util/Chips.kt new file mode 100644 index 0000000..ed7bdd7 --- /dev/null +++ b/src/main/java/com/focusbox/app/util/Chips.kt @@ -0,0 +1,44 @@ +package com.focusbox.app.util + +import android.content.Context +import android.graphics.drawable.Drawable +import android.graphics.drawable.GradientDrawable +import android.widget.LinearLayout +import android.widget.TextView +import androidx.core.content.ContextCompat +import com.focusbox.app.R + +/** 小圆点,用作项目标记 */ +fun Context.dotDrawable(color: Int, sizeDp: Float = 8f): Drawable = GradientDrawable().apply { + shape = GradientDrawable.OVAL + setColor(color) + setSize(dpi(sizeDp), dpi(sizeDp)) +} + +/** + * 统一的筛选胶囊。选中态用浅品牌底 + 品牌描边, + * 未选中是白底细描边——比 Material Chip 少一层阴影,在浅底上更干净。 + */ +fun Context.makeChip(text: String, selected: Boolean, dotColor: Int? = null): TextView = + TextView(this).apply { + this.text = text + textSize = 12.5f + gravity = android.view.Gravity.CENTER + setTextColor(col(if (selected) R.color.brand else R.color.text_secondary)) + background = ContextCompat.getDrawable( + this@makeChip, + if (selected) R.drawable.bg_chip_on else R.drawable.bg_chip_off, + ) + setPadding(dpi(12f), dpi(7f), dpi(12f), dpi(7f)) + if (dotColor != null) { + val d = this@makeChip.dotDrawable(dotColor) + setCompoundDrawablesRelativeWithIntrinsicBounds(d, null, null, null) + compoundDrawablePadding = dpi(5f) + } + val lp = LinearLayout.LayoutParams( + LinearLayout.LayoutParams.WRAP_CONTENT, + LinearLayout.LayoutParams.WRAP_CONTENT, + ) + lp.marginEnd = dpi(8f) + layoutParams = lp + } diff --git a/src/main/java/com/focusbox/app/util/Dates.kt b/src/main/java/com/focusbox/app/util/Dates.kt new file mode 100644 index 0000000..7b95dfe --- /dev/null +++ b/src/main/java/com/focusbox/app/util/Dates.kt @@ -0,0 +1,125 @@ +package com.focusbox.app.util + +import java.text.SimpleDateFormat +import java.util.Calendar +import java.util.Date +import java.util.Locale + +/** 时间格式化与"自然日"边界计算,全局只此一份,避免各处口径不一。 */ +object Dates { + + 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)) + + fun dayStart(ms: Long): Long { + val c = Calendar.getInstance() + c.timeInMillis = ms + c.set(Calendar.HOUR_OF_DAY, 0) + c.set(Calendar.MINUTE, 0) + c.set(Calendar.SECOND, 0) + c.set(Calendar.MILLISECOND, 0) + return c.timeInMillis + } + + fun dayStartOfKey(key: String): Long = keyFmt.parse(key)?.time ?: 0L + + fun todayStart(): Long = dayStart(System.currentTimeMillis()) + + /** 本周一 00:00(周一为一周起点,符合国内习惯) */ + fun weekStart(): Long { + val c = Calendar.getInstance() + c.timeInMillis = todayStart() + val dow = c.get(Calendar.DAY_OF_WEEK) // 1=周日 + val back = if (dow == Calendar.SUNDAY) 6 else dow - 2 + c.add(Calendar.DAY_OF_MONTH, -back) + return c.timeInMillis + } + + fun monthStart(): Long { + val c = Calendar.getInstance() + c.timeInMillis = todayStart() + c.set(Calendar.DAY_OF_MONTH, 1) + return c.timeInMillis + } + + fun addDays(ms: Long, days: Int): Long { + val c = Calendar.getInstance() + c.timeInMillis = ms + c.add(Calendar.DAY_OF_MONTH, days) + return c.timeInMillis + } + + /** 月末会按当月最后一天收敛(1月31日 + 1月 = 2月28/29日),不会溢出到下个月 */ + fun addMonths(ms: Long, months: Int): Long { + val c = Calendar.getInstance() + c.timeInMillis = ms + c.add(Calendar.MONTH, months) + return c.timeInMillis + } + + /** 12:30 这种时钟显示;不足 10 分钟显示 09:30 两位分 */ + fun clock(ms: Long): String { + val total = (ms / 1000).coerceAtLeast(0) + val m = total / 60 + val s = total % 60 + return String.format(Locale.US, "%02d:%02d", m, s) + } + + /** 45m / 2h10m / 12.5h,统计里统一用这个口径 */ + fun duration(seconds: Int): String { + if (seconds < 60) return "${seconds}秒" + val minutes = seconds / 60 + if (minutes < 60) return "${minutes}分钟" + val h = minutes / 60 + val m = minutes % 60 + return if (m == 0) "${h}小时" else "${h}小时${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 weekday(ms: Long): String { + val c = Calendar.getInstance() + c.timeInMillis = ms + return arrayOf("周日", "周一", "周二", "周三", "周四", "周五", "周六")[ + (c.get(Calendar.DAY_OF_WEEK) - 1).coerceIn(0, 6) + ] + } + + /** 11月27日 周五 */ + fun dateWithWeek(ms: Long): String = "${mdLong(ms)} ${weekday(ms)}" + + /** 今天 / 明天 / 已逾期 / 11月30日 */ + fun dueLabel(due: Long): String { + if (due <= 0) return "" + val today = todayStart() + val d = dayStart(due) + return when { + d == today -> "今天" + d == addDays(today, 1) -> "明天" + d == addDays(today, -1) -> "昨天" + d < today -> md(d) + else -> md(d) + } + } + + fun weekdayShort(index: Int): String = + arrayOf("一", "二", "三", "四", "五", "六", "日")[index.coerceIn(0, 6)] +} diff --git a/src/main/java/com/focusbox/app/util/Palette.kt b/src/main/java/com/focusbox/app/util/Palette.kt new file mode 100644 index 0000000..2fd372a --- /dev/null +++ b/src/main/java/com/focusbox/app/util/Palette.kt @@ -0,0 +1,21 @@ +package com.focusbox.app.util + +/** 项目配色。八色一组,两两之间在色相上有足够间距,圆点上也能分辨。 */ +object Palette { + + val colors = intArrayOf( + 0xFFC75B45.toInt(), // 陶土红 + 0xFFD98324.toInt(), // 琥珀 + 0xFFC9A227.toInt(), // 芥黄 + 0xFF4C8C4A.toInt(), // 苔绿 + 0xFF3F7F6E.toInt(), // 松石 + 0xFF3B7DD8.toInt(), // 靛蓝 + 0xFF6C5CE7.toInt(), // 紫 + 0xFFB7548E.toInt(), // 玫红 + ) + + /** 收件箱用中性灰,避免和自建项目争注意力 */ + const val INBOX = 0xFF7A756C.toInt() + + fun colorAt(index: Int): Int = colors[index.mod(colors.size)] +} diff --git a/src/main/java/com/focusbox/app/util/Prefs.kt b/src/main/java/com/focusbox/app/util/Prefs.kt new file mode 100644 index 0000000..2001c86 --- /dev/null +++ b/src/main/java/com/focusbox/app/util/Prefs.kt @@ -0,0 +1,125 @@ +package com.focusbox.app.util + +import android.content.Context +import android.content.SharedPreferences + +/** + * 全部可调项与计时状态的落盘位置。 + * + * 计时状态必须持久化:息屏被杀进程后重新打开,仍要能接着走同一个番茄, + * 否则用户会看到一个"自己重新开始"的计时器。 + */ +object Prefs { + + private lateinit var sp: SharedPreferences + + fun init(context: Context) { + sp = context.getSharedPreferences("focusbox", Context.MODE_PRIVATE) + } + + // ---- 时长 ---- + var focusMinutes: Int + get() = sp.getInt("focus_minutes", 25) + set(v) = sp.edit().putInt("focus_minutes", v.coerceIn(5, 180)).apply() + + var shortBreakMinutes: Int + get() = sp.getInt("short_break", 5) + set(v) = sp.edit().putInt("short_break", v.coerceIn(1, 60)).apply() + + var longBreakMinutes: Int + get() = sp.getInt("long_break", 15) + set(v) = sp.edit().putInt("long_break", v.coerceIn(5, 90)).apply() + + var longBreakEvery: Int + get() = sp.getInt("long_every", 4) + set(v) = sp.edit().putInt("long_every", v.coerceIn(2, 8)).apply() + + // ---- 自动衔接 ---- + var autoStartBreak: Boolean + get() = sp.getBoolean("auto_break", true) + set(v) = sp.edit().putBoolean("auto_break", v).apply() + + var autoStartFocus: Boolean + get() = sp.getBoolean("auto_focus", false) + set(v) = sp.edit().putBoolean("auto_focus", v).apply() + + // ---- 提醒 ---- + var soundOn: Boolean + get() = sp.getBoolean("sound", true) + set(v) = sp.edit().putBoolean("sound", v).apply() + + var vibrateOn: Boolean + get() = sp.getBoolean("vibrate", true) + set(v) = sp.edit().putBoolean("vibrate", v).apply() + + var keepScreenOn: Boolean + get() = sp.getBoolean("keep_screen", true) + set(v) = sp.edit().putBoolean("keep_screen", v).apply() + + // ---- 目标 ---- + var dailyGoalMinutes: Int + get() = sp.getInt("daily_goal", 120) + set(v) = sp.edit().putInt("daily_goal", v.coerceIn(15, 720)).apply() + + /** 0 跟随系统 / 1 浅色 / 2 深色 */ + var themeMode: Int + get() = sp.getInt("theme_mode", 0) + set(v) = sp.edit().putInt("theme_mode", v).apply() + + // ---- 计时状态 ---- + var timerMode: Int + get() = sp.getInt("t_mode", 0) + set(v) = sp.edit().putInt("t_mode", v).apply() + + var timerRunning: Boolean + get() = sp.getBoolean("t_running", false) + set(v) = sp.edit().putBoolean("t_running", v).apply() + + var timerTotalMs: Long + get() = sp.getLong("t_total", 0L) + set(v) = sp.edit().putLong("t_total", v).apply() + + var timerRemainingMs: Long + get() = sp.getLong("t_remaining", 0L) + set(v) = sp.edit().putLong("t_remaining", v).apply() + + var timerEndAt: Long + get() = sp.getLong("t_end", 0L) + set(v) = sp.edit().putLong("t_end", v).apply() + + var timerTaskId: Long + get() = sp.getLong("t_task", 0L) + set(v) = sp.edit().putLong("t_task", v).apply() + + var timerProjectId: Long + get() = sp.getLong("t_project", 0L) + set(v) = sp.edit().putLong("t_project", v).apply() + + var timerRound: Int + get() = sp.getInt("t_round", 0) + set(v) = sp.edit().putInt("t_round", v).apply() + + var timerStartedAt: Long + get() = sp.getLong("t_started", 0L) + set(v) = sp.edit().putLong("t_started", v).apply() + + /** 是否处于正计时(秒表)页 */ + var timerCountUp: Boolean + get() = sp.getBoolean("t_countup", false) + set(v) = sp.edit().putBoolean("t_countup", v).apply() + + /** 正计时的累计毫秒(暂停时保存的值) */ + var timerAccumMs: Long + get() = sp.getLong("t_accum", 0L) + set(v) = sp.edit().putLong("t_accum", v).apply() + + fun clearTimer() { + sp.edit() + .putBoolean("t_running", false) + .putLong("t_remaining", 0L) + .putLong("t_end", 0L) + .putLong("t_started", 0L) + .putLong("t_accum", 0L) + .apply() + } +} diff --git a/src/main/java/com/focusbox/app/util/Ui.kt b/src/main/java/com/focusbox/app/util/Ui.kt new file mode 100644 index 0000000..778e2ac --- /dev/null +++ b/src/main/java/com/focusbox/app/util/Ui.kt @@ -0,0 +1,97 @@ +package com.focusbox.app.util + +import android.content.Context +import android.graphics.drawable.GradientDrawable +import android.util.TypedValue +import android.view.View +import android.widget.ImageView +import android.widget.TextView +import androidx.annotation.ColorRes +import androidx.core.content.ContextCompat +import androidx.core.graphics.drawable.DrawableCompat + +fun Context.dpf(v: Float): Float = v * resources.displayMetrics.density + +fun Context.dpi(v: Float): Int = (v * resources.displayMetrics.density).toInt() + +fun Context.col(@ColorRes id: Int): Int = ContextCompat.getColor(this, id) + +fun Context.spf(v: Float): Float = TypedValue.applyDimension( + TypedValue.COMPLEX_UNIT_SP, v, resources.displayMetrics +) + +/* + * 下面几组重载不是冗余:布局代码大量写在 `LinearLayout(ctx).apply { ... }` 里, + * 此时隐式接收者是 View 而不是 Context,只留 Context 版本会导致 dpi/col 全部解析失败。 + * Fragment 版本覆盖 `LinearLayout.LayoutParams(...).apply { marginStart = dpi(4f) }` + * 这类接收者既不是 View 也不是 Context 的场景。 + */ + +fun View.dpi(v: Float): Int = context.dpi(v) + +fun View.col(@ColorRes id: Int): Int = context.col(id) + +fun androidx.fragment.app.Fragment.dpi(v: Float): Int = requireContext().dpi(v) + +fun androidx.fragment.app.Fragment.col(@ColorRes id: Int): Int = requireContext().col(id) + +fun android.app.Dialog.dpi(v: Float): Int = context.dpi(v) + +fun android.app.Dialog.col(@ColorRes id: Int): Int = context.col(id) + +/** 圆角面板 / 药丸 / 圆点,全部用代码生成,避免为每种尺寸再建一个 drawable */ +fun Context.roundBg(color: Int, radiusDp: Float, strokeColor: Int? = null, strokeDp: Float = 1f): GradientDrawable = + GradientDrawable().apply { + shape = GradientDrawable.RECTANGLE + cornerRadius = dpf(radiusDp) + setColor(color) + if (strokeColor != null) setStroke(dpi(strokeDp).coerceAtLeast(1), strokeColor) + } + +fun View.roundBg(color: Int, radiusDp: Float, strokeColor: Int? = null, strokeDp: Float = 1f): GradientDrawable = + context.roundBg(color, radiusDp, strokeColor, strokeDp) + +fun androidx.fragment.app.Fragment.roundBg( + color: Int, + radiusDp: Float, + strokeColor: Int? = null, + strokeDp: Float = 1f, +): GradientDrawable = requireContext().roundBg(color, radiusDp, strokeColor, strokeDp) + +fun android.app.Dialog.roundBg( + color: Int, + radiusDp: Float, + strokeColor: Int? = null, + strokeDp: Float = 1f, +): GradientDrawable = context.roundBg(color, radiusDp, strokeColor, strokeDp) + +fun Context.circleBg(color: Int): GradientDrawable = GradientDrawable().apply { + shape = GradientDrawable.OVAL + setColor(color) +} + +fun View.circleBg(color: Int): GradientDrawable = context.circleBg(color) + +fun androidx.fragment.app.Fragment.circleBg(color: Int): GradientDrawable = requireContext().circleBg(color) + +fun android.app.Dialog.circleBg(color: Int): GradientDrawable = context.circleBg(color) + +fun ImageView.tint(color: Int) { + val d = drawable ?: return + val wrapped = DrawableCompat.wrap(d.mutate()) + DrawableCompat.setTint(wrapped, color) + setImageDrawable(wrapped) +} + +fun View.visible(show: Boolean) { + visibility = if (show) View.VISIBLE else View.GONE +} + +/** 统一的行内边距换算,保证不同布局的 16dp 是同一个 16dp */ +fun View.pad(h: Float, v: Float) { + setPadding(context.dpi(h), context.dpi(v), context.dpi(h), context.dpi(v)) +} + +fun TextView.setAlphaCompat(a: Float) { + alpha = a +} diff --git a/src/main/java/com/focusbox/app/widget/Charts.kt b/src/main/java/com/focusbox/app/widget/Charts.kt new file mode 100644 index 0000000..74833ca --- /dev/null +++ b/src/main/java/com/focusbox/app/widget/Charts.kt @@ -0,0 +1,242 @@ +package com.focusbox.app.widget + +import android.content.Context +import android.graphics.Canvas +import android.graphics.Paint +import android.graphics.RectF +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 +import com.focusbox.app.util.spf +import java.util.Calendar + +/** 趋势柱状图:支持 7 / 30 天,柱脚标签按密度抽稀,柱子不会挤成一片色块。 */ +class BarChartView @JvmOverloads constructor( + context: Context, + attrs: AttributeSet? = null, +) : View(context, attrs) { + + private data class Bar(val label: String, val value: Int) + + private var bars: List = emptyList() + + private val barPaint = Paint(Paint.ANTI_ALIAS_FLAG) + private val gridPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + style = Paint.Style.STROKE + strokeWidth = context.dpf(1f) + color = context.col(R.color.divider) + } + private val textPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + textSize = context.spf(10f) + color = context.col(R.color.text_tertiary) + textAlign = Paint.Align.CENTER + } + private val valuePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + textSize = context.spf(10f) + color = context.col(R.color.text_secondary) + textAlign = Paint.Align.CENTER + } + + fun setData(points: List) { + bars = points.map { Bar(it.label, it.minutes) } + invalidate() + } + + override fun onDraw(canvas: Canvas) { + if (bars.isEmpty()) return + + val labelH = context.dpf(20f) + val topPad = context.dpf(18f) + val baseY = height - labelH + val usableH = baseY - topPad + val brand = context.col(R.color.brand) + val soft = context.col(R.color.brand_soft) + val peak = (bars.maxOfOrNull { it.value } ?: 0).coerceAtLeast(30) + + // 两条参考线:一半与峰顶,给出高度感又不喧宾夺主 + gridPaint.color = context.col(R.color.divider) + canvas.drawLine(0f, baseY, width.toFloat(), baseY, gridPaint) + canvas.drawLine(0f, baseY - usableH / 2f, width.toFloat(), baseY - usableH / 2f, gridPaint) + + val n = bars.size + val slot = width.toFloat() / n + val barW = (slot * if (n <= 7) 0.42f else 0.62f).coerceAtLeast(context.dpf(2f)) + val radius = minOf(barW / 2f, context.dpf(4f)) + val lastIndex = n - 1 + + bars.forEachIndexed { i, bar -> + val cx = slot * i + slot / 2f + val h = (bar.value.toFloat() / peak * usableH).coerceAtLeast(if (bar.value > 0) context.dpf(2f) else 0f) + if (h > 0f) { + barPaint.color = if (i == lastIndex) brand else soft + val r = RectF(cx - barW / 2f, baseY - h, cx + barW / 2f, baseY) + canvas.drawRoundRect(r, radius, radius, barPaint) + } + + if (n <= 7) { + if (bar.value > 0) { + valuePaint.color = context.col(R.color.text_secondary) + canvas.drawText("${bar.value}", cx, baseY - h - context.dpf(5f), valuePaint) + } + textPaint.color = context.col(R.color.text_tertiary) + canvas.drawText(bar.label, cx, height - context.dpf(5f), textPaint) + } else if (i % 5 == 0 || i == lastIndex) { + textPaint.color = context.col(R.color.text_tertiary) + canvas.drawText(bar.label, cx, height - context.dpf(5f), textPaint) + } + } + } +} + +/** 打卡热力图:7 行(周一…周日)× N 列(周),色阶五档。 */ +class HeatmapView @JvmOverloads constructor( + context: Context, + attrs: AttributeSet? = null, +) : View(context, attrs) { + + private var days: List = emptyList() + + private val cellPaint = Paint(Paint.ANTI_ALIAS_FLAG) + private val textPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + textSize = context.spf(9f) + color = context.col(R.color.text_tertiary) + textAlign = Paint.Align.RIGHT + } + + private var levels = intArrayOf( + context.col(R.color.heat0), + context.col(R.color.heat1), + context.col(R.color.heat2), + context.col(R.color.heat3), + context.col(R.color.heat4), + ) + + fun setData(points: List) { + days = points + invalidate() + } + + private fun levelOf(minutes: Int): Int = when { + minutes <= 0 -> 0 + minutes < 25 -> 1 + minutes < 50 -> 2 + minutes < 90 -> 3 + else -> 4 + } + + private fun weekdayIndex(ms: Long): Int { + val c = Calendar.getInstance() + c.timeInMillis = ms + val dow = c.get(Calendar.DAY_OF_WEEK) + return if (dow == Calendar.SUNDAY) 6 else dow - 2 + } + + override fun onDraw(canvas: Canvas) { + if (days.isEmpty()) return + + val labelW = context.dpf(16f) + val gap = context.dpf(3f) + val top = context.dpf(2f) + val firstMs = Dates.dayStartOfKey(days.first().key) + val startCol = weekdayIndex(firstMs) // 第一列从周一算起,前面留空 + val totalCells = startCol + days.size + val cols = (totalCells + 6) / 7 + val cellW = (width - labelW - gap * (cols - 1)) / cols + // 高度也要参与取小:宽屏时按宽度算出的格子会把第 7 行挤出可视区 + val cellH = (height - top - gap * 6) / 7f + val cell = minOf(cellW.toFloat(), cellH, context.dpf(15f)) + val radius = cell * 0.28f + + val rect = RectF() + days.forEachIndexed { i, d -> + val pos = startCol + i + val col = pos / 7 + val row = pos % 7 + val x = labelW + col * (cell + gap) + val y = top + row * (cell + gap) + cellPaint.color = levels[levelOf(d.minutes)] + rect.set(x, y, x + cell, y + cell) + canvas.drawRoundRect(rect, radius, radius, cellPaint) + } + + // 只在周一/三/五标字,避免七行小字糊在一起 + val labels = mapOf(0 to "一", 2 to "三", 4 to "五") + labels.forEach { (row, s) -> + val y = top + row * (cell + gap) + cell * 0.78f + canvas.drawText(s, labelW - context.dpf(4f), y, textPaint) + } + } +} + +/** 项目占比环:中间显示总时长,环上按项目分色。 */ +class DonutView @JvmOverloads constructor( + context: Context, + attrs: AttributeSet? = null, +) : View(context, attrs) { + + private var slices: List = 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) { + 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) + } +} diff --git a/src/main/java/com/focusbox/app/widget/RingView.kt b/src/main/java/com/focusbox/app/widget/RingView.kt new file mode 100644 index 0000000..2e70e61 --- /dev/null +++ b/src/main/java/com/focusbox/app/widget/RingView.kt @@ -0,0 +1,73 @@ +package com.focusbox.app.widget + +import android.content.Context +import android.graphics.Canvas +import android.graphics.Paint +import android.graphics.RectF +import android.util.AttributeSet +import android.view.View +import com.focusbox.app.R +import com.focusbox.app.util.col +import com.focusbox.app.util.dpf + +/** + * 计时圆环。 + * + * 只用一条弧表达进度:从 -90° 顺时针扫过 progress * 360°。 + * 进度为 0 时不画弧——圆头端点会在起点留下一个圆点,看起来像"已经走了 1%"。 + */ +class RingView @JvmOverloads constructor( + context: Context, + attrs: AttributeSet? = null, +) : View(context, attrs) { + + var progress: Float = 0f + set(value) { + field = value.coerceIn(0f, 1f) + invalidate() + } + + var ringColor: Int = context.col(R.color.brand) + set(value) { + field = value + invalidate() + } + + var trackColor: Int = context.col(R.color.ring_track) + set(value) { + field = value + invalidate() + } + + var strokeDp: Float = 12f + set(value) { + field = value + invalidate() + } + + private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + style = Paint.Style.STROKE + strokeCap = Paint.Cap.ROUND + } + private val rect = RectF() + + override fun onDraw(canvas: Canvas) { + val stroke = context.dpf(strokeDp) + paint.strokeWidth = stroke + val pad = stroke / 2f + context.dpf(2f) + rect.set(pad, pad, width - pad, height - pad) + val radius = minOf(rect.width(), rect.height()) / 2f + + paint.color = trackColor + canvas.drawCircle(rect.centerX(), rect.centerY(), radius, paint) + + if (progress > 0.002f) { + paint.color = ringColor + val box = RectF( + rect.centerX() - radius, rect.centerY() - radius, + rect.centerX() + radius, rect.centerY() + radius, + ) + canvas.drawArc(box, -90f, 360f * progress, false, paint) + } + } +} diff --git a/src/main/res/anim/sheet_in.xml b/src/main/res/anim/sheet_in.xml new file mode 100644 index 0000000..e2aecb6 --- /dev/null +++ b/src/main/res/anim/sheet_in.xml @@ -0,0 +1,8 @@ + + + + diff --git a/src/main/res/anim/sheet_out.xml b/src/main/res/anim/sheet_out.xml new file mode 100644 index 0000000..0c09ce6 --- /dev/null +++ b/src/main/res/anim/sheet_out.xml @@ -0,0 +1,8 @@ + + + + diff --git a/src/main/res/drawable/bg_btn_ghost.xml b/src/main/res/drawable/bg_btn_ghost.xml new file mode 100644 index 0000000..7dad038 --- /dev/null +++ b/src/main/res/drawable/bg_btn_ghost.xml @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/src/main/res/drawable/bg_btn_primary.xml b/src/main/res/drawable/bg_btn_primary.xml new file mode 100644 index 0000000..5f8adea --- /dev/null +++ b/src/main/res/drawable/bg_btn_primary.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/src/main/res/drawable/bg_card.xml b/src/main/res/drawable/bg_card.xml new file mode 100644 index 0000000..dbcb08c --- /dev/null +++ b/src/main/res/drawable/bg_card.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/src/main/res/drawable/bg_card_alt.xml b/src/main/res/drawable/bg_card_alt.xml new file mode 100644 index 0000000..305577e --- /dev/null +++ b/src/main/res/drawable/bg_card_alt.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/src/main/res/drawable/bg_chip_off.xml b/src/main/res/drawable/bg_chip_off.xml new file mode 100644 index 0000000..7dad038 --- /dev/null +++ b/src/main/res/drawable/bg_chip_off.xml @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/src/main/res/drawable/bg_chip_on.xml b/src/main/res/drawable/bg_chip_on.xml new file mode 100644 index 0000000..1f55999 --- /dev/null +++ b/src/main/res/drawable/bg_chip_on.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/src/main/res/drawable/bg_field.xml b/src/main/res/drawable/bg_field.xml new file mode 100644 index 0000000..a36b4c3 --- /dev/null +++ b/src/main/res/drawable/bg_field.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/src/main/res/drawable/bg_icon_btn.xml b/src/main/res/drawable/bg_icon_btn.xml new file mode 100644 index 0000000..82155ad --- /dev/null +++ b/src/main/res/drawable/bg_icon_btn.xml @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/src/main/res/drawable/bg_segment_on.xml b/src/main/res/drawable/bg_segment_on.xml new file mode 100644 index 0000000..b13e688 --- /dev/null +++ b/src/main/res/drawable/bg_segment_on.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/src/main/res/drawable/bg_segment_track.xml b/src/main/res/drawable/bg_segment_track.xml new file mode 100644 index 0000000..61d523a --- /dev/null +++ b/src/main/res/drawable/bg_segment_track.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/src/main/res/drawable/bg_sheet.xml b/src/main/res/drawable/bg_sheet.xml new file mode 100644 index 0000000..7df426a --- /dev/null +++ b/src/main/res/drawable/bg_sheet.xml @@ -0,0 +1,7 @@ + + + + + diff --git a/src/main/res/drawable/ic_back.xml b/src/main/res/drawable/ic_back.xml new file mode 100644 index 0000000..bd35fa3 --- /dev/null +++ b/src/main/res/drawable/ic_back.xml @@ -0,0 +1,9 @@ + + + diff --git a/src/main/res/drawable/ic_bell.xml b/src/main/res/drawable/ic_bell.xml new file mode 100644 index 0000000..e4335a6 --- /dev/null +++ b/src/main/res/drawable/ic_bell.xml @@ -0,0 +1,9 @@ + + + diff --git a/src/main/res/drawable/ic_calendar.xml b/src/main/res/drawable/ic_calendar.xml new file mode 100644 index 0000000..bc65aac --- /dev/null +++ b/src/main/res/drawable/ic_calendar.xml @@ -0,0 +1,9 @@ + + + diff --git a/src/main/res/drawable/ic_check.xml b/src/main/res/drawable/ic_check.xml new file mode 100644 index 0000000..571e477 --- /dev/null +++ b/src/main/res/drawable/ic_check.xml @@ -0,0 +1,9 @@ + + + diff --git a/src/main/res/drawable/ic_chevron_right.xml b/src/main/res/drawable/ic_chevron_right.xml new file mode 100644 index 0000000..a8439e8 --- /dev/null +++ b/src/main/res/drawable/ic_chevron_right.xml @@ -0,0 +1,9 @@ + + + diff --git a/src/main/res/drawable/ic_close.xml b/src/main/res/drawable/ic_close.xml new file mode 100644 index 0000000..b018863 --- /dev/null +++ b/src/main/res/drawable/ic_close.xml @@ -0,0 +1,9 @@ + + + diff --git a/src/main/res/drawable/ic_edit.xml b/src/main/res/drawable/ic_edit.xml new file mode 100644 index 0000000..7f89e86 --- /dev/null +++ b/src/main/res/drawable/ic_edit.xml @@ -0,0 +1,9 @@ + + + diff --git a/src/main/res/drawable/ic_focus.xml b/src/main/res/drawable/ic_focus.xml new file mode 100644 index 0000000..f8f9dc9 --- /dev/null +++ b/src/main/res/drawable/ic_focus.xml @@ -0,0 +1,9 @@ + + + diff --git a/src/main/res/drawable/ic_launcher_bg.xml b/src/main/res/drawable/ic_launcher_bg.xml new file mode 100644 index 0000000..e6e078b --- /dev/null +++ b/src/main/res/drawable/ic_launcher_bg.xml @@ -0,0 +1,7 @@ + + + + diff --git a/src/main/res/drawable/ic_launcher_fg.xml b/src/main/res/drawable/ic_launcher_fg.xml new file mode 100644 index 0000000..b5d2af0 --- /dev/null +++ b/src/main/res/drawable/ic_launcher_fg.xml @@ -0,0 +1,26 @@ + + + + + + + diff --git a/src/main/res/drawable/ic_more.xml b/src/main/res/drawable/ic_more.xml new file mode 100644 index 0000000..3ca18a0 --- /dev/null +++ b/src/main/res/drawable/ic_more.xml @@ -0,0 +1,9 @@ + + + diff --git a/src/main/res/drawable/ic_notif_blank.xml b/src/main/res/drawable/ic_notif_blank.xml new file mode 100644 index 0000000..4d64c93 --- /dev/null +++ b/src/main/res/drawable/ic_notif_blank.xml @@ -0,0 +1,12 @@ + + + + + diff --git a/src/main/res/drawable/ic_pause.xml b/src/main/res/drawable/ic_pause.xml new file mode 100644 index 0000000..2013ecf --- /dev/null +++ b/src/main/res/drawable/ic_pause.xml @@ -0,0 +1,9 @@ + + + diff --git a/src/main/res/drawable/ic_play.xml b/src/main/res/drawable/ic_play.xml new file mode 100644 index 0000000..425a4e2 --- /dev/null +++ b/src/main/res/drawable/ic_play.xml @@ -0,0 +1,9 @@ + + + diff --git a/src/main/res/drawable/ic_plus.xml b/src/main/res/drawable/ic_plus.xml new file mode 100644 index 0000000..36a3e81 --- /dev/null +++ b/src/main/res/drawable/ic_plus.xml @@ -0,0 +1,9 @@ + + + diff --git a/src/main/res/drawable/ic_project.xml b/src/main/res/drawable/ic_project.xml new file mode 100644 index 0000000..12b05c1 --- /dev/null +++ b/src/main/res/drawable/ic_project.xml @@ -0,0 +1,9 @@ + + + diff --git a/src/main/res/drawable/ic_refresh.xml b/src/main/res/drawable/ic_refresh.xml new file mode 100644 index 0000000..605bbc2 --- /dev/null +++ b/src/main/res/drawable/ic_refresh.xml @@ -0,0 +1,9 @@ + + + diff --git a/src/main/res/drawable/ic_settings.xml b/src/main/res/drawable/ic_settings.xml new file mode 100644 index 0000000..90a29b5 --- /dev/null +++ b/src/main/res/drawable/ic_settings.xml @@ -0,0 +1,9 @@ + + + diff --git a/src/main/res/drawable/ic_skip.xml b/src/main/res/drawable/ic_skip.xml new file mode 100644 index 0000000..5fd8cb7 --- /dev/null +++ b/src/main/res/drawable/ic_skip.xml @@ -0,0 +1,9 @@ + + + diff --git a/src/main/res/drawable/ic_stats.xml b/src/main/res/drawable/ic_stats.xml new file mode 100644 index 0000000..4cc3468 --- /dev/null +++ b/src/main/res/drawable/ic_stats.xml @@ -0,0 +1,9 @@ + + + diff --git a/src/main/res/drawable/ic_stop.xml b/src/main/res/drawable/ic_stop.xml new file mode 100644 index 0000000..1d77540 --- /dev/null +++ b/src/main/res/drawable/ic_stop.xml @@ -0,0 +1,9 @@ + + + diff --git a/src/main/res/drawable/ic_task.xml b/src/main/res/drawable/ic_task.xml new file mode 100644 index 0000000..5835425 --- /dev/null +++ b/src/main/res/drawable/ic_task.xml @@ -0,0 +1,9 @@ + + + diff --git a/src/main/res/drawable/ic_trash.xml b/src/main/res/drawable/ic_trash.xml new file mode 100644 index 0000000..150a8d2 --- /dev/null +++ b/src/main/res/drawable/ic_trash.xml @@ -0,0 +1,9 @@ + + + diff --git a/src/main/res/drawable/progress_line.xml b/src/main/res/drawable/progress_line.xml new file mode 100644 index 0000000..4b083b7 --- /dev/null +++ b/src/main/res/drawable/progress_line.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + diff --git a/src/main/res/layout/activity_main.xml b/src/main/res/layout/activity_main.xml new file mode 100644 index 0000000..24d2fe2 --- /dev/null +++ b/src/main/res/layout/activity_main.xml @@ -0,0 +1,27 @@ + + + + + + + + + diff --git a/src/main/res/layout/fragment_focus.xml b/src/main/res/layout/fragment_focus.xml new file mode 100644 index 0000000..732d43c --- /dev/null +++ b/src/main/res/layout/fragment_focus.xml @@ -0,0 +1,225 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/res/layout/fragment_projects.xml b/src/main/res/layout/fragment_projects.xml new file mode 100644 index 0000000..d420617 --- /dev/null +++ b/src/main/res/layout/fragment_projects.xml @@ -0,0 +1,87 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/res/layout/fragment_settings.xml b/src/main/res/layout/fragment_settings.xml new file mode 100644 index 0000000..668e591 --- /dev/null +++ b/src/main/res/layout/fragment_settings.xml @@ -0,0 +1,33 @@ + + + + + + + + + + diff --git a/src/main/res/layout/fragment_stats.xml b/src/main/res/layout/fragment_stats.xml new file mode 100644 index 0000000..698bfd7 --- /dev/null +++ b/src/main/res/layout/fragment_stats.xml @@ -0,0 +1,393 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/res/layout/fragment_tasks.xml b/src/main/res/layout/fragment_tasks.xml new file mode 100644 index 0000000..3d5f8ae --- /dev/null +++ b/src/main/res/layout/fragment_tasks.xml @@ -0,0 +1,88 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/res/layout/item_footer.xml b/src/main/res/layout/item_footer.xml new file mode 100644 index 0000000..3c6e224 --- /dev/null +++ b/src/main/res/layout/item_footer.xml @@ -0,0 +1,19 @@ + + + + + diff --git a/src/main/res/layout/item_project.xml b/src/main/res/layout/item_project.xml new file mode 100644 index 0000000..62930f7 --- /dev/null +++ b/src/main/res/layout/item_project.xml @@ -0,0 +1,66 @@ + + + + + + + + + + + + + + + + diff --git a/src/main/res/layout/item_task.xml b/src/main/res/layout/item_task.xml new file mode 100644 index 0000000..343778b --- /dev/null +++ b/src/main/res/layout/item_task.xml @@ -0,0 +1,78 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/res/layout/sheet_project.xml b/src/main/res/layout/sheet_project.xml new file mode 100644 index 0000000..a9b6ceb --- /dev/null +++ b/src/main/res/layout/sheet_project.xml @@ -0,0 +1,96 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/res/layout/sheet_task.xml b/src/main/res/layout/sheet_task.xml new file mode 100644 index 0000000..0990246 --- /dev/null +++ b/src/main/res/layout/sheet_task.xml @@ -0,0 +1,308 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 0000000..4fefd60 --- /dev/null +++ b/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/src/main/res/mipmap-anydpi/ic_launcher.xml b/src/main/res/mipmap-anydpi/ic_launcher.xml new file mode 100644 index 0000000..9b848dd --- /dev/null +++ b/src/main/res/mipmap-anydpi/ic_launcher.xml @@ -0,0 +1,26 @@ + + + + + + + diff --git a/src/main/res/values-night/colors.xml b/src/main/res/values-night/colors.xml new file mode 100644 index 0000000..be28793 --- /dev/null +++ b/src/main/res/values-night/colors.xml @@ -0,0 +1,43 @@ + + + #E08A72 + #C75B45 + #33E08A72 + #1A120E + + #7FBFAE + #5FA391 + + #E8705F + #6FBF8F + + #121316 + #1B1D21 + #232629 + #2C3035 + + #EDE9E3 + #F7F4EF + #A9A39A + #8C867D + + #2A2D31 + #232629 + #34383E + + #2B2F34 + #262A2E + #33383E + + #1FFFFFFF + #33FFFFFF + + #26292D + #4A2E27 + #6E4034 + #96523F + #C47056 + + #2A2D33 + #191B1F + diff --git a/src/main/res/values-night/themes.xml b/src/main/res/values-night/themes.xml new file mode 100644 index 0000000..339d2b9 --- /dev/null +++ b/src/main/res/values-night/themes.xml @@ -0,0 +1,18 @@ + + + + diff --git a/src/main/res/values/colors.xml b/src/main/res/values/colors.xml new file mode 100644 index 0000000..819e091 --- /dev/null +++ b/src/main/res/values/colors.xml @@ -0,0 +1,49 @@ + + + + #C75B45 + #A6462F + #1FC75B45 + #FFFFFF + + + #3F7F6E + #2F6455 + + #C0392B + #2E7D51 + + #F6F3EE + #FFFFFF + #F1ECE4 + #E9E2D6 + + #1E1B18 + #131110 + #635C52 + #6F685C + + #E7E1D6 + #F4F0E9 + #DDD5C7 + + #EDE6DA + #EBE5DA + #FFFFFF + + #14000000 + #33FFFFFF + + + #EDE7DB + #F2C9B9 + #E39B80 + #D4745B + #B44B36 + + #2A2D33 + #191B1F + diff --git a/src/main/res/values/sheet.xml b/src/main/res/values/sheet.xml new file mode 100644 index 0000000..0743b54 --- /dev/null +++ b/src/main/res/values/sheet.xml @@ -0,0 +1,20 @@ + + + + + + + diff --git a/src/main/res/values/strings.xml b/src/main/res/values/strings.xml new file mode 100644 index 0000000..c894976 --- /dev/null +++ b/src/main/res/values/strings.xml @@ -0,0 +1,163 @@ + + + 专注盒子 + + 首页 + 任务 + 项目 + 统计 + 设置 + + 专注 + 休息 + 长休息 + + 开始专注 + 开始休息 + 开始计时 + 暂停 + 继续 + 重置 + 跳过 + 结束本轮 + 完成 + + 倒计时 + 正计时 + 上下滑动圆环调整时长 · 左右滑动切换正计时 + 左右滑动切回倒计时 + 计时中不能切换,先结束本轮 + + 当前任务 + 未选择任务 · 直接开始也可以 + 选择任务 + 还没有待办任务,先去「任务」新建一个 + 今天第 %1$d 个番茄 + + 任务 + %1$d 个待办 + %1$d 个今日任务 + %1$d 个已完成 + 新建任务 + 全部 + 今日 + 已完成 + 显示已完成 + 隐藏已完成 + 待完成 + 已完成 + 还没有任务\n点右上角 + 记下第一件要做的事 + 今天没有到期的任务\n切到「全部」可以看其他安排 + 还没有已完成的任务 + 要做什么? + 备注(可选) + 优先级 + 低 + 中 + 高 + 专注时长 + %1$d 分钟 + 重复 + 不重复 + 天 + 周 + 月 + 天 + 周 + 月 + 重复间隔 + 预估番茄 + 截止日期 + 不设截止 + 清除 + 所属项目 + 删除 + 保存 + 取消 + 编辑 + 归档 + 取消归档 + 已归档 + 删除这个任务?专注记录会保留。 + 删除项目「%1$s」?项目下的任务会移到收件箱。 + + 项目 + %1$d 个项目 · %2$d 个待办 + 新建项目 + 项目名称 + 收件箱 + 颜色 + 显示已归档 + 还没有项目\n按用途分组,统计里就能看到时间花在哪 + + 统计 + 本周 + 本月 + 全部 + 今日 + 专注时长 + 番茄数 + 完成任务 + 今日目标 %1$d%% + 专注趋势 + 打卡热力图 + 项目分布 + 任务分布 + 任务占比 + 还有 %1$d 个项目 + 还有 %1$d 个任务 + 累计 + 连续打卡 + %1$d 天 + 总专注 + 总番茄 + 完成任务 + 暂无数据 + 天 + 次 + + 设置 + 时长 + 自动衔接 + 提醒 + 目标 + 外观 + 数据 + 专注 + 短休息 + 长休息 + 长休息间隔 + 专注结束自动开始休息 + 休息结束自动开始下一轮 + 结束提示音 + 振动 + 计时时保持屏幕常亮 + 每日目标 + 深色模式 + 跟随系统 + 浅色 + 深色 + 清空所有数据 + 项目、任务、专注记录全部删除,不可恢复 + 确定清空全部数据?此操作不可恢复。 + 版本 %1$s · 自用版 + %1$d 分钟 + %1$d 轮 + + 专注计时 + 计时进行中的常驻通知 + 专注中 + 休息中 + 已暂停 + 暂停 + 继续 + 结束 + 本轮完成 + 休息一下,%1$d 分钟后继续 + 休息结束 + 准备好就开始下一轮 + + 请在系统设置里允许通知,否则计时看不到状态 + 已完成 + 已保存 + diff --git a/src/main/res/values/themes.xml b/src/main/res/values/themes.xml new file mode 100644 index 0000000..7aa414c --- /dev/null +++ b/src/main/res/values/themes.xml @@ -0,0 +1,76 @@ + + + + + + + + + + + + + + + + + + + + +