Compare commits

..

9 Commits

Author SHA1 Message Date
Misaki bfab0579a7 feat: add completed task and project summary
- Add completed timeblock queries and completed project aggregation\n- Add desktop completed summary dialog with range filters, stats, and streak\n- Add medal entry point in the today panel\n- Add Android completed summary menu with local statistics\n- Rebuild AppImage and update validation docs/screenshots
2026-11-10 16:45:54 +08:00
Misaki 35cabb37b2 feat: add long-term projects with AI creation
- Add project model, schema v4, sync triggers, and server support\n- Add project panel, deadline countdown, manual create/edit/complete/delete\n- Parse AI project operations and show them in the proposal diff\n- Sync projects to Android and display them read-only\n- Rebuild AppImage and update validation docs and screenshots
2026-10-31 15:52:48 +08:00
Misaki 9dae003b93 build: add Linux AppImage packaging
- Add reproducible linuxdeploy/appimagetool packaging script\n- Bundle Qt runtime, xcb/Wayland plugins, SQLite, TLS, and fcitx5 plugin\n- Add desktop icon, metadata, and direct-run AppImage\n- Fix release-mode scheduler warning and document Linux packaging
2026-10-26 21:57:08 +08:00
Misaki f68b4f7c6f fix: sync completion across clients and restore Windows build
- Guard SystemTray DBus members correctly for MinGW builds\n- Let remote done override local scheduled/in-progress despite clock skew\n- Add Android start/lead reminders and lead-minute setting\n- Use expedited WorkManager for local Android changes\n- Add desktop/Android completion and reminder validation
2026-10-26 21:30:58 +08:00
Misaki 795f9730f8 feat: add desktop start and native reminders
- Notify at schedule start and optionally N minutes before\n- Add reminder lead setting and TOML persistence\n- Use Linux DBus native notifications with action handling\n- Focus the matching block when a notification is clicked\n- Keep overdue reminders and update validation docs/screenshots
2026-10-26 21:16:07 +08:00
Misaki 121e66d527 feat(android): add reminders and background sync
- Add local overdue reminders with notification channel and tap-to-date\n- Extract shared sync engine for foreground and WorkManager sync\n- Schedule 15-minute sync/reminder work and restore tasks after boot\n- Request notification permission and document Android background limits
2026-10-26 21:02:55 +08:00
Misaki 082c1229f9 feat: add Android sync client
- Add Kotlin/Material 3 Android project with SQLite outbox and LWW\n- Implement registration, push/pull, WebSocket notifications, and settings\n- Add schedule list, date navigation, create/edit/delete, and completion\n- Add JVM LWW/time tests and build a debug APK\n- Document Android v1 scope and validation
2026-10-26 20:43:34 +08:00
Misaki c749d642cf feat: add search, recurring schedules, and Windows packaging
- Add title/description search with Ctrl+F and a result dialog\n- Support daily/weekly/monthly recurring blocks with conflict skipping\n- Add CPack NSIS packaging, MinGW release preset, and deploy script\n- Add window/view/list/dialog fade animations\n- Document multi-device conflict behavior and update validation screenshots
2026-10-26 19:53:56 +08:00
Misaki 9bafa71667 feat: add energy-aware scheduling and daily insights
- Learn a per-device 7x24 energy profile from completed tasks\n- Constrain high-energy scheduling and expose energy peaks to AI\n- Add ghost-time overlays, daily review dialog, and proactive suggestions\n- Cover energy/insights logic and local OpenAI-compatible providers with tests\n- Update validation docs and screenshots
2026-10-26 19:08:09 +08:00
166 changed files with 9940 additions and 83 deletions
+5
View File
@@ -13,3 +13,8 @@ server/bin/
config.toml
config.toml.bak
server/data/
android/.gradle/
android/local.properties
android/app/build/
android/build/
dist/
+42
View File
@@ -30,3 +30,45 @@ if(GO_EXECUTABLE)
endif()
add_subdirectory(client)
install(FILES README.md DESTINATION .)
install(FILES client/3rd/ElaWidgetTools/LICENSE
DESTINATION licenses RENAME ElaWidgetTools-LICENSE)
install(FILES client/3rd/tomlplusplus/LICENSE
DESTINATION licenses RENAME tomlplusplus-LICENSE)
if(WIN32)
if(NOT SCHEDULE_WINDEPLOYQT)
message(FATAL_ERROR "windeployqt was not configured; check the Qt/MinGW preset paths")
endif()
set(_compiler_runtime_arg "")
if(MSVC)
set(_compiler_runtime_arg "--compiler-runtime")
endif()
install(CODE "
set(_stage \"\$ENV{DESTDIR}\${CMAKE_INSTALL_PREFIX}\")
execute_process(
COMMAND \"${SCHEDULE_WINDEPLOYQT}\" ${_compiler_runtime_arg} --dir \"\${_stage}\" \"\${_stage}/Schedule.exe\"
RESULT_VARIABLE _deploy_result
)
if(NOT _deploy_result EQUAL 0)
message(FATAL_ERROR \"windeployqt failed during install: \${_deploy_result}\")
endif()
")
set(CPACK_GENERATOR "NSIS")
set(CPACK_PACKAGE_NAME "Schedule")
set(CPACK_PACKAGE_VENDOR "Misaki")
set(CPACK_PACKAGE_VERSION "${PROJECT_VERSION}")
set(CPACK_PACKAGE_INSTALL_DIRECTORY "Schedule")
set(CPACK_PACKAGE_EXECUTABLES "Schedule;AI 日程")
set(CPACK_CREATE_DESKTOP_LINKS "Schedule")
set(CPACK_NSIS_DISPLAY_NAME "AI 日程")
set(CPACK_NSIS_PACKAGE_NAME "AI 日程")
set(CPACK_NSIS_ENABLE_UNINSTALL_BEFORE_INSTALL ON)
set(CPACK_NSIS_MODIFY_PATH OFF)
set(CPACK_NSIS_INSTALLED_ICON_NAME "Schedule.exe")
set(CPACK_NSIS_MUI_FINISHPAGE_RUN "Schedule.exe")
set(CPACK_RESOURCE_FILE_README "${CMAKE_SOURCE_DIR}/README.md")
include(CPack)
endif()
+21
View File
@@ -65,6 +65,18 @@
"deprecated": false
}
},
{
"name": "windows-mingw-release",
"displayName": "Windows MinGW-w64 Release",
"inherits": "windows-mingw",
"binaryDir": "${sourceDir}/build/windows-mingw-release",
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Release"
},
"warnings": {
"deprecated": false
}
},
{
"name": "macos-clang",
"displayName": "macOS Clang (edit Qt path in preset)",
@@ -96,6 +108,10 @@
"name": "windows-mingw",
"configurePreset": "windows-mingw"
},
{
"name": "windows-mingw-release",
"configurePreset": "windows-mingw-release"
},
{
"name": "macos-clang",
"configurePreset": "macos-clang"
@@ -143,6 +159,11 @@
"QT_QPA_PLATFORM": "offscreen",
"PATH": "C:/Qt/6.6.3/mingw_64/bin;C:/Qt/Tools/mingw1120_64/bin;$penv{PATH}"
}
},
{
"name": "windows-mingw-release",
"inherits": "windows-mingw",
"configurePreset": "windows-mingw-release"
}
]
}
+152 -7
View File
@@ -2,7 +2,7 @@
细粒度个人日程 + AI 自然语言排程 + 自部署多设备同步。
当前进度:**阶段 0 + 阶段 1 + 界面重构 + TOML 配置 + AI 日程闭环 + AI 增强(更新/删除/涟漪/拆分)+ 多设备同步**。
当前进度:**阶段 0–4 + 搜索 / 重复日程 / 长期项目 / 完成汇总 / Windows 安装包 / Linux AppImage / 界面动画 + 桌面日程提醒 + Android 同步客户端 v1**。
本地模型 50 条指令回归已完成:完整 49/50(98%),失败项 #42 单独复测通过。
详细计划见 [`docs/PLAN.md`](docs/PLAN.md),验证记录见 [`docs/validation/`](docs/validation/)。
@@ -11,7 +11,11 @@
- **紧凑主窗口**(默认启动):AI 助手 + 今日任务,顶部可打开详细日程或设置。
- **详细日程窗口**:日 / 月 / 年三种视图、选中日期任务面板、新建/编辑/删除、设置;顶部房屋按钮或关闭窗口回到紧凑窗口。
- **系统托盘**:关闭紧凑窗口时最小化到托盘;托盘可显示主窗口、新建日程、退出。
- **设置**:主题(跟随系统/浅色/深色)、ElaMica 云母效果、AI 接口地址/模型/API Key、同步服务地址/开关。
- **智能增强**:今日任务面板显示主动建议;日视图绘制幽灵时间;提供每日复盘对话框。
- **搜索与重复**:详细日程支持标题/说明搜索(`Ctrl+F`);新建日程可设置每天/每周/每月重复。
- **长期项目**:跨多天的模糊截止目标独立显示,可手工创建,也可由 AI 从自然语言中识别创建。
- **轻量动画**:窗口淡入、视图切换淡入、任务列表刷新与 Diff 卡片淡入。
- **设置**:主题(跟随系统/浅色/深色)、ElaMica 云母效果、AI 接口地址/模型/API Key、日程提前提醒分钟数、同步服务地址/开关。
> 云母效果使用 ElaWidgetTools 的 `ElaMica` 跨平台模拟背景(内置模糊基底图),
> 在 Linux 下不是系统级窗口模糊;后续可在 Windows 上扩展系统 Mica。
@@ -35,10 +39,92 @@
- Word:docx 需要 `unzip`,doc 需要 `catdoc`
- 图片:以 data URL 发送,需要模型支持视觉输入
排程由本地确定性 `SchedulerEngine` 完成:避开已确认日程、优先用户指定时间、回退到 08:00–22:00、按 15 分钟粒度、遵守 deadline。
排程由本地确定性 `SchedulerEngine` 完成:避开已确认日程、优先用户指定时间、回退到 08:00–22:00、按 15 分钟粒度、遵守 deadline,并按学习到的精力曲线约束高精力任务。
> 隐私提示:拖入文件的文本/图片会发送到你配置的 AI 服务。若需完全离线,请配置本地 OpenAI 兼容模型。
## 精力、幽灵时间与复盘
- 客户端从**已完成且带 `energy_req` 的日程**学习 7×24 精力档案(0 低 / 1 中 / 2 高);撤销完成后会回退。
- AI 收到精力高峰摘要;`SchedulerEngine` 会为高精力任务寻找高精力时段,而不是只找最早空档。
- **幽灵时间**:日视图以半透明虚线块显示 08:00–22:00 内的可用空档;复盘对话框列出当天所有 30 分钟以上空档。
- **主动建议**:今日任务面板顶部显示「处理超时日程 / 发现幽灵时间 / 做一次今日复盘」等确定性建议。
- **每日复盘**:点击今日任务标题旁的复盘按钮或按 `Ctrl+R`,查看完成率、专注时长、精力高峰、待办与幽灵时间。
精力档案按设备本地保存,不参与多设备变更流;不同设备的作息差异不会互相覆盖。
## 搜索与重复日程
### 搜索
- 详细日程顶部搜索框输入标题或说明,回车打开结果;`Ctrl+F` 从任何窗口打开。
- 查询覆盖任务标题、说明和来源引用;结果按离当前时间最近排序,最多 100 条。
- 点击或回车选择结果会跳到对应日期并定位到日程块。
### 重复日程
- 新建日程时可选择每天、每周或每月重复,并设置重复结束日期。
- 重复会物化为共享同一任务的时间块,最多 1 年 / 200 次;与现有日程冲突的日期会自动跳过。
- 重复规则元数据保存在本机 `recurrence` 表;具体时间块照常参与多设备同步。其他设备能看到所有已物化的日程。
- 编辑某个重复日程的标题会修改共享任务标题(影响该系列);删除单个块只删除该次。
## 桌面日程提醒
桌面端现在提供三种系统通知:
- **日程开始**:时间块到达开始时间时通知(App 需运行,轮询间隔 20 秒)。
- **提前提醒**:在开始前 N 分钟再通知一次;N 可在设置中选择 0(仅开始时)、5、10、15、30、60 分钟。
- **日程超时**:结束时间后仍未完成时通知(原有行为)。
通知后端:
- Linux 使用 `org.freedesktop.Notifications` DBus 原生通知,并在支持动作的桌面环境提供「打开日程」按钮。
- Windows/macOS 使用 `QSystemTrayIcon` 的系统托盘通知。
- 点击通知会打开详细日程并定位到对应时间块;Linux DBus 点击走 `ActionInvoked`,Windows/macOS 走 `messageClicked`。
限制:应用必须仍在运行(可最小化到托盘);没有开机自启;轮询不是精确闹钟;同一时间块提醒状态只保存在内存中,重启后可能再次提醒。
## 长期项目
长期项目是独立于细碎时间块的高层目标,例如「一个月内完成飞行控制器项目」。
- 新建日程区域旁的文件夹按钮可手工创建项目:标题、说明、模糊截止日期。
- 今日任务面板顶部显示「长期项目」区,展示剩余天数/逾期状态;点击编辑,菜单可标记完成或删除。
- AI 会把跨多天、数周或数月的目标识别为 `project`,在 Diff 卡片中显示为「长期项目」,接受后写入项目表,不会占用某一天的时间块。
- 长期项目通过同步变更流同步到其他桌面端;Android 当前只展示,不提供创建/编辑。
- 项目截止日期是日期级模糊值,不参与精力曲线、幽灵时间或自动排程。
## 已完成汇总
今日任务面板标题旁的奖牌按钮打开「已完成汇总」:
- 可选择本周 / 本月 / 全部范围。
- 统计已完成短期任务数、累计专注时长、已完成长期项目数、连续完成天数。
- 分别列出已完成的短期任务和长期项目,带完成时间和截止日期。
- Android 菜单也提供「已完成汇总」,展示同类统计和最近完成记录。
## 同步冲突行为
同步是后台无感进行的:不弹冲突对话框,失败自动重试,状态只显示在顶部标签。
- **同一任务/时间块在不同设备同时编辑**:按 `updated_at` 做 LWW,时间戳更新的版本获胜;删除墓碑在等时间戳时优先。
- **完成状态**:只要有设备把时间块标记为 done,其他设备会接受该完成状态,即使远端时间戳较旧(避免手机/PC 时钟偏差导致完成状态不同步);取消完成仍按 LWW。
- **不同日程被安排在同一时间**:它们是两个独立实体,都会保留,日视图以重叠列展示;系统不会自动移动或删除任何一方。
- **重复日程**:物化后的时间块按普通日程同步;重复规则本身不参与变更流。
- **服务端**只保存有序变更流,不做语义合并;最终一致性由客户端 LWW 保证。
- 如果希望“同一时间只保留一个日程”,需要后续在客户端增加冲突策略或自动涟漪;当前策略是保留双方、避免静默丢数据。
### 本地模型
本地模型通过 **OpenAI 兼容端点**接入,与云端使用同一套 Provider:
| 服务 | 接口地址示例 | API Key |
|---|---|---|
| Ollama | `http://127.0.0.1:11434/v1` | 留空 |
| LM Studio | `http://127.0.0.1:1234/v1` | 留空 |
| vLLM / llama.cpp / 其他 | 对应 `/v1` 地址 | 按服务要求 |
在设置中填写接口地址和模型名即可;本地服务不要求 API Key 时留空。模型需要支持流式 SSE 和 OpenAI Chat Completions 格式。
### Linux 中文输入法(fcitx5)
自定义 Qt 安装通常不带 fcitx5 的 Qt6 platform input context 插件;系统包
@@ -79,6 +165,24 @@ Windows/macOS 使用 Qt 原生输入法支持,不需要该插件。
客户端使用 SQLite outbox 捕获本地变更,按服务端 `seq` 增量拉取;冲突按 `updated_at` 做 LWW,删除墓碑优先于等时间戳的更新。断线后保留 outbox 并自动重试,WebSocket 断开时退化为定时轮询。同步协议与部署说明见 [`server/README.md`](server/README.md),验证记录见 [`docs/validation/phase-3.md`](docs/validation/phase-3.md)。
## Android 客户端
`android/` 是阶段 5.0 的 Kotlin/Android 同步客户端,复用阶段 3 的 REST/WebSocket 协议:
- 今日日程列表、完成状态、编辑、长按删除、新建。
- SQLite outbox、LWW、WebSocket + 15 秒轮询、设备注册。
- 开始/提前 N 分钟/结束未完成本地通知;WorkManager 每 15 分钟后台同步;开机重建任务。
- 桌面创建的长期项目会同步到 Android 并只读展示。
- 暂不含 AI 对话/附件、精力曲线、复盘。
```bash
cd android
./gradlew :app:assembleDebug
adb install -r app/build/outputs/apk/debug/app-debug.apk
```
首次使用需安装 Android SDK 34 + Build-Tools 34,并在 App 设置中填写服务地址(模拟器用 `http://10.0.2.2:8787`,真机用电脑局域网 IP)。详细说明见 [`android/README.md`](android/README.md),验证记录见 [`docs/validation/phase-5.md`](docs/validation/phase-5.md)。
## 构建
依赖:CMake ≥ 3.24、Ninja、Qt 6.5+(含 Qt WebSockets)、GCC/Clang(C++20);构建同步服务端需要 Go 1.23+,Docker 部署可选。
@@ -143,6 +247,38 @@ cmake --build --preset linux-gcc
`windows-msvc` 与 `macos-clang` 也采用相同的做法:在对应 preset 中直接填写
`CMAKE_PREFIX_PATH`,不使用环境变量或自动搜索。
### Windows 安装包
安装 [NSIS](https://nsis.sourceforge.io/) 并将 `makensis.exe` 加入 `PATH` 后,在仓库根目录运行:
```powershell
.\scripts\package-windows.ps1
```
脚本会使用 `windows-mingw-release` preset 构建 Release、运行测试,然后执行 CPack:
- 安装 `build/windows-mingw-release/Schedule-0.1.0-win64.exe`;
- 安装过程会自动运行 `windeployqt`,收集 Qt DLL、插件和 MinGW 运行时;
- 未安装 NSIS 时会退化为 `Schedule-*.zip` 便携包。
安装包包含开始菜单项与桌面快捷方式,卸载信息写入 Windows 应用列表。
### Linux AppImage
可生成免安装的 AppImage:
```bash
./scripts/package-linux-appimage.sh
chmod +x dist/AI-Schedule-0.1.0-x86_64.AppImage
./dist/AI-Schedule-0.1.0-x86_64.AppImage
```
- 产物:`dist/AI-Schedule-0.1.0-x86_64.AppImage`(约 34 MB)。
- 已打包 Qt 库、xcb/Wayland 平台插件、SQLite 驱动、TLS 和 fcitx5 输入法插件。
- 无 FUSE 环境使用:`./dist/AI-Schedule-0.1.0-x86_64.AppImage --appimage-extract-and-run`。
- 可用 `QT_ROOT` 覆盖 Qt 路径,`TOOLS_DIR` 指定已下载的 linuxdeploy/appimagetool。
- 详细验证见 [`docs/validation/phase-4-3.md`](docs/validation/phase-4-3.md)。
### Windows 多设备联调
1. 在服务端机器启动 `go run ./cmd/server`(或 Docker),设置随机 `SYNC_TOKEN_PEPPER`。
@@ -162,9 +298,11 @@ cmake --build --preset linux-gcc
ctest --preset linux-gcc
```
当前自动化测试(11 组):存储/服务、网格与详细窗口、紧凑窗口、TOML 配置、SchedulerEngine、
AI 编排(15 个用例:流式、修复、更新/删除、涟漪、拆分、冲突保护、多轮历史、文件、删除兜底、无 diff 重试)、
OpenAI 兼容 Provider(本地假 SSE 服务)、AI 对话到接受落库的 UI 全链路、Go 服务端单元/接口/并发测试、双客户端同步集成(含离线重连)。
当前自动化测试(12 组):存储/服务、网格与详细窗口、紧凑窗口、TOML 配置、SchedulerEngine、
精力档案 / 幽灵时间 / 每日复盘、搜索 / 重复日程、AI 编排(15 个用例:流式、修复、更新/删除、涟漪、拆分、冲突保护、多轮历史、文件、删除兜底、无 diff 重试)、
OpenAI 兼容 Provider(本地假 SSE 服务,含无 API Key 的本地模型)、AI 对话到接受落库的 UI 全链路、Go 服务端单元/接口/并发测试、双客户端同步集成(含离线重连)。
Android:`cd android && ./gradlew :app:testDebugUnitTest`,当前 LWW / 时间工具 / 完成合并共 8 个 JVM 测试通过;APK 构建见 [`android/README.md`](android/README.md)。
本地模型回归(50 条真实中文指令):
@@ -178,7 +316,7 @@ cmake --build --preset linux-gcc --target ai_regression
## 数据与配置
- 数据库:`~/.local/share/Misaki/Schedule/schedule.db`(SQLite WAL)。
- 数据库:`~/.local/share/Misaki/Schedule/schedule.db`(SQLite WAL,包含精力档案;精力档案不参与同步)。
- 配置文件:`~/.config/Misaki/Schedule/config.toml`(TOML,权限 0600)。
- 旧版 `~/.config/Misaki/Schedule.conf` 会在首次启动时自动迁移,原文件保留作备份。
@@ -195,6 +333,9 @@ temperature = 0.2
enabled = false
server_url = "http://127.0.0.1:8787"
token = ""
[reminders]
lead_minutes = 10
```
AI 接口地址、模型、API Key 与同步服务地址/开关可直接在设置对话框中修改。同步令牌由客户端在注册后自动写入,文件权限 0600。
@@ -210,6 +351,8 @@ AI 接口地址、模型、API Key 与同步服务地址/开关可直接在设
|---|---|
| `Ctrl+O` | 打开详细日程 |
| `Ctrl+,` | 打开设置 |
| `Ctrl+R` | 今日复盘 |
| `Ctrl+F` | 打开搜索 |
### 详细日程窗口
@@ -221,6 +364,8 @@ AI 接口地址、模型、API Key 与同步服务地址/开关可直接在设
| `Alt+←/→` | 上一段 / 下一段(日/月/年自适应) |
| `Ctrl+T` | 回到今天 |
| `Ctrl+,` | 打开设置 |
| `Ctrl+R` | 今日复盘 |
| `Ctrl+F` | 搜索日程 |
| `Ctrl` + 滚轮 | 时间轴缩放(日视图) |
| `Delete` | 删除选中日程(日视图) |
| `Enter` | 编辑选中日程(日视图) |
+7
View File
@@ -0,0 +1,7 @@
.gradle/
local.properties
build/
app/build/
*.apk
*.aab
.idea/
+70
View File
@@ -0,0 +1,70 @@
# Schedule Android
阶段 5.0 的 Android 同步客户端。使用 Kotlin + 原生 View,直接复用阶段 3 的 REST/WebSocket 协议,不依赖 Qt。
## 功能
- 今日日程列表:按日期前后切换、完成状态、编辑、长按删除。
- 本地 SQLite:task / timeblock / outbox / sync_state。
- 同步:设备注册、outbox 推送、增量拉取、LWW、WebSocket 通知、定时轮询。
- 长期项目:接收桌面端项目,在今日列表上方只读展示标题和截止倒计时。
- 已完成汇总:右上角菜单查看短期任务数、专注时长、长期项目数和最近完成记录。
- 提醒:日程开始、提前 N 分钟、结束后未完成都会发本地通知;通知点击回到对应日期。
- 后台:WorkManager 每 15 分钟同步一次;开机接收 `BOOT_COMPLETED` 重新登记任务。
- 设置:同步服务地址与启用开关;不支持 AI 对话和附件提取(桌面端功能)。
## 构建
要求:JDK 17+、Android SDK Platform 34 + Build-Tools 34。
```bash
cd android
# 首次使用 Android Studio 打开项目会自动生成 local.properties;
# 命令行可手动创建:
printf 'sdk.dir=/path/to/Android/Sdk\n' > local.properties
./gradlew :app:assembleDebug
```
APK:`android/app/build/outputs/apk/debug/app-debug.apk`。
安装到手机(开启 USB 调试):
```bash
adb install -r app/build/outputs/apk/debug/app-debug.apk
```
单元测试:
```bash
./gradlew :app:testDebugUnitTest
```
## 同步配置
1. 服务端监听 `0.0.0.0:8787`(或局域网可访问地址),手机与电脑同一局域网。
2. 打开 App → 右上角菜单 → 设置 → 填写 `http://<电脑局域网IP>:8787`,启用同步。
3. 首次启用自动注册设备;服务端需保存稳定的 `SYNC_TOKEN_PEPPER`。
4. Android 模拟器访问宿主机用 `http://10.0.2.2:8787`。
> App 允许明文 HTTP 以便局域网自部署测试;公网部署请使用 HTTPS 反向代理。
> Token 存在 SharedPreferences 中,明文保存;后续可接入 Android Keystore。
## 通知与后台同步
- 提醒使用 Android 本地通知,不依赖服务端推送/FCM。
- 通知类型:日程开始、提前 N 分钟(0/5/10/15/30/60)、结束后未完成。
- 设置页可选择提前分钟数;默认提前 10 分钟。
- Android 13+ 首次启动会请求通知权限;拒绝后提醒不显示,但同步不受影响。
- WorkManager 周期最小为 15 分钟;提醒可能延迟,开始提醒只覆盖开始后 20 分钟内。
- 开机广播会重新安排提醒与同步任务;不会自动打开 App 界面。
- 如需即时后台推送,需要后续接入 FCM 或常驻前台服务(会增加耗电/复杂度)。
> 部分国产 ROM 需要手动允许「自启动」「后台运行」或关闭电池优化,否则开机任务和周期同步可能被系统拦截。
## 当前限制
- 无 AI 对话 / 文件附件 / 精力曲线 / 重复日程创建 / 每日复盘;这些仍由桌面端提供。
- 长期项目目前只读展示,移动端暂不支持创建/编辑/完成操作。
- 提醒不是精确闹钟:WorkManager 周期任务可能延迟。
- 无 FCM 推送;App 被强制停止后,Android 不会执行周期任务,直到下次手动打开。
- 未在真机或模拟器上做交互验证;当前验证到 APK 构建、JVM 单元测试和 Manifest 检查。
+47
View File
@@ -0,0 +1,47 @@
plugins {
id("com.android.application")
id("org.jetbrains.kotlin.android")
}
android {
namespace = "com.misaki.schedule"
compileSdk = 34
defaultConfig {
applicationId = "com.misaki.schedule"
minSdk = 26
targetSdk = 34
versionCode = 1
versionName = "0.1.0"
}
buildTypes {
release {
isMinifyEnabled = false
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
kotlinOptions {
jvmTarget = "17"
}
}
dependencies {
implementation("androidx.core:core-ktx:1.13.1")
implementation("androidx.appcompat:appcompat:1.7.0")
implementation("com.google.android.material:material:1.12.0")
implementation("androidx.recyclerview:recyclerview:1.3.2")
implementation("androidx.activity:activity-ktx:1.9.1")
implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.8.4")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.8.1")
implementation("com.squareup.okhttp3:okhttp:4.12.0")
implementation("androidx.work:work-runtime-ktx:2.9.1")
testImplementation("junit:junit:4.13.2")
testImplementation("org.json:json:20240303")
}
+1
View File
@@ -0,0 +1 @@
# Keep OkHttp and coroutines defaults.
+35
View File
@@ -0,0 +1,35 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/Theme.Schedule"
android:usesCleartextTraffic="true">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name=".background.BootReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
</manifest>
@@ -0,0 +1,268 @@
package com.misaki.schedule
import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.view.View
import android.widget.ScrollView
import android.widget.TextView
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.appbar.MaterialToolbar
import com.google.android.material.button.MaterialButton
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.misaki.schedule.data.Prefs
import com.misaki.schedule.data.ScheduleItem
import com.misaki.schedule.data.ScheduleRepository
import com.misaki.schedule.background.BackgroundScheduler
import com.misaki.schedule.background.NotificationHelper
import com.misaki.schedule.data.TimeUtils
import com.misaki.schedule.sync.SyncManager
import com.misaki.schedule.ui.ProjectAdapter
import com.misaki.schedule.ui.ScheduleAdapter
import com.misaki.schedule.ui.ScheduleDialog
import com.misaki.schedule.ui.SettingsDialog
import kotlinx.coroutines.launch
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.util.Locale
class MainActivity : AppCompatActivity() {
private lateinit var repository: ScheduleRepository
private lateinit var prefs: Prefs
private lateinit var syncManager: SyncManager
private lateinit var adapter: ScheduleAdapter
private lateinit var projectAdapter: ProjectAdapter
private lateinit var list: RecyclerView
private lateinit var projectList: RecyclerView
private lateinit var projectHeader: TextView
private lateinit var emptyText: TextView
private lateinit var dateText: TextView
private lateinit var syncStatus: TextView
private var selectedDate: LocalDate = LocalDate.now()
private val dateFormatter = DateTimeFormatter.ofPattern("yyyy年M月d日 EEEE", Locale.CHINA)
private val notificationPermission = registerForActivityResult(
ActivityResultContracts.RequestPermission(),
) { }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
repository = ScheduleRepository(this)
prefs = Prefs(this)
syncManager = SyncManager(this, prefs, repository)
NotificationHelper.ensureChannel(this)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) !=
PackageManager.PERMISSION_GRANTED
) {
notificationPermission.launch(Manifest.permission.POST_NOTIFICATIONS)
}
BackgroundScheduler.update(this, prefs)
intent.getStringExtra("date")?.let { value ->
TimeUtils.dateOf(value)?.let { selectedDate = it }
}
list = findViewById(R.id.scheduleList)
projectList = findViewById(R.id.projectList)
projectHeader = findViewById(R.id.projectHeader)
emptyText = findViewById(R.id.emptyText)
dateText = findViewById(R.id.dateText)
syncStatus = findViewById(R.id.syncStatus)
adapter = ScheduleAdapter(
onEdit = { showScheduleDialog(it) },
onLongPress = { confirmDelete(it) },
onDoneChanged = { item, done ->
repository.setDone(item.block.id, done, prefs.deviceId)
syncManager.triggerSync()
BackgroundScheduler.syncNow(this)
},
)
list.layoutManager = LinearLayoutManager(this)
list.adapter = adapter
projectAdapter = ProjectAdapter()
projectList.layoutManager = LinearLayoutManager(this)
projectList.adapter = projectAdapter
findViewById<FloatingActionButton>(R.id.addButton).setOnClickListener {
val start = TimeUtils.defaultStart(selectedDate)
showScheduleDialog(null, start)
}
findViewById<MaterialButton>(R.id.todayButton).setOnClickListener {
selectedDate = LocalDate.now()
refresh()
}
findViewById<View>(R.id.previousDay).setOnClickListener {
selectedDate = selectedDate.minusDays(1)
refresh()
}
findViewById<View>(R.id.nextDay).setOnClickListener {
selectedDate = selectedDate.plusDays(1)
refresh()
}
val toolbar = findViewById<MaterialToolbar>(R.id.toolbar)
toolbar.setOnMenuItemClickListener { item ->
when (item.itemId) {
R.id.action_completed -> {
showCompletedSummary()
true
}
R.id.action_sync -> {
syncManager.reload()
true
}
R.id.action_settings -> {
SettingsDialog.show(this, prefs, syncManager)
true
}
else -> false
}
}
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
launch { repository.revision.collect { refresh() } }
launch {
syncManager.status.collect { status ->
syncStatus.text = status.text
syncStatus.setTextColor(
ContextCompat.getColor(
this@MainActivity,
if (status.error) android.R.color.holo_red_dark else R.color.seed,
)
)
}
}
}
}
refresh()
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
intent.getStringExtra("date")?.let { value ->
TimeUtils.dateOf(value)?.let {
selectedDate = it
refresh()
}
}
}
override fun onStart() {
super.onStart()
syncManager.start()
}
override fun onStop() {
syncManager.stop()
super.onStop()
}
override fun onDestroy() {
syncManager.shutdown()
super.onDestroy()
}
private fun showCompletedSummary() {
val items = repository.completedItems()
val projects = repository.completedProjects()
val focusedMinutes = items.sumOf {
val start = TimeUtils.parse(it.block.startAt)
val end = TimeUtils.parse(it.block.endAt)
if (start != null && end != null) {
maxOf(0, java.time.Duration.between(start, end).toMinutes().toInt())
} else 0
}
val summaryText = buildString {
append("短期任务 ${items.size} · 长期项目 ${projects.size}\n")
append("累计专注 ${focusedMinutes / 60} 小时 ${focusedMinutes % 60} 分钟\n\n")
if (items.isNotEmpty()) {
append("短期任务\n")
items.take(50).forEach {
append("· ${it.task.title} ${TimeUtils.formatDate(it.block.doneAt ?: it.block.endAt)}\n")
}
append("\n")
}
if (projects.isNotEmpty()) {
append("长期项目\n")
projects.forEach { append("· ${it.title} ${TimeUtils.formatDate(it.updatedAt)}\n") }
}
if (items.isEmpty() && projects.isEmpty()) {
append("还没有已完成记录。")
}
}
val content = TextView(this).apply {
text = summaryText
textSize = 14f
setPadding(48, 24, 48, 24)
}
val scroll = ScrollView(this).apply { addView(content) }
MaterialAlertDialogBuilder(this)
.setTitle(R.string.completed_summary)
.setView(scroll)
.setPositiveButton(android.R.string.ok, null)
.show()
}
private fun refresh() {
dateText.text = selectedDate.format(dateFormatter)
val items = repository.itemsForDate(selectedDate)
adapter.submit(items)
emptyText.visibility = if (items.isEmpty()) View.VISIBLE else View.GONE
val projects = repository.projects()
projectAdapter.submit(projects)
projectHeader.visibility = if (projects.isEmpty()) View.GONE else View.VISIBLE
projectList.visibility = if (projects.isEmpty()) View.GONE else View.VISIBLE
}
private fun showScheduleDialog(item: ScheduleItem?, fallbackStart: java.time.LocalDateTime? = null) {
val start = item?.let { TimeUtils.localTime(it.block.startAt) } ?: fallbackStart ?: TimeUtils.defaultStart(selectedDate)
val end = item?.let { TimeUtils.localTime(it.block.endAt) } ?: start.plusHours(1)
val dialog = ScheduleDialog(
this,
if (item == null) getString(R.string.add_schedule) else item.task.title,
item?.task?.title.orEmpty(),
start,
end,
) { title, newStart, newEnd ->
if (item == null) {
repository.create(title, newStart, newEnd, prefs.deviceId)
} else {
repository.update(item.block.id, title, newStart, newEnd, prefs.deviceId)
}
selectedDate = newStart.toLocalDate()
syncManager.triggerSync()
BackgroundScheduler.syncNow(this)
refresh()
}
dialog.show()
}
private fun confirmDelete(item: ScheduleItem) {
MaterialAlertDialogBuilder(this)
.setTitle(R.string.delete_title)
.setMessage(getString(R.string.delete_message, item.task.title))
.setNegativeButton(R.string.cancel, null)
.setPositiveButton(R.string.delete) { _, _ ->
repository.delete(item.block.id)
syncManager.triggerSync()
BackgroundScheduler.syncNow(this)
refresh()
}
.show()
}
}
@@ -0,0 +1,67 @@
package com.misaki.schedule.background
import android.content.Context
import androidx.work.Constraints
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.ExistingWorkPolicy
import androidx.work.NetworkType
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.OutOfQuotaPolicy
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkManager
import com.misaki.schedule.data.Prefs
import java.util.concurrent.TimeUnit
object BackgroundScheduler {
private const val SYNC_WORK = "schedule-sync"
private const val REMINDER_WORK = "schedule-reminders"
private const val SYNC_NOW_WORK = "schedule-sync-now"
fun update(context: Context, prefs: Prefs) {
scheduleReminders(context)
if (prefs.enabled) scheduleSync(context) else cancelSync(context)
}
fun scheduleSync(context: Context) {
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
val request = PeriodicWorkRequestBuilder<SyncWorker>(15, TimeUnit.MINUTES)
.setConstraints(constraints)
.build()
WorkManager.getInstance(context).enqueueUniquePeriodicWork(
SYNC_WORK,
ExistingPeriodicWorkPolicy.UPDATE,
request,
)
}
fun cancelSync(context: Context) {
WorkManager.getInstance(context).cancelUniqueWork(SYNC_WORK)
WorkManager.getInstance(context).cancelUniqueWork(SYNC_NOW_WORK)
}
fun scheduleReminders(context: Context) {
val request = PeriodicWorkRequestBuilder<ReminderWorker>(15, TimeUnit.MINUTES).build()
WorkManager.getInstance(context).enqueueUniquePeriodicWork(
REMINDER_WORK,
ExistingPeriodicWorkPolicy.UPDATE,
request,
)
}
fun syncNow(context: Context) {
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
val request = OneTimeWorkRequestBuilder<SyncWorker>()
.setConstraints(constraints)
.setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST)
.build()
WorkManager.getInstance(context).enqueueUniqueWork(
SYNC_NOW_WORK,
ExistingWorkPolicy.REPLACE,
request,
)
}
}
@@ -0,0 +1,13 @@
package com.misaki.schedule.background
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.misaki.schedule.data.Prefs
class BootReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action != Intent.ACTION_BOOT_COMPLETED) return
BackgroundScheduler.update(context, Prefs(context))
}
}
@@ -0,0 +1,99 @@
package com.misaki.schedule.background
import android.Manifest
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat
import com.misaki.schedule.MainActivity
import com.misaki.schedule.R
import com.misaki.schedule.data.ScheduleItem
import com.misaki.schedule.data.TimeUtils
object NotificationHelper {
const val CHANNEL_ID = "schedule_reminders"
fun ensureChannel(context: Context) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
val manager = context.getSystemService(NotificationManager::class.java) ?: return
val channel = NotificationChannel(
CHANNEL_ID,
context.getString(R.string.reminder_channel_name),
NotificationManager.IMPORTANCE_HIGH,
).apply {
description = context.getString(R.string.reminder_channel_description)
}
manager.createNotificationChannel(channel)
}
fun canNotify(context: Context): Boolean {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) !=
PackageManager.PERMISSION_GRANTED
) {
return false
}
return NotificationManagerCompat.from(context).areNotificationsEnabled()
}
fun notifyReminder(context: Context, item: ScheduleItem): Boolean {
val range = TimeUtils.formatRange(item.block.startAt, item.block.endAt)
return notify(
context,
item,
context.getString(R.string.reminder_title),
context.getString(R.string.reminder_text, item.task.title, range),
)
}
fun notifyLead(context: Context, item: ScheduleItem, minutesBefore: Int): Boolean {
val text = context.getString(
R.string.reminder_lead_text,
item.task.title,
minutesBefore,
TimeUtils.formatTime(item.block.startAt),
)
return notify(context, item, context.getString(R.string.reminder_lead_title), text)
}
fun notifyStart(context: Context, item: ScheduleItem): Boolean {
val text = context.getString(
R.string.reminder_start_text,
item.task.title,
TimeUtils.formatRange(item.block.startAt, item.block.endAt),
)
return notify(context, item, context.getString(R.string.reminder_start_title), text)
}
private fun notify(context: Context, item: ScheduleItem, title: String, text: String): Boolean {
if (!canNotify(context)) return false
ensureChannel(context)
val intent = Intent(context, MainActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
putExtra("date", item.block.startAt)
}
val pending = PendingIntent.getActivity(
context,
item.block.id.hashCode(),
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
)
val notification = NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(title)
.setContentText(text)
.setStyle(NotificationCompat.BigTextStyle().bigText(text))
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setAutoCancel(true)
.setContentIntent(pending)
.build()
NotificationManagerCompat.from(context).notify(item.block.id.hashCode(), notification)
return true
}
}
@@ -0,0 +1,59 @@
package com.misaki.schedule.background
import android.content.Context
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import com.misaki.schedule.data.Prefs
import com.misaki.schedule.data.ScheduleRepository
import com.misaki.schedule.data.TimeUtils
class ReminderWorker(appContext: Context, params: WorkerParameters) : CoroutineWorker(appContext, params) {
override suspend fun doWork(): Result {
return try {
NotificationHelper.ensureChannel(applicationContext)
if (!NotificationHelper.canNotify(applicationContext)) {
return Result.success()
}
val repository = ScheduleRepository(applicationContext)
val prefs = Prefs(applicationContext)
val now = TimeUtils.nowIso()
val since = TimeUtils.hoursAgo(24)
val pending = repository.pendingReminders(now, since)
for ((item, key) in pending) {
if (NotificationHelper.notifyReminder(applicationContext, item)) {
repository.markReminderSent(key, item.block.id, now)
}
}
val leadMinutes = prefs.reminderLeadMinutes
val nowInstant = java.time.Instant.now()
val horizon = TimeUtils.iso(nowInstant.plusSeconds(maxOf(leadMinutes, 20) * 60L))
val active = repository.upcomingReminderCandidates(now, horizon)
for (item in active) {
val start = TimeUtils.parse(item.block.startAt) ?: continue
val end = TimeUtils.parse(item.block.endAt) ?: continue
val startKey = "${item.block.id}@${item.block.startAt}@start"
val leadKey = "${item.block.id}@${item.block.startAt}@lead@${leadMinutes}"
if (leadMinutes > 0 &&
!nowInstant.isBefore(start.minusSeconds(leadMinutes * 60L)) &&
nowInstant.isBefore(start) &&
!repository.isReminderSent(leadKey) &&
NotificationHelper.notifyLead(applicationContext, item, leadMinutes)
) {
repository.markReminderSent(leadKey, item.block.id, now)
}
if (!nowInstant.isBefore(start) &&
nowInstant.isBefore(end) &&
nowInstant.isBefore(start.plusSeconds(20 * 60L)) &&
!repository.isReminderSent(startKey) &&
NotificationHelper.notifyStart(applicationContext, item)
) {
repository.markReminderSent(startKey, item.block.id, now)
}
}
Result.success()
} catch (_: Exception) {
Result.retry()
}
}
}
@@ -0,0 +1,34 @@
package com.misaki.schedule.background
import android.content.Context
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import com.misaki.schedule.data.Prefs
import com.misaki.schedule.data.ScheduleRepository
import com.misaki.schedule.sync.SyncEngine
import com.misaki.schedule.sync.UnauthorizedException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.IOException
class SyncWorker(appContext: Context, params: WorkerParameters) : CoroutineWorker(appContext, params) {
override suspend fun doWork(): Result {
val prefs = Prefs(applicationContext)
if (!prefs.enabled || prefs.serverUrl.isBlank()) return Result.success()
val repository = ScheduleRepository(applicationContext)
val engine = SyncEngine(prefs, repository)
return withContext(Dispatchers.IO) {
try {
engine.runOnce()
Result.success()
} catch (_: UnauthorizedException) {
prefs.clearToken()
Result.retry()
} catch (_: IOException) {
Result.retry()
} catch (_: Exception) {
Result.retry()
}
}
}
}
@@ -0,0 +1,55 @@
package com.misaki.schedule.data
import android.content.Context
import android.os.Build
import java.util.UUID
class Prefs(context: Context) {
private val prefs = context.getSharedPreferences("schedule_prefs", Context.MODE_PRIVATE)
private val generatedDeviceId: String by lazy {
val existing = prefs.getString("device_id", null)
if (!existing.isNullOrBlank()) {
existing
} else {
UUID.randomUUID().toString().also { prefs.edit().putString("device_id", it).apply() }
}
}
var serverUrl: String
get() = prefs.getString("server_url", "").orEmpty()
set(value) = prefs.edit().putString("server_url", normalizeUrl(value)).apply()
var enabled: Boolean
get() = prefs.getBoolean("sync_enabled", false)
set(value) = prefs.edit().putBoolean("sync_enabled", value).apply()
var token: String
get() = prefs.getString("token", "").orEmpty()
set(value) = prefs.edit().putString("token", value).apply()
var reminderLeadMinutes: Int
get() = prefs.getInt("reminder_lead_minutes", 10).coerceIn(0, 24 * 60)
set(value) = prefs.edit().putInt("reminder_lead_minutes", value.coerceIn(0, 24 * 60)).apply()
val deviceId: String
get() = generatedDeviceId
val deviceName: String
get() = listOf(Build.MANUFACTURER, Build.MODEL).filter { it.isNotBlank() }
.joinToString(" ").ifBlank { "Android" }
fun clearToken() {
prefs.edit().remove("token").apply()
}
companion object {
fun normalizeUrl(value: String): String {
var url = value.trim()
if (url.isEmpty()) return ""
if (!url.startsWith("http://") && !url.startsWith("https://")) {
url = "http://$url"
}
return url.trimEnd('/')
}
}
}
@@ -0,0 +1,107 @@
package com.misaki.schedule.data
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
class ScheduleDb(context: Context) : SQLiteOpenHelper(context, "schedule.db", null, 3) {
override fun onConfigure(db: SQLiteDatabase) {
super.onConfigure(db)
db.setForeignKeyConstraintsEnabled(true)
}
override fun onCreate(db: SQLiteDatabase) {
db.execSQL(
"""
CREATE TABLE task(
id TEXT PRIMARY KEY,
title TEXT NOT NULL,
description TEXT,
source TEXT,
source_ref TEXT,
estimated_min INTEGER,
energy_req INTEGER,
deadline TEXT,
priority INTEGER DEFAULT 1,
status TEXT DEFAULT 'active',
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
version INTEGER DEFAULT 0,
device_id TEXT NOT NULL
)
""".trimIndent()
)
db.execSQL(
"""
CREATE TABLE timeblock(
id TEXT PRIMARY KEY,
task_id TEXT NOT NULL REFERENCES task(id) ON DELETE CASCADE,
start_at TEXT NOT NULL,
end_at TEXT NOT NULL,
granularity INTEGER DEFAULT 15,
splittable INTEGER DEFAULT 1,
breakable INTEGER DEFAULT 1,
status TEXT DEFAULT 'scheduled',
done_at TEXT,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
version INTEGER DEFAULT 0,
device_id TEXT NOT NULL
)
""".trimIndent()
)
db.execSQL(
"""
CREATE TABLE outbox(
id INTEGER PRIMARY KEY AUTOINCREMENT,
entity_type TEXT NOT NULL,
entity_id TEXT NOT NULL,
op TEXT NOT NULL,
payload TEXT,
created_at TEXT NOT NULL
)
""".trimIndent()
)
db.execSQL("CREATE TABLE sync_state(device_id TEXT PRIMARY KEY, last_seq INTEGER DEFAULT 0)")
db.execSQL(
"CREATE TABLE reminder_sent(key TEXT PRIMARY KEY, block_id TEXT NOT NULL, sent_at TEXT NOT NULL)"
)
createProjectTable(db)
db.execSQL("CREATE INDEX idx_timeblock_start ON timeblock(start_at)")
db.execSQL("CREATE INDEX idx_timeblock_task ON timeblock(task_id)")
db.execSQL("CREATE INDEX idx_outbox_entity ON outbox(entity_type, entity_id)")
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
if (oldVersion < 2) {
db.execSQL(
"CREATE TABLE IF NOT EXISTS reminder_sent(key TEXT PRIMARY KEY, block_id TEXT NOT NULL, sent_at TEXT NOT NULL)"
)
}
if (oldVersion < 3) {
createProjectTable(db)
}
}
private fun createProjectTable(db: SQLiteDatabase) {
db.execSQL(
"""
CREATE TABLE IF NOT EXISTS project(
id TEXT PRIMARY KEY,
title TEXT NOT NULL,
description TEXT,
source TEXT,
source_ref TEXT,
deadline TEXT,
priority INTEGER DEFAULT 1,
status TEXT DEFAULT 'active',
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
version INTEGER DEFAULT 0,
device_id TEXT NOT NULL
)
""".trimIndent()
)
db.execSQL("CREATE INDEX IF NOT EXISTS idx_project_deadline ON project(status, deadline)")
}
}
@@ -0,0 +1,124 @@
package com.misaki.schedule.data
import java.time.Instant
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.LocalTime
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.time.temporal.ChronoUnit
data class Task(
val id: String,
val title: String,
val description: String?,
val source: String,
val sourceRef: String?,
val estimatedMin: Int?,
val energyReq: Int?,
val deadline: String?,
val priority: Int,
val status: String,
val createdAt: String,
val updatedAt: String,
val version: Int,
val deviceId: String,
)
data class TimeBlock(
val id: String,
val taskId: String,
val startAt: String,
val endAt: String,
val granularity: Int,
val splittable: Boolean,
val breakable: Boolean,
val status: String,
val doneAt: String?,
val createdAt: String,
val updatedAt: String,
val version: Int,
val deviceId: String,
)
data class Project(
val id: String,
val title: String,
val description: String?,
val source: String,
val sourceRef: String?,
val deadline: String?,
val priority: Int,
val status: String,
val createdAt: String,
val updatedAt: String,
val version: Int,
val deviceId: String,
)
data class ScheduleItem(val task: Task, val block: TimeBlock) {
fun isActive(): Boolean = block.status == "scheduled" || block.status == "in_progress"
fun isDone(): Boolean = block.status == "done"
}
object TimeUtils {
private val isoFormatter = DateTimeFormatter.ISO_INSTANT
private val displayTime = DateTimeFormatter.ofPattern("HH:mm")
private val displayDate = DateTimeFormatter.ofPattern("M月d日")
fun nowIso(): String = isoFormatter.format(Instant.now().truncatedTo(ChronoUnit.MILLIS))
fun iso(value: Instant): String = isoFormatter.format(value.truncatedTo(ChronoUnit.MILLIS))
fun toIso(local: LocalDateTime): String =
isoFormatter.format(local.atZone(ZoneId.systemDefault()).toInstant().truncatedTo(ChronoUnit.MILLIS))
fun parse(local: String?): Instant? = try {
if (local.isNullOrBlank()) null else Instant.parse(local)
} catch (_: Exception) {
null
}
fun localTime(iso: String?): LocalDateTime? =
parse(iso)?.atZone(ZoneId.systemDefault())?.toLocalDateTime()
fun formatTime(iso: String?): String =
localTime(iso)?.format(displayTime) ?: "--:--"
fun formatDate(iso: String?): String =
localTime(iso)?.format(displayDate) ?: ""
fun formatRange(start: String?, end: String?): String =
"${formatTime(start)}–${formatTime(end)}"
fun dayStart(date: LocalDate): String =
toIso(date.atStartOfDay())
fun dayEnd(date: LocalDate): String =
toIso(date.plusDays(1).atStartOfDay())
fun dateOf(iso: String?): LocalDate? =
parse(iso)?.atZone(ZoneId.systemDefault())?.toLocalDate()
fun startOfDay(date: LocalDate): LocalDateTime = date.atStartOfDay()
fun hoursAgo(hours: Long): String =
isoFormatter.format(Instant.now().minus(hours, ChronoUnit.HOURS).truncatedTo(ChronoUnit.MILLIS))
fun defaultStart(date: LocalDate): LocalDateTime {
val today = LocalDate.now()
if (date == today) {
val now = LocalDateTime.now().plusMinutes(15)
return now.withSecond(0).withNano(0)
}
return LocalDateTime.of(date, LocalTime.of(9, 0))
}
}
fun statusLabel(status: String): String = when (status) {
"done" -> "已完成"
"in_progress" -> "进行中"
"dropped" -> "已放弃"
"missed" -> "已错过"
else -> "待办"
}
@@ -0,0 +1,625 @@
package com.misaki.schedule.data
import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import com.misaki.schedule.sync.CompletionMerge
import com.misaki.schedule.sync.JsonCodec
import com.misaki.schedule.sync.Lww
import kotlinx.coroutines.flow.MutableStateFlow
import org.json.JSONArray
import org.json.JSONObject
import java.time.LocalDate
import java.time.LocalDateTime
import java.util.UUID
class ScheduleRepository(context: Context) {
private val dbHelper = ScheduleDb(context.applicationContext)
private val db: SQLiteDatabase get() = dbHelper.writableDatabase
val revision = MutableStateFlow(0L)
data class PendingBatch(val maxId: Long, val count: Int, val changes: JSONArray)
data class PullResult(val applied: Int)
fun itemsForDate(date: LocalDate): List<ScheduleItem> {
val result = mutableListOf<ScheduleItem>()
db.rawQuery(
"""
SELECT t.id, t.title, t.description, t.source, t.source_ref, t.estimated_min,
t.energy_req, t.deadline, t.priority, t.status, t.created_at, t.updated_at,
t.version, t.device_id,
b.id, b.task_id, b.start_at, b.end_at, b.granularity, b.splittable,
b.breakable, b.status, b.done_at, b.created_at, b.updated_at, b.version, b.device_id
FROM timeblock b JOIN task t ON t.id = b.task_id
WHERE b.start_at < ? AND b.end_at > ?
ORDER BY b.start_at ASC
""".trimIndent(),
arrayOf(TimeUtils.dayEnd(date), TimeUtils.dayStart(date))
).use { cursor ->
while (cursor.moveToNext()) {
result.add(readItem(cursor))
}
}
return result
}
fun projects(): List<Project> {
val result = mutableListOf<Project>()
db.rawQuery(
"""
SELECT id, title, description, source, source_ref, deadline, priority, status,
created_at, updated_at, version, device_id
FROM project
WHERE status = 'active'
ORDER BY CASE WHEN deadline IS NULL THEN 1 ELSE 0 END, deadline ASC, priority DESC
""".trimIndent(),
emptyArray()
).use { cursor ->
while (cursor.moveToNext()) {
result.add(
Project(
id = cursor.getString(0),
title = cursor.getString(1),
description = cursor.stringOrNull(2),
source = cursor.getString(3) ?: "android",
sourceRef = cursor.stringOrNull(4),
deadline = cursor.stringOrNull(5),
priority = cursor.getInt(6),
status = cursor.getString(7) ?: "active",
createdAt = cursor.getString(8),
updatedAt = cursor.getString(9),
version = cursor.getInt(10),
deviceId = cursor.getString(11),
)
)
}
}
return result
}
fun completedItems(): List<ScheduleItem> {
val result = mutableListOf<ScheduleItem>()
db.rawQuery(
"""
SELECT t.id, t.title, t.description, t.source, t.source_ref, t.estimated_min,
t.energy_req, t.deadline, t.priority, t.status, t.created_at, t.updated_at,
t.version, t.device_id,
b.id, b.task_id, b.start_at, b.end_at, b.granularity, b.splittable,
b.breakable, b.status, b.done_at, b.created_at, b.updated_at, b.version, b.device_id
FROM timeblock b JOIN task t ON t.id = b.task_id
WHERE b.status = 'done'
ORDER BY COALESCE(b.done_at, b.end_at) DESC
LIMIT 200
""".trimIndent(),
emptyArray()
).use { cursor ->
while (cursor.moveToNext()) result.add(readItem(cursor))
}
return result
}
fun completedProjects(): List<Project> {
val result = mutableListOf<Project>()
db.rawQuery(
"""
SELECT id, title, description, source, source_ref, deadline, priority, status,
created_at, updated_at, version, device_id
FROM project WHERE status = 'done'
ORDER BY updated_at DESC
""".trimIndent(),
emptyArray()
).use { cursor ->
while (cursor.moveToNext()) {
result.add(Project(
id = cursor.getString(0),
title = cursor.getString(1),
description = cursor.stringOrNull(2),
source = cursor.getString(3) ?: "android",
sourceRef = cursor.stringOrNull(4),
deadline = cursor.stringOrNull(5),
priority = cursor.getInt(6),
status = cursor.getString(7) ?: "done",
createdAt = cursor.getString(8),
updatedAt = cursor.getString(9),
version = cursor.getInt(10),
deviceId = cursor.getString(11),
))
}
}
return result
}
fun create(title: String, start: LocalDateTime, end: LocalDateTime, deviceId: String): String {
val now = TimeUtils.nowIso()
val taskId = UUID.randomUUID().toString()
val blockId = UUID.randomUUID().toString()
val task = Task(
id = taskId,
title = title.trim().ifBlank { "未命名日程" },
description = null,
source = "android",
sourceRef = null,
estimatedMin = minutesBetween(start, end),
energyReq = null,
deadline = null,
priority = 1,
status = "active",
createdAt = now,
updatedAt = now,
version = 0,
deviceId = deviceId,
)
val block = TimeBlock(
id = blockId,
taskId = taskId,
startAt = TimeUtils.toIso(start),
endAt = TimeUtils.toIso(end),
granularity = 15,
splittable = true,
breakable = true,
status = "scheduled",
doneAt = null,
createdAt = now,
updatedAt = now,
version = 0,
deviceId = deviceId,
)
inTransaction { database ->
database.insertOrThrow("task", null, taskValues(task))
database.insertOrThrow("timeblock", null, blockValues(block))
enqueue(database, "task", taskId, "upsert", JsonCodec.taskToJson(task), now)
enqueue(database, "timeblock", blockId, "upsert", JsonCodec.blockToJson(block), now)
}
bump()
return blockId
}
fun update(blockId: String, title: String, start: LocalDateTime, end: LocalDateTime, deviceId: String) {
val existing = itemByBlock(blockId) ?: return
val now = TimeUtils.nowIso()
val task = existing.task.copy(
title = title.trim().ifBlank { "未命名日程" },
estimatedMin = minutesBetween(start, end),
updatedAt = now,
version = existing.task.version + 1,
deviceId = deviceId,
)
val block = existing.block.copy(
startAt = TimeUtils.toIso(start),
endAt = TimeUtils.toIso(end),
updatedAt = now,
version = existing.block.version + 1,
deviceId = deviceId,
)
inTransaction { database ->
database.update("task", taskValues(task), "id = ?", arrayOf(task.id))
database.update("timeblock", blockValues(block), "id = ?", arrayOf(block.id))
enqueue(database, "task", task.id, "upsert", JsonCodec.taskToJson(task), now)
enqueue(database, "timeblock", block.id, "upsert", JsonCodec.blockToJson(block), now)
}
bump()
}
fun setDone(blockId: String, done: Boolean, deviceId: String) {
val existing = itemByBlock(blockId) ?: return
val now = TimeUtils.nowIso()
val block = existing.block.copy(
status = if (done) "done" else "scheduled",
doneAt = if (done) now else null,
updatedAt = now,
version = existing.block.version + 1,
deviceId = deviceId,
)
inTransaction { database ->
database.update("timeblock", blockValues(block), "id = ?", arrayOf(block.id))
enqueue(database, "timeblock", block.id, "upsert", JsonCodec.blockToJson(block), now)
}
bump()
}
fun delete(blockId: String) {
val existing = itemByBlock(blockId) ?: return
val now = TimeUtils.nowIso()
inTransaction { database ->
database.delete("timeblock", "id = ?", arrayOf(existing.block.id))
val remaining = database.rawQuery(
"SELECT COUNT(*) FROM timeblock WHERE task_id = ?",
arrayOf(existing.task.id)
).use { cursor -> if (cursor.moveToFirst()) cursor.getInt(0) else 0 }
enqueue(database, "timeblock", existing.block.id, "delete",
JsonCodec.blockToJson(existing.block).withUpdatedAt(now), now)
if (remaining == 0) {
database.delete("task", "id = ?", arrayOf(existing.task.id))
enqueue(database, "task", existing.task.id, "delete",
JsonCodec.taskToJson(existing.task).withUpdatedAt(now), now)
}
}
bump()
}
fun pendingChanges(limit: Int = 100): PendingBatch {
val changes = JSONArray()
var maxId = 0L
var count = 0
db.rawQuery(
"SELECT id, entity_type, entity_id, op, payload FROM outbox ORDER BY id ASC LIMIT ?",
arrayOf(limit.toString())
).use { cursor ->
while (cursor.moveToNext()) {
val id = cursor.getLong(0)
maxId = maxOf(maxId, id)
val payload = cursor.getString(4)?.let { JSONObject(it) } ?: JSONObject()
val change = JSONObject().apply {
put("entity_type", cursor.getString(1))
put("entity_id", cursor.getString(2))
put("op", cursor.getString(3))
put("version", payload.optInt("version", 0))
put("updated_at", payload.optString("updated_at", TimeUtils.nowIso()))
put("payload", payload)
}
changes.put(change)
count++
}
}
return PendingBatch(maxId, count, changes)
}
fun clearOutboxThrough(maxId: Long) {
db.delete("outbox", "id <= ?", arrayOf(maxId.toString()))
}
fun pendingReminders(nowIso: String, sinceIso: String): List<Pair<ScheduleItem, String>> {
val result = mutableListOf<Pair<ScheduleItem, String>>()
db.rawQuery(
"""
SELECT t.id, t.title, t.description, t.source, t.source_ref, t.estimated_min,
t.energy_req, t.deadline, t.priority, t.status, t.created_at, t.updated_at,
t.version, t.device_id,
b.id, b.task_id, b.start_at, b.end_at, b.granularity, b.splittable,
b.breakable, b.status, b.done_at, b.created_at, b.updated_at, b.version, b.device_id,
b.id || '@' || b.updated_at
FROM timeblock b JOIN task t ON t.id = b.task_id
LEFT JOIN reminder_sent r ON r.key = b.id || '@' || b.updated_at
WHERE b.status IN ('scheduled', 'in_progress')
AND b.end_at <= ? AND b.end_at >= ?
AND r.key IS NULL
ORDER BY b.end_at ASC
""".trimIndent(),
arrayOf(nowIso, sinceIso)
).use { cursor ->
while (cursor.moveToNext()) {
result.add(readItem(cursor) to cursor.getString(27))
}
}
return result
}
fun upcomingReminderCandidates(nowIso: String, horizonIso: String): List<ScheduleItem> {
val result = mutableListOf<ScheduleItem>()
db.rawQuery(
"""
SELECT t.id, t.title, t.description, t.source, t.source_ref, t.estimated_min,
t.energy_req, t.deadline, t.priority, t.status, t.created_at, t.updated_at,
t.version, t.device_id,
b.id, b.task_id, b.start_at, b.end_at, b.granularity, b.splittable,
b.breakable, b.status, b.done_at, b.created_at, b.updated_at, b.version, b.device_id
FROM timeblock b JOIN task t ON t.id = b.task_id
WHERE b.status IN ('scheduled', 'in_progress')
AND b.start_at <= ? AND b.end_at > ?
ORDER BY b.start_at ASC
LIMIT 50
""".trimIndent(),
arrayOf(horizonIso, nowIso)
).use { cursor ->
while (cursor.moveToNext()) {
result.add(readItem(cursor))
}
}
return result
}
fun isReminderSent(key: String): Boolean {
db.rawQuery("SELECT 1 FROM reminder_sent WHERE key = ?", arrayOf(key)).use { cursor ->
return cursor.moveToFirst()
}
}
fun markReminderSent(key: String, blockId: String, sentAt: String) {
val values = ContentValues().apply {
put("key", key)
put("block_id", blockId)
put("sent_at", sentAt)
}
db.insertWithOnConflict("reminder_sent", null, values, SQLiteDatabase.CONFLICT_IGNORE)
}
fun lastSeq(deviceId: String): Long {
db.rawQuery("SELECT last_seq FROM sync_state WHERE device_id = ?", arrayOf(deviceId)).use { cursor ->
return if (cursor.moveToFirst()) cursor.getLong(0) else 0L
}
}
fun applyRemote(deviceId: String, changes: JSONArray, latestSeq: Long): PullResult {
var applied = 0
inTransaction { database ->
for (index in 0 until changes.length()) {
val change = changes.getJSONObject(index)
if (change.optString("device_id") == deviceId) continue
val entityType = change.optString("entity_type")
val entityId = change.optString("entity_id")
val op = change.optString("op")
val remoteUpdated = change.optString("updated_at")
val payload = change.optJSONObject("payload")
val localUpdated = localUpdatedAt(database, entityType, entityId)
val equalWins = op == "delete"
val forceCompletion = CompletionMerge.remoteCompletionWins(
entityType,
op,
localBlockStatus(database, entityId),
payload?.optString("status"),
)
if (!forceCompletion && !Lww.shouldApply(localUpdated, remoteUpdated, equalWins)) continue
if (op == "delete") {
when (entityType) {
"task" -> database.delete("task", "id = ?", arrayOf(entityId))
"timeblock" -> database.delete("timeblock", "id = ?", arrayOf(entityId))
"project" -> database.delete("project", "id = ?", arrayOf(entityId))
}
applied++
} else if (op == "upsert") {
if (payload == null) continue
when (entityType) {
"task" -> {
payload.put("updated_at", remoteUpdated)
payload.put("version", change.optInt("version", 0))
payload.put("device_id", change.optString("device_id"))
database.insertWithOnConflict("task", null, taskValues(payload), SQLiteDatabase.CONFLICT_REPLACE)
applied++
}
"timeblock" -> {
payload.put("updated_at", remoteUpdated)
payload.put("version", change.optInt("version", 0))
payload.put("device_id", change.optString("device_id"))
if (taskExists(database, payload.optString("task_id"))) {
database.insertWithOnConflict("timeblock", null, blockValues(payload), SQLiteDatabase.CONFLICT_REPLACE)
applied++
}
}
"project" -> {
payload.put("updated_at", remoteUpdated)
payload.put("version", change.optInt("version", 0))
payload.put("device_id", change.optString("device_id"))
database.insertWithOnConflict("project", null, projectValues(payload), SQLiteDatabase.CONFLICT_REPLACE)
applied++
}
}
}
}
val values = ContentValues().apply { put("last_seq", latestSeq) }
val updated = database.update("sync_state", values, "device_id = ?", arrayOf(deviceId))
if (updated == 0) {
values.put("device_id", deviceId)
database.insertOrThrow("sync_state", null, values)
}
}
if (applied > 0) bump()
return PullResult(applied)
}
private fun itemByBlock(blockId: String): ScheduleItem? {
db.rawQuery(
"""
SELECT t.id, t.title, t.description, t.source, t.source_ref, t.estimated_min,
t.energy_req, t.deadline, t.priority, t.status, t.created_at, t.updated_at,
t.version, t.device_id,
b.id, b.task_id, b.start_at, b.end_at, b.granularity, b.splittable,
b.breakable, b.status, b.done_at, b.created_at, b.updated_at, b.version, b.device_id
FROM timeblock b JOIN task t ON t.id = b.task_id WHERE b.id = ?
""".trimIndent(),
arrayOf(blockId)
).use { cursor ->
return if (cursor.moveToFirst()) readItem(cursor) else null
}
}
private fun readItem(cursor: Cursor): ScheduleItem {
val task = Task(
id = cursor.getString(0),
title = cursor.getString(1),
description = cursor.stringOrNull(2),
source = cursor.getString(3) ?: "android",
sourceRef = cursor.stringOrNull(4),
estimatedMin = cursor.intOrNull(5),
energyReq = cursor.intOrNull(6),
deadline = cursor.stringOrNull(7),
priority = cursor.getInt(8),
status = cursor.getString(9) ?: "active",
createdAt = cursor.getString(10),
updatedAt = cursor.getString(11),
version = cursor.getInt(12),
deviceId = cursor.getString(13),
)
val block = TimeBlock(
id = cursor.getString(14),
taskId = cursor.getString(15),
startAt = cursor.getString(16),
endAt = cursor.getString(17),
granularity = cursor.getInt(18),
splittable = cursor.getInt(19) != 0,
breakable = cursor.getInt(20) != 0,
status = cursor.getString(21) ?: "scheduled",
doneAt = cursor.stringOrNull(22),
createdAt = cursor.getString(23),
updatedAt = cursor.getString(24),
version = cursor.getInt(25),
deviceId = cursor.getString(26),
)
return ScheduleItem(task, block)
}
private fun localUpdatedAt(database: SQLiteDatabase, entityType: String, entityId: String): String? {
val table = when (entityType) {
"task" -> "task"
"timeblock" -> "timeblock"
"project" -> "project"
else -> return null
}
database.rawQuery("SELECT updated_at FROM $table WHERE id = ?", arrayOf(entityId)).use { cursor ->
return if (cursor.moveToFirst()) cursor.getString(0) else null
}
}
private fun localBlockStatus(database: SQLiteDatabase, blockId: String): String? {
database.rawQuery("SELECT status FROM timeblock WHERE id = ?", arrayOf(blockId)).use { cursor ->
return if (cursor.moveToFirst()) cursor.getString(0) else null
}
}
private fun taskExists(database: SQLiteDatabase, taskId: String): Boolean {
database.rawQuery("SELECT 1 FROM task WHERE id = ?", arrayOf(taskId)).use { cursor ->
return cursor.moveToFirst()
}
}
private fun enqueue(
database: SQLiteDatabase,
entityType: String,
entityId: String,
op: String,
payload: JSONObject,
createdAt: String,
) {
val values = ContentValues().apply {
put("entity_type", entityType)
put("entity_id", entityId)
put("op", op)
put("payload", payload.toString())
put("created_at", createdAt)
}
database.insertOrThrow("outbox", null, values)
}
private fun taskValues(task: Task): ContentValues = ContentValues().apply {
put("id", task.id)
put("title", task.title)
put("description", task.description)
put("source", task.source)
put("source_ref", task.sourceRef)
put("estimated_min", task.estimatedMin)
put("energy_req", task.energyReq)
put("deadline", task.deadline)
put("priority", task.priority)
put("status", task.status)
put("created_at", task.createdAt)
put("updated_at", task.updatedAt)
put("version", task.version)
put("device_id", task.deviceId)
}
private fun taskValues(payload: JSONObject): ContentValues = ContentValues().apply {
put("id", payload.optString("id"))
put("title", payload.optString("title", "未命名日程"))
put("description", payload.stringOrNull("description"))
put("source", payload.optString("source", "android"))
put("source_ref", payload.stringOrNull("source_ref"))
put("estimated_min", payload.intOrNull("estimated_min"))
put("energy_req", payload.intOrNull("energy_req"))
put("deadline", payload.stringOrNull("deadline"))
put("priority", payload.optInt("priority", 1))
put("status", payload.optString("status", "active"))
put("created_at", payload.optString("created_at", TimeUtils.nowIso()))
put("updated_at", payload.optString("updated_at", TimeUtils.nowIso()))
put("version", payload.optInt("version", 0))
put("device_id", payload.optString("device_id"))
}
private fun blockValues(block: TimeBlock): ContentValues = ContentValues().apply {
put("id", block.id)
put("task_id", block.taskId)
put("start_at", block.startAt)
put("end_at", block.endAt)
put("granularity", block.granularity)
put("splittable", if (block.splittable) 1 else 0)
put("breakable", if (block.breakable) 1 else 0)
put("status", block.status)
put("done_at", block.doneAt)
put("created_at", block.createdAt)
put("updated_at", block.updatedAt)
put("version", block.version)
put("device_id", block.deviceId)
}
private fun projectValues(payload: JSONObject): ContentValues = ContentValues().apply {
put("id", payload.optString("id"))
put("title", payload.optString("title", "未命名项目"))
put("description", payload.stringOrNull("description"))
put("source", payload.optString("source", "android"))
put("source_ref", payload.stringOrNull("source_ref"))
put("deadline", payload.stringOrNull("deadline"))
put("priority", payload.optInt("priority", 1))
put("status", payload.optString("status", "active"))
put("created_at", payload.optString("created_at", TimeUtils.nowIso()))
put("updated_at", payload.optString("updated_at", TimeUtils.nowIso()))
put("version", payload.optInt("version", 0))
put("device_id", payload.optString("device_id"))
}
private fun blockValues(payload: JSONObject): ContentValues = ContentValues().apply {
put("id", payload.optString("id"))
put("task_id", payload.optString("task_id"))
put("start_at", payload.optString("start_at"))
put("end_at", payload.optString("end_at"))
put("granularity", payload.optInt("granularity", 15))
put("splittable", if (payload.boolInt("splittable", true)) 1 else 0)
put("breakable", if (payload.boolInt("breakable", true)) 1 else 0)
put("status", payload.optString("status", "scheduled"))
put("done_at", payload.stringOrNull("done_at"))
put("created_at", payload.optString("created_at", TimeUtils.nowIso()))
put("updated_at", payload.optString("updated_at", TimeUtils.nowIso()))
put("version", payload.optInt("version", 0))
put("device_id", payload.optString("device_id"))
}
private fun inTransaction(block: (SQLiteDatabase) -> Unit) {
val database = db
database.beginTransaction()
try {
block(database)
database.setTransactionSuccessful()
} finally {
database.endTransaction()
}
}
private fun bump() {
revision.value = revision.value + 1
}
private fun minutesBetween(start: LocalDateTime, end: LocalDateTime): Int =
java.time.Duration.between(start, end).toMinutes().toInt()
private fun Cursor.stringOrNull(index: Int): String? = if (isNull(index)) null else getString(index)
private fun Cursor.intOrNull(index: Int): Int? = if (isNull(index)) null else getInt(index)
private fun JSONObject.stringOrNull(key: String): String? =
if (isNull(key)) null else optString(key).takeIf { it.isNotEmpty() }
private fun JSONObject.intOrNull(key: String): Int? =
if (isNull(key) || !has(key)) null else optInt(key)
private fun JSONObject.boolInt(key: String, fallback: Boolean): Boolean = when (val value = opt(key)) {
is Boolean -> value
is Number -> value.toInt() != 0
else -> fallback
}
private fun JSONObject.withUpdatedAt(value: String): JSONObject {
val copy = JSONObject(toString())
copy.put("updated_at", value)
return copy
}
}
@@ -0,0 +1,14 @@
package com.misaki.schedule.sync
object CompletionMerge {
fun remoteCompletionWins(
entityType: String,
op: String,
localStatus: String?,
remoteStatus: String?,
): Boolean =
entityType == "timeblock" &&
op == "upsert" &&
remoteStatus == "done" &&
(localStatus == "scheduled" || localStatus == "in_progress")
}
@@ -0,0 +1,40 @@
package com.misaki.schedule.sync
import com.misaki.schedule.data.Task
import com.misaki.schedule.data.TimeBlock
import org.json.JSONObject
object JsonCodec {
fun taskToJson(task: Task): JSONObject = JSONObject().apply {
put("id", task.id)
put("title", task.title)
put("description", task.description ?: JSONObject.NULL)
put("source", task.source)
put("source_ref", task.sourceRef ?: JSONObject.NULL)
put("estimated_min", task.estimatedMin ?: JSONObject.NULL)
put("energy_req", task.energyReq ?: JSONObject.NULL)
put("deadline", task.deadline ?: JSONObject.NULL)
put("priority", task.priority)
put("status", task.status)
put("created_at", task.createdAt)
put("updated_at", task.updatedAt)
put("version", task.version)
put("device_id", task.deviceId)
}
fun blockToJson(block: TimeBlock): JSONObject = JSONObject().apply {
put("id", block.id)
put("task_id", block.taskId)
put("start_at", block.startAt)
put("end_at", block.endAt)
put("granularity", block.granularity)
put("splittable", block.splittable)
put("breakable", block.breakable)
put("status", block.status)
put("done_at", block.doneAt ?: JSONObject.NULL)
put("created_at", block.createdAt)
put("updated_at", block.updatedAt)
put("version", block.version)
put("device_id", block.deviceId)
}
}
@@ -0,0 +1,18 @@
package com.misaki.schedule.sync
import java.time.Instant
object Lww {
/**
* @param equalWins delete tombstones win when timestamps are equal.
*/
fun shouldApply(local: String?, remote: String, equalWins: Boolean): Boolean {
if (local.isNullOrBlank()) return true
val localInstant: Instant? = runCatching { Instant.parse(local) }.getOrNull()
val remoteInstant: Instant? = runCatching { Instant.parse(remote) }.getOrNull()
if (localInstant != null && remoteInstant != null) {
return remoteInstant.isAfter(localInstant) || (equalWins && remoteInstant == localInstant)
}
return remote > local || (equalWins && remote == local)
}
}
@@ -0,0 +1,106 @@
package com.misaki.schedule.sync
import com.misaki.schedule.data.Prefs
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.WebSocket
import okhttp3.WebSocketListener
import org.json.JSONArray
import org.json.JSONObject
import java.io.IOException
import java.util.concurrent.TimeUnit
class UnauthorizedException : IOException("同步认证失效")
data class PullPage(val changes: JSONArray, val latestSeq: Long, val hasMore: Boolean)
class SyncApi(private val prefs: Prefs) {
val client: OkHttpClient = OkHttpClient.Builder()
.connectTimeout(15, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.build()
private val jsonType = "application/json; charset=utf-8".toMediaType()
fun register(deviceId: String, name: String): String {
val body = JSONObject().apply {
put("device_id", deviceId)
put("name", name)
}
val request = Request.Builder()
.url(apiUrl("v1/devices/register"))
.post(body.toString().toRequestBody(jsonType))
.build()
val json = executeJson(request, requireAuth = false)
val token = json.optString("token")
if (token.isBlank()) throw IOException("注册响应缺少 token")
return token
}
fun push(token: String, changes: JSONArray): Int {
val body = JSONObject().apply { put("changes", changes) }
val request = Request.Builder()
.url(apiUrl("v1/changes/push"))
.header("Authorization", "Bearer $token")
.post(body.toString().toRequestBody(jsonType))
.build()
return executeJson(request, requireAuth = true).optInt("accepted", 0)
}
fun pull(token: String, sinceSeq: Long): PullPage {
val url = apiUrl("v1/changes/pull").newBuilder()
.addQueryParameter("since_seq", sinceSeq.toString())
.addQueryParameter("limit", "200")
.build()
val request = Request.Builder()
.url(url)
.header("Authorization", "Bearer $token")
.get()
.build()
val json = executeJson(request, requireAuth = true)
return PullPage(
changes = json.optJSONArray("changes") ?: JSONArray(),
latestSeq = json.optLong("latest_seq", sinceSeq),
hasMore = json.optBoolean("has_more", false),
)
}
fun newWebSocket(token: String, listener: WebSocketListener): WebSocket {
val url = streamUrl(token)
return client.newWebSocket(Request.Builder().url(url).build(), listener)
}
private fun streamUrl(token: String): HttpUrl {
return baseUrl().newBuilder()
.addPathSegments("v1/stream")
.addQueryParameter("token", token)
.build()
}
private fun apiUrl(path: String): HttpUrl =
baseUrl().newBuilder().addPathSegments(path).build()
private fun baseUrl(): HttpUrl {
val raw = Prefs.normalizeUrl(prefs.serverUrl)
return raw.toHttpUrlOrNull()
?: throw IOException("同步服务地址无效")
}
private fun executeJson(request: Request, requireAuth: Boolean): JSONObject {
client.newCall(request).execute().use { response ->
if (response.code == 401 && requireAuth) throw UnauthorizedException()
val text = response.body?.string().orEmpty()
if (!response.isSuccessful) {
throw IOException("HTTP ${response.code}: ${text.take(200)}")
}
return runCatching { JSONObject(text) }.getOrElse {
throw IOException("服务器返回了无效 JSON")
}
}
}
}
@@ -0,0 +1,49 @@
package com.misaki.schedule.sync
import com.misaki.schedule.data.Prefs
import com.misaki.schedule.data.ScheduleRepository
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
/**
* Shared one-pass sync implementation used by the foreground controller and WorkManager.
*/
class SyncEngine(
private val prefs: Prefs,
private val repository: ScheduleRepository,
) {
val api = SyncApi(prefs)
suspend fun runOnce() = mutex.withLock {
if (!prefs.enabled || prefs.serverUrl.isBlank()) {
return@withLock
}
if (prefs.token.isBlank()) {
prefs.token = api.register(prefs.deviceId, prefs.deviceName)
}
var pushes = 0
while (pushes < 10) {
val batch = repository.pendingChanges()
if (batch.count == 0) break
val accepted = api.push(prefs.token, batch.changes)
if (accepted < batch.count) throw IllegalStateException("服务端未接受全部变更")
repository.clearOutboxThrough(batch.maxId)
pushes++
}
var cursor = repository.lastSeq(prefs.deviceId)
var pages = 0
while (pages < 10) {
val page = api.pull(prefs.token, cursor)
repository.applyRemote(prefs.deviceId, page.changes, page.latestSeq)
cursor = page.latestSeq
pages++
if (!page.hasMore) break
}
}
companion object {
private val mutex = Mutex()
}
}
@@ -0,0 +1,138 @@
package com.misaki.schedule.sync
import android.content.Context
import com.misaki.schedule.data.Prefs
import com.misaki.schedule.data.ScheduleRepository
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeoutOrNull
import okhttp3.Response
import okhttp3.WebSocket
import okhttp3.WebSocketListener
import org.json.JSONObject
class SyncManager(
@Suppress("UNUSED_PARAMETER") context: Context,
private val prefs: Prefs,
private val repository: ScheduleRepository,
) {
data class Status(val text: String, val error: Boolean = false)
val status = MutableStateFlow(Status("本地"))
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
private val engine = SyncEngine(prefs, repository)
private val api = engine.api
private val trigger = Channel<Unit>(Channel.CONFLATED)
private var job: Job? = null
@Volatile private var webSocket: WebSocket? = null
fun start() {
job?.cancel()
closeWebSocket()
if (!prefs.enabled) {
status.value = Status("同步未启用")
return
}
if (prefs.serverUrl.isBlank()) {
status.value = Status("未配置同步地址", error = true)
return
}
job = scope.launch { loop() }
}
fun stop() {
job?.cancel()
job = null
closeWebSocket()
status.value = Status("本地")
}
fun reload() {
stop()
start()
}
fun triggerSync() {
trigger.trySend(Unit)
}
private suspend fun loop() {
while (scope.isActive) {
try {
if (prefs.token.isBlank()) register()
ensureWebSocket()
syncOnce()
status.value = Status("已同步")
withTimeoutOrNull(15000) { trigger.receive() }
} catch (_: UnauthorizedException) {
closeWebSocket()
prefs.clearToken()
status.value = Status("认证失效,正在重新注册")
delay(300)
} catch (error: Exception) {
status.value = Status("离线,等待重试", error = true)
withTimeoutOrNull(5000) { trigger.receive() }
}
}
}
private fun register() {
status.value = Status("正在注册设备…")
val token = api.register(prefs.deviceId, prefs.deviceName)
prefs.token = token
}
private suspend fun syncOnce() {
status.value = Status("同步中…")
engine.runOnce()
}
private fun ensureWebSocket() {
if (webSocket != null || prefs.token.isBlank()) return
synchronized(this) {
if (webSocket != null) return
webSocket = api.newWebSocket(prefs.token, object : WebSocketListener() {
override fun onOpen(webSocket: WebSocket, response: Response) {
triggerSync()
}
override fun onMessage(webSocket: WebSocket, text: String) {
val type = runCatching { JSONObject(text).optString("type") }.getOrNull()
if (type == "ready" || type == "changes") {
triggerSync()
}
}
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
this@SyncManager.webSocket = null
}
override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
this@SyncManager.webSocket = null
}
})
}
}
private fun closeWebSocket() {
synchronized(this) {
webSocket?.close(1000, "stop")
webSocket = null
}
}
fun shutdown() {
stop()
scope.cancel()
}
}
@@ -0,0 +1,51 @@
package com.misaki.schedule.ui
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.misaki.schedule.R
import com.misaki.schedule.data.Project
import java.time.LocalDate
import java.time.temporal.ChronoUnit
class ProjectAdapter : RecyclerView.Adapter<ProjectAdapter.ViewHolder>() {
private var items: List<Project> = emptyList()
fun submit(projects: List<Project>) {
items = projects
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_project, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(items[position])
}
override fun getItemCount(): Int = items.size
class ViewHolder(itemView: android.view.View) : RecyclerView.ViewHolder(itemView) {
private val title: TextView = itemView.findViewById(R.id.projectTitle)
private val deadline: TextView = itemView.findViewById(R.id.projectDeadline)
fun bind(project: Project) {
title.text = project.title
deadline.text = deadlineLabel(project)
}
private fun deadlineLabel(project: Project): String {
val date = runCatching { LocalDate.parse(project.deadline) }.getOrNull()
?: return "无截止日期"
val days = ChronoUnit.DAYS.between(LocalDate.now(), date).toInt()
return when {
days < 0 -> "截止 ${date} · 已逾期 ${-days} 天"
days == 0 -> "截止 今天"
else -> "截止 ${date} · 剩余 ${days} 天"
}
}
}
}
@@ -0,0 +1,65 @@
package com.misaki.schedule.ui
import android.graphics.Paint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.misaki.schedule.R
import com.misaki.schedule.data.ScheduleItem
import com.misaki.schedule.data.TimeUtils
import com.misaki.schedule.data.statusLabel
class ScheduleAdapter(
private val onEdit: (ScheduleItem) -> Unit,
private val onLongPress: (ScheduleItem) -> Unit,
private val onDoneChanged: (ScheduleItem, Boolean) -> Unit,
) : RecyclerView.Adapter<ScheduleAdapter.ViewHolder>() {
private var items: List<ScheduleItem> = emptyList()
fun submit(newItems: List<ScheduleItem>) {
items = newItems
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_schedule, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(items[position])
}
override fun getItemCount(): Int = items.size
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val title: TextView = itemView.findViewById(R.id.titleText)
private val time: TextView = itemView.findViewById(R.id.timeText)
private val status: TextView = itemView.findViewById(R.id.statusText)
private val done: CheckBox = itemView.findViewById(R.id.doneCheck)
fun bind(item: ScheduleItem) {
title.text = item.task.title
time.text = TimeUtils.formatRange(item.block.startAt, item.block.endAt)
status.text = statusLabel(item.block.status)
val isDone = item.isDone()
done.setOnCheckedChangeListener(null)
done.isChecked = isDone
done.setOnCheckedChangeListener { _, checked -> onDoneChanged(item, checked) }
title.paintFlags = if (isDone) {
title.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG
} else {
title.paintFlags and Paint.STRIKE_THRU_TEXT_FLAG.inv()
}
itemView.setOnClickListener { onEdit(item) }
itemView.setOnLongClickListener {
onLongPress(item)
true
}
}
}
}
@@ -0,0 +1,105 @@
package com.misaki.schedule.ui
import android.app.DatePickerDialog
import android.app.Dialog
import android.app.TimePickerDialog
import android.content.Context
import android.view.View
import android.view.WindowManager
import android.widget.TextView
import com.google.android.material.button.MaterialButton
import com.google.android.material.textfield.TextInputEditText
import com.misaki.schedule.R
import com.misaki.schedule.data.TimeUtils
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
class ScheduleDialog(
context: Context,
dialogTitle: String,
private val initialTitle: String,
initialStart: LocalDateTime,
initialEnd: LocalDateTime,
private val onSave: (String, LocalDateTime, LocalDateTime) -> Unit,
) : Dialog(context) {
private var start: LocalDateTime = initialStart
private var end: LocalDateTime = initialEnd
private val titleInput: TextInputEditText
private val startButton: MaterialButton
private val endButton: MaterialButton
private val errorText: TextView
private val formatter = DateTimeFormatter.ofPattern("M月d日 HH:mm")
init {
setContentView(R.layout.dialog_schedule)
setTitle(dialogTitle)
window?.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT)
titleInput = findViewById(R.id.titleInput)
startButton = findViewById(R.id.startButton)
endButton = findViewById(R.id.endButton)
errorText = findViewById(R.id.errorText)
titleInput.setText(initialTitle)
updateButtons()
findViewById<MaterialButton>(R.id.cancelButton).setOnClickListener { dismiss() }
findViewById<MaterialButton>(R.id.saveButton).setOnClickListener { save() }
startButton.setOnClickListener {
pickDateTime(start) { picked ->
start = picked
if (end <= start) end = start.plusHours(1)
updateButtons()
}
}
endButton.setOnClickListener {
pickDateTime(end) { picked ->
end = picked
updateButtons()
}
}
}
private fun updateButtons() {
startButton.text = formatter.format(start)
endButton.text = formatter.format(end)
}
private fun pickDateTime(initial: LocalDateTime, onPicked: (LocalDateTime) -> Unit) {
DatePickerDialog(
context,
{ _, year, month, day ->
TimePickerDialog(
context,
{ _, hour, minute ->
onPicked(LocalDateTime.of(year, month + 1, day, hour, minute))
},
initial.hour,
initial.minute,
true,
).show()
},
initial.year,
initial.monthValue - 1,
initial.dayOfMonth,
).show()
}
private fun save() {
val title = titleInput.text?.toString()?.trim().orEmpty()
if (title.isEmpty()) {
showError(context.getString(R.string.title_required))
return
}
if (end <= start) {
showError(context.getString(R.string.start_after_end))
return
}
onSave(title, start, end)
dismiss()
}
private fun showError(message: String) {
errorText.text = message
errorText.visibility = View.VISIBLE
}
}
@@ -0,0 +1,41 @@
package com.misaki.schedule.ui
import android.content.Context
import android.view.LayoutInflater
import android.widget.ArrayAdapter
import android.widget.Spinner
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.materialswitch.MaterialSwitch
import com.google.android.material.textfield.TextInputEditText
import com.misaki.schedule.R
import com.misaki.schedule.background.BackgroundScheduler
import com.misaki.schedule.data.Prefs
import com.misaki.schedule.sync.SyncManager
object SettingsDialog {
fun show(context: Context, prefs: Prefs, syncManager: SyncManager) {
val view = LayoutInflater.from(context).inflate(R.layout.dialog_settings, null)
val url = view.findViewById<TextInputEditText>(R.id.serverUrlInput)
val enabled = view.findViewById<MaterialSwitch>(R.id.syncSwitch)
val lead = view.findViewById<Spinner>(R.id.leadSpinner)
val leadValues = intArrayOf(0, 5, 10, 15, 30, 60)
val leadLabels = leadValues.map { if (it == 0) "仅开始时" else "提前 $it 分钟" }
lead.adapter = ArrayAdapter(context, android.R.layout.simple_spinner_dropdown_item, leadLabels)
lead.setSelection(leadValues.indexOf(prefs.reminderLeadMinutes).takeIf { it >= 0 } ?: 2)
url.setText(prefs.serverUrl)
enabled.isChecked = prefs.enabled
MaterialAlertDialogBuilder(context)
.setTitle(R.string.settings)
.setView(view)
.setNegativeButton(R.string.cancel, null)
.setPositiveButton(R.string.save) { _, _ ->
prefs.serverUrl = url.text?.toString().orEmpty()
prefs.enabled = enabled.isChecked
prefs.reminderLeadMinutes = leadValues[lead.selectedItemPosition.coerceIn(0, leadValues.lastIndex)]
BackgroundScheduler.update(context, prefs)
syncManager.reload()
}
.show()
}
}
@@ -0,0 +1,9 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#FFFFFF"
android:pathData="M11,5h2v6h6v2h-6v6h-2v-6h-6v-2h6z" />
</vector>
@@ -0,0 +1,18 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<path
android:fillColor="#4F6BED"
android:pathData="M0,0h108v108h-108z" />
<path
android:fillColor="#FFFFFF"
android:pathData="M28,24h52a8,8 0,0 1,8 8v52a8,8 0,0 1,-8 8h-52a8,8 0,0 1,-8 -8v-52a8,8 0,0 1,8 -8z" />
<path
android:fillColor="#4F6BED"
android:pathData="M28,40h52v6h-52zM38,30h6v12h-6zM64,30h6v12h-6z" />
<path
android:fillColor="#4F6BED"
android:pathData="M42,56h8v8h-8zM58,56h8v8h-8zM42,70h8v8h-8z" />
</vector>
@@ -0,0 +1,9 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#FFFFFFFF"
android:pathData="M12,2a10,10 0,1 0,0 20a10,10 0,0 0,0 -20zM12,4a8,8 0,1 1,0 16a8,8 0,0 1,0 -16zM11,7h2v5.4l3.2,3.2l-1.4,1.4l-3.8,-3.8z" />
</vector>
@@ -0,0 +1,129 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="?attr/colorSurface">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.google.android.material.appbar.MaterialToolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorSurface"
app:menu="@menu/menu_main"
app:title="@string/app_name"
app:titleTextColor="?attr/colorOnSurface" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal"
android:paddingHorizontal="12dp"
android:paddingVertical="6dp">
<ImageButton
android:id="@+id/previousDay"
android:layout_width="40dp"
android:layout_height="40dp"
android:background="?attr/selectableItemBackgroundBorderless"
android:contentDescription="@string/previous_day"
android:src="@android:drawable/ic_media_previous"
app:tint="?attr/colorOnSurface" />
<TextView
android:id="@+id/dateText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:textSize="17sp"
android:textStyle="bold" />
<ImageButton
android:id="@+id/nextDay"
android:layout_width="40dp"
android:layout_height="40dp"
android:background="?attr/selectableItemBackgroundBorderless"
android:contentDescription="@string/next_day"
android:src="@android:drawable/ic_media_next"
app:tint="?attr/colorOnSurface" />
<com.google.android.material.button.MaterialButton
android:id="@+id/todayButton"
style="@style/Widget.Material3.Button.TextButton"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:text="@string/today" />
</LinearLayout>
<TextView
android:id="@+id/syncStatus"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingHorizontal="16dp"
android:paddingBottom="4dp"
android:text="@string/sync_local"
android:textColor="?attr/colorPrimary"
android:textSize="12sp" />
<TextView
android:id="@+id/projectHeader"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingHorizontal="16dp"
android:paddingTop="4dp"
android:text="@string/long_term_projects"
android:textStyle="bold"
android:textSize="13sp"
android:visibility="gone" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/projectList"
android:layout_width="match_parent"
android:layout_height="120dp"
android:clipToPadding="false"
android:paddingBottom="4dp"
android:visibility="gone" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/scheduleList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false"
android:paddingTop="6dp"
android:paddingBottom="88dp" />
<TextView
android:id="@+id/emptyText"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="@string/empty_schedule"
android:textColor="?attr/colorOnSurfaceVariant"
android:textSize="15sp"
android:visibility="gone" />
</FrameLayout>
</LinearLayout>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/addButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="20dp"
android:contentDescription="@string/add_schedule"
android:src="@drawable/ic_add"
app:tint="?attr/colorOnPrimary" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
@@ -0,0 +1,79 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="22dp">
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/title">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/titleInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:imeOptions="actionDone"
android:inputType="text"
android:maxLines="2" />
</com.google.android.material.textfield.TextInputLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:orientation="horizontal">
<com.google.android.material.button.MaterialButton
android:id="@+id/startButton"
style="@style/Widget.Material3.Button.OutlinedButton"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/start" />
<Space
android:layout_width="10dp"
android:layout_height="1dp" />
<com.google.android.material.button.MaterialButton
android:id="@+id/endButton"
style="@style/Widget.Material3.Button.OutlinedButton"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/end" />
</LinearLayout>
<TextView
android:id="@+id/errorText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="8dp"
android:textColor="?attr/colorError"
android:textSize="12sp"
android:visibility="gone" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="18dp"
android:gravity="end"
android:orientation="horizontal">
<com.google.android.material.button.MaterialButton
android:id="@+id/cancelButton"
style="@style/Widget.Material3.Button.TextButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/cancel" />
<com.google.android.material.button.MaterialButton
android:id="@+id/saveButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/save" />
</LinearLayout>
</LinearLayout>
@@ -0,0 +1,49 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="22dp">
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/server_url">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/serverUrlInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/server_url_hint"
android:imeOptions="actionDone"
android:inputType="textUri"
android:maxLines="1" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.materialswitch.MaterialSwitch
android:id="@+id/syncSwitch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:text="@string/enable_sync" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="14dp"
android:text="@string/reminder_lead"
android:textSize="14sp" />
<Spinner
android:id="@+id/leadSpinner"
android:layout_width="match_parent"
android:layout_height="48dp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:text="@string/settings_hint"
android:textColor="?attr/colorOnSurfaceVariant"
android:textSize="12sp" />
</LinearLayout>
@@ -0,0 +1,35 @@
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.card.MaterialCardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginHorizontal="14dp"
android:layout_marginVertical="4dp"
app:cardCornerRadius="10dp"
app:cardElevation="0dp"
app:strokeWidth="0dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="10dp">
<TextView
android:id="@+id/projectTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLines="2"
android:textSize="14sp"
android:textStyle="bold" />
<TextView
android:id="@+id/projectDeadline"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="3dp"
android:textColor="?attr/colorPrimary"
android:textSize="11sp" />
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
@@ -0,0 +1,62 @@
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.card.MaterialCardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginHorizontal="14dp"
android:layout_marginVertical="5dp"
android:clickable="true"
android:focusable="true"
android:foreground="?attr/selectableItemBackground"
app:cardCornerRadius="12dp"
app:cardElevation="1dp"
app:strokeWidth="0dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal"
android:padding="10dp">
<CheckBox
android:id="@+id/doneCheck"
android:layout_width="48dp"
android:layout_height="48dp"
android:buttonTint="?attr/colorPrimary"
android:contentDescription="@string/save"
android:gravity="center" />
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical"
android:paddingEnd="8dp">
<TextView
android:id="@+id/titleText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLines="2"
android:textSize="15sp"
android:textStyle="bold" />
<TextView
android:id="@+id/timeText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="4dp"
android:textColor="?attr/colorOnSurfaceVariant"
android:textSize="12sp" />
</LinearLayout>
<TextView
android:id="@+id/statusText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="?attr/colorPrimary"
android:textSize="11sp" />
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/action_completed"
android:title="@string/completed_summary"
android:showAsAction="never" />
<item
android:id="@+id/action_sync"
android:title="@string/sync_now"
android:showAsAction="never" />
<item
android:id="@+id/action_settings"
android:title="@string/settings"
android:showAsAction="never" />
</menu>
@@ -0,0 +1,6 @@
<resources>
<color name="seed">#4F6BED</color>
<color name="accent">#4F6BED</color>
<color name="surface">#F6F7FB</color>
<color name="surface_dark">#15171C</color>
</resources>
@@ -0,0 +1,44 @@
<resources>
<string name="app_name">AI 日程</string>
<string name="settings">设置</string>
<string name="sync_now">立即同步</string>
<string name="today">今天</string>
<string name="previous_day">前一天</string>
<string name="next_day">后一天</string>
<string name="add_schedule">新建日程</string>
<string name="long_term_projects">长期项目</string>
<string name="completed_summary">已完成汇总</string>
<string name="empty_schedule">今天还没有安排</string>
<string name="sync_local">本地</string>
<string name="sync_not_configured">未配置同步服务</string>
<string name="sync_disabled">同步未启用</string>
<string name="sync_registering">正在注册设备…</string>
<string name="sync_busy">同步中…</string>
<string name="sync_done">已同步</string>
<string name="sync_offline">离线,等待重试</string>
<string name="delete_title">删除日程</string>
<string name="delete_message">确定删除「%1$s」吗?</string>
<string name="cancel">取消</string>
<string name="delete">删除</string>
<string name="save">保存</string>
<string name="title">标题</string>
<string name="start">开始</string>
<string name="end">结束</string>
<string name="title_hint">例如:写周报</string>
<string name="start_after_end">结束时间必须晚于开始时间</string>
<string name="title_required">请输入标题</string>
<string name="server_url">同步服务地址</string>
<string name="server_url_hint">http://192.168.1.2:8787</string>
<string name="enable_sync">启用多设备同步</string>
<string name="settings_hint">服务端需与手机在同一网络,或使用可访问的 HTTPS 地址。</string>
<string name="reminder_channel_name">日程提醒</string>
<string name="reminder_channel_description">日程结束时提醒未完成事项</string>
<string name="reminder_title">日程已结束</string>
<string name="reminder_text">「%1$s」原定 %2 尚未完成,点击处理。</string>
<string name="notification_permission_hint">开启通知权限后,日程开始/结束时会收到提醒。</string>
<string name="reminder_lead">提前提醒</string>
<string name="reminder_lead_title">日程即将开始</string>
<string name="reminder_lead_text">「%1$s」将在 %2 分钟后开始(%3)。</string>
<string name="reminder_start_title">日程开始</string>
<string name="reminder_start_text">「%1$s」现在开始(%2)。</string>
</resources>
@@ -0,0 +1,7 @@
<resources>
<style name="Theme.Schedule" parent="Theme.Material3.DayNight.NoActionBar">
<item name="colorPrimary">@color/seed</item>
<item name="colorSecondary">@color/accent</item>
<item name="android:fontFamily">sans</item>
</style>
</resources>
@@ -0,0 +1,22 @@
package com.misaki.schedule
import com.misaki.schedule.sync.CompletionMerge
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class CompletionMergeTest {
@Test
fun doneWinsOverLocalScheduledOrInProgress() {
assertTrue(CompletionMerge.remoteCompletionWins("timeblock", "upsert", "scheduled", "done"))
assertTrue(CompletionMerge.remoteCompletionWins("timeblock", "upsert", "in_progress", "done"))
}
@Test
fun doesNotOverrideDroppedOrUnrelatedChanges() {
assertFalse(CompletionMerge.remoteCompletionWins("timeblock", "upsert", "dropped", "done"))
assertFalse(CompletionMerge.remoteCompletionWins("task", "upsert", "active", "done"))
assertFalse(CompletionMerge.remoteCompletionWins("timeblock", "delete", "scheduled", "done"))
assertFalse(CompletionMerge.remoteCompletionWins("timeblock", "upsert", "scheduled", "scheduled"))
}
}
@@ -0,0 +1,27 @@
package com.misaki.schedule
import com.misaki.schedule.sync.Lww
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class LwwTest {
@Test
fun newerRemoteWins() {
assertTrue(Lww.shouldApply("2026-10-26T10:00:00.000Z", "2026-10-26T10:00:00.001Z", false))
assertFalse(Lww.shouldApply("2026-10-26T10:00:00.002Z", "2026-10-26T10:00:00.001Z", false))
}
@Test
fun equalTimestampRules() {
val value = "2026-10-26T10:00:00.000Z"
assertFalse(Lww.shouldApply(value, value, false))
assertTrue(Lww.shouldApply(value, value, true))
}
@Test
fun missingLocalAlwaysApplies() {
assertTrue(Lww.shouldApply(null, "2026-10-26T10:00:00.000Z", false))
assertTrue(Lww.shouldApply("", "2026-10-26T10:00:00.000Z", true))
}
}
@@ -0,0 +1,30 @@
package com.misaki.schedule
import com.misaki.schedule.data.TimeUtils
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Test
import java.time.LocalDateTime
class TimeUtilsTest {
@Test
fun roundTripsLocalDateTime() {
val value = LocalDateTime.of(2026, 10, 26, 9, 30)
val iso = TimeUtils.toIso(value)
assertEquals(value, TimeUtils.localTime(iso))
}
@Test
fun formatsTimeRange() {
assertEquals("09:00–10:30", TimeUtils.formatRange(
"2026-10-26T01:00:00.000Z",
"2026-10-26T02:30:00.000Z",
))
}
@Test
fun invalidTimestampIsSafe() {
assertNotNull(TimeUtils.nowIso())
assertEquals("--:--", TimeUtils.formatTime("not-a-time"))
}
}
+4
View File
@@ -0,0 +1,4 @@
plugins {
id("com.android.application") version "8.5.2" apply false
id("org.jetbrains.kotlin.android") version "1.9.24" apply false
}
+4
View File
@@ -0,0 +1,4 @@
org.gradle.jvmargs=-Xmx1536m -Dfile.encoding=UTF-8
android.useAndroidX=true
android.nonTransitiveRClass=true
kotlin.code.style=official
Binary file not shown.
+7
View File
@@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored Executable
+249
View File
@@ -0,0 +1,249 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
+92
View File
@@ -0,0 +1,92 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
+18
View File
@@ -0,0 +1,18 @@
pluginManagement {
repositories {
google()
mavenCentral()
gradlePluginPortal()
}
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
}
}
rootProject.name = "ScheduleAndroid"
include(":app")
+3
View File
@@ -1,6 +1,9 @@
cmake_minimum_required(VERSION 3.24)
find_package(Qt6 6.5 REQUIRED COMPONENTS Core Gui Widgets Sql Network Concurrent WebSockets Test)
if(UNIX AND NOT APPLE)
find_package(Qt6 REQUIRED COMPONENTS DBus)
endif()
qt_standard_project_setup()
+9 -1
View File
@@ -3,8 +3,11 @@
当前本地时间:{CURRENT_TIME}
今天星期:{WEEKDAY}
用户默认可用时间:{WORK_START}–{WORK_END}
用户精力高峰(用于安排高精力任务):{ENERGY_PROFILE}
用户现有日程(每行开头的 [bN] 是引用编号,只能用于 update/delete):
{EXISTING_SCHEDULE}
用户现有长期项目(避免重复创建):
{EXISTING_PROJECTS}
工作规则:
1. 先用 1–3 句简洁回复,说明你理解的需求和准备怎么安排。
@@ -13,7 +16,8 @@
{"operations":[
{"type":"create","title":"任务标题","description":"可选说明","duration_min":60,"deadline":"YYYY-MM-DDTHH:MM:SS","priority":1,"energy_req":1,"splittable":false,"preferred_start":"YYYY-MM-DDTHH:MM:SS","preferred_end":"YYYY-MM-DDTHH:MM:SS"},
{"type":"update","target_ref":"b1","title":"可选的新标题","duration_min":60,"preferred_start":"YYYY-MM-DDTHH:MM:SS","preferred_end":"YYYY-MM-DDTHH:MM:SS"},
{"type":"delete","target_ref":"b2"}
{"type":"delete","target_ref":"b2"},
{"type":"project","title":"跨月项目","description":"可选说明","deadline":"YYYY-MM-DD","priority":2}
]}
4. 时间使用用户本地时间,不带时区;不确定的字段填 null。
5. duration_min 必须在 15–480 之间;无法确定时用 60。
@@ -29,6 +33,10 @@
15. 现有日程摘要中带“(会议)”标记的条目属于会议类;用户要求删除“所有会议”时,逐个 delete 所有带该标记的条目。
16. 示例:现有 [b2] 团队同步(会议)、[b4] 项目会议(会议)。用户说“删除明天所有会议”时,输出 {"operations":[{"type":"delete","target_ref":"b2"},{"type":"delete","target_ref":"b4"}]}。
17. 示例:用户说“明天之前找时间做两小时长任务,可以拆开”,输出 create 并设置 "splittable":true;不要拆成两个独立任务。
18. energy_req 取值:0=低精力杂务,1=一般沟通/会议,2=高专注深度工作、学习或创作;不确定时填 1。高精力任务应优先放在用户的精力高峰时段。
19. 长期项目:当用户描述的是跨多天、数周或数月完成的目标(例如“一个月内完成飞行控制器项目”),且没有要求现在就拆成具体日程块时,使用 {"type":"project","title":"项目标题","description":"可选说明","deadline":"YYYY-MM-DD","priority":2}。不要用 create 把它塞进某一天。
20. 只有用户明确要求“今天/明天/几点做多久”或明确要求把项目拆成执行块时,才使用 create 创建具体时间块。
21. 长期项目的 deadline 使用日期而不是具体时间;如果用户说“这个月底/下个月/一个月内”,结合当前日期推算出合理日期。
补充信息:
{EXTRA_CONTEXT}
+3 -1
View File
@@ -4,7 +4,8 @@ JSON 格式:
{"operations":[
{"type":"create","title":"任务标题","description":"可选说明","duration_min":60,"deadline":"YYYY-MM-DDTHH:MM:SS","priority":1,"energy_req":1,"splittable":false,"preferred_start":"YYYY-MM-DDTHH:MM:SS","preferred_end":"YYYY-MM-DDTHH:MM:SS"},
{"type":"update","target_ref":"b1","title":"可选的新标题","duration_min":60,"preferred_start":"YYYY-MM-DDTHH:MM:SS","preferred_end":"YYYY-MM-DDTHH:MM:SS"},
{"type":"delete","target_ref":"b2"}
{"type":"delete","target_ref":"b2"},
{"type":"project","title":"长期项目标题","description":"可选说明","deadline":"YYYY-MM-DD","priority":2}
]}
规则:
@@ -14,4 +15,5 @@ JSON 格式:
- 如果只是闲聊或没有日程变更,operations 输出空数组。
- 用户明确要求新增/修改/删除时,必须给出 operations;冲突、时长不足或过去时间交给本地排程器处理。
- 可拆分请求优先设置 splittable=true。
- 跨多天/数周/数月的目标使用 type=project;只有具体执行块才使用 create。
- 现有日程摘要中的(会议)标记用于识别会议类;删除“所有会议”时删除全部带标记项。
+37
View File
@@ -1,7 +1,13 @@
add_library(schedule_core STATIC
core/DateTimeUtils.cpp
core/DateTimeUtils.h
core/DailyInsights.cpp
core/DailyInsights.h
core/EnergyProfile.cpp
core/EnergyProfile.h
core/Project.h
core/ProposedDiff.h
core/Recurrence.h
core/SchedulerEngine.cpp
core/SchedulerEngine.h
core/ScheduleItem.h
@@ -77,16 +83,28 @@ add_library(schedule_ui STATIC
ui/MainWindow.h
ui/dialogs/BlockEditDialog.cpp
ui/dialogs/BlockEditDialog.h
ui/dialogs/CompletedSummaryDialog.cpp
ui/dialogs/CompletedSummaryDialog.h
ui/dialogs/DailyReviewDialog.cpp
ui/dialogs/DailyReviewDialog.h
ui/dialogs/ProjectDialog.cpp
ui/dialogs/ProjectDialog.h
ui/dialogs/SearchDialog.cpp
ui/dialogs/SearchDialog.h
ui/dialogs/SettingsDialog.cpp
ui/dialogs/SettingsDialog.h
ui/panels/ChatPanel.cpp
ui/panels/ChatPanel.h
ui/panels/DiffPreviewCard.cpp
ui/panels/DiffPreviewCard.h
ui/panels/ProjectCard.cpp
ui/panels/ProjectCard.h
ui/panels/TodayItemCard.cpp
ui/panels/TodayItemCard.h
ui/panels/TodayPanel.cpp
ui/panels/TodayPanel.h
ui/theme/AnimationUtils.cpp
ui/theme/AnimationUtils.h
ui/theme/ThemeManager.cpp
ui/theme/ThemeManager.h
ui/theme/ThemeTokens.h
@@ -104,6 +122,9 @@ target_link_libraries(schedule_ui
PUBLIC schedule_ai schedule_sync Qt6::Widgets ElaWidgetTools
PRIVATE schedule_warnings
)
if(UNIX AND NOT APPLE)
target_link_libraries(schedule_ui PRIVATE Qt6::DBus)
endif()
qt_add_executable(Schedule
main.cpp
@@ -118,3 +139,19 @@ target_link_libraries(Schedule PRIVATE schedule_ui schedule_sync)
if(WIN32)
schedule_deploy_qt_runtime(Schedule)
endif()
install(TARGETS Schedule
RUNTIME DESTINATION .
BUNDLE DESTINATION .
)
if(WIN32 AND MINGW)
get_filename_component(_mingw_bin_dir "${CMAKE_CXX_COMPILER}" DIRECTORY)
file(GLOB _mingw_runtime
"${_mingw_bin_dir}/libgcc_s_*.dll"
"${_mingw_bin_dir}/libstdc++-6.dll"
"${_mingw_bin_dir}/libwinpthread-1.dll"
)
if(_mingw_runtime)
install(FILES ${_mingw_runtime} DESTINATION .)
endif()
endif()
+73 -4
View File
@@ -476,7 +476,10 @@ QString AIService::buildSystemPrompt()
prompt.replace(QStringLiteral("{WEEKDAY}"), weekdayLabel(now.date()));
prompt.replace(QStringLiteral("{WORK_START}"), QStringLiteral("08:00"));
prompt.replace(QStringLiteral("{WORK_END}"), QStringLiteral("22:00"));
prompt.replace(QStringLiteral("{ENERGY_PROFILE}"),
m_scheduleService.dailyReview(now.date()).energySummary);
prompt.replace(QStringLiteral("{EXISTING_SCHEDULE}"), scheduleSummary());
prompt.replace(QStringLiteral("{EXISTING_PROJECTS}"), projectSummary());
prompt.replace(QStringLiteral("{EXTRA_CONTEXT}"),
m_filePaths.isEmpty()
? QStringLiteral("无")
@@ -542,6 +545,31 @@ QString AIService::scheduleSummary()
return m_contextSummary;
}
QString AIService::projectSummary()
{
const QVector<Project> projects = m_scheduleService.projects();
if (projects.isEmpty())
{
return QStringLiteral("(暂无长期项目)");
}
QString summary;
int count = 0;
for (const Project& project : projects)
{
summary += QStringLiteral("- %1").arg(project.title);
if (project.deadline.has_value())
{
summary += QStringLiteral("(截止 %1)").arg(project.deadline->toString(QStringLiteral("yyyy-MM-dd")));
}
summary += QLatin1Char('\n');
if (++count >= 50)
{
break;
}
}
return summary.trimmed();
}
QJsonValue AIService::buildUserContent() const
{
QString text = m_userText;
@@ -612,6 +640,9 @@ void AIService::buildProposalFromOperations(const QJsonArray& operations, const
bool forceSplit = false;
};
QJsonArray projectCreates;
QVector<ProposedProjectEntry> projectEntries;
auto findContext = [this](const QString& raw) -> const ContextItem* {
QString key = raw.trimmed();
if (key.startsWith(QLatin1Char('[')) && key.endsWith(QLatin1Char(']')))
@@ -822,6 +853,39 @@ void AIService::buildProposalFromOperations(const QJsonArray& operations, const
{
type = QStringLiteral("create");
}
if (type == QStringLiteral("project"))
{
const QString title = object.value(QStringLiteral("title")).toString().trimmed();
const QString deadlineText = object.value(QStringLiteral("deadline")).toString().trimmed();
const QDate deadline =
QDate::fromString(deadlineText.left(10), Qt::ISODate);
if (title.isEmpty() || !deadline.isValid())
{
Q_EMIT notice(QStringLiteral("AI 返回的长期项目缺少标题或截止日期,已跳过"));
continue;
}
const QString tempId = QStringLiteral("p%1").arg(projectCreates.size() + 1);
QJsonObject project;
project.insert(QStringLiteral("temp_id"), tempId);
project.insert(QStringLiteral("title"), title.left(200));
project.insert(QStringLiteral("description"),
object.value(QStringLiteral("description")).toString().left(2000));
project.insert(QStringLiteral("deadline"), deadline.toString(Qt::ISODate));
project.insert(QStringLiteral("priority"),
std::clamp(object.value(QStringLiteral("priority")).toInt(2), 1, 5));
project.insert(QStringLiteral("source_ref"), m_userText.left(500));
projectCreates.append(project);
ProposedProjectEntry entry;
entry.tempId = tempId;
entry.operation = ProposedOperation::Create;
entry.title = title;
entry.description = project.value(QStringLiteral("description")).toString();
entry.deadline = deadline;
entry.priority = project.value(QStringLiteral("priority")).toInt();
projectEntries.append(entry);
continue;
}
if (type == QStringLiteral("create"))
{
bool changed = false;
@@ -898,7 +962,7 @@ void AIService::buildProposalFromOperations(const QJsonArray& operations, const
}
}
if (specs.isEmpty())
if (specs.isEmpty() && projectCreates.isEmpty())
{
if (tryLocalDeleteAllMeetings())
{
@@ -922,6 +986,9 @@ void AIService::buildProposalFromOperations(const QJsonArray& operations, const
}
scheduler::Options options;
options.granularityMinutes = 15;
options.energyAt = [this](scheduler::SysTime value) {
return m_scheduleService.energyLevelFor(fromSysTime(value));
};
struct Busy
{
@@ -1538,7 +1605,7 @@ void AIService::buildProposalFromOperations(const QJsonArray& operations, const
}
}
if (creates.isEmpty() && updates.isEmpty() && deletes.isEmpty())
if (creates.isEmpty() && updates.isEmpty() && deletes.isEmpty() && projectCreates.isEmpty())
{
appendHistory(m_visibleText);
finishRequest();
@@ -1553,8 +1620,8 @@ void AIService::buildProposalFromOperations(const QJsonArray& operations, const
QString explanation = visibleReply.trimmed();
if (explanation.isEmpty())
{
explanation = QStringLiteral("我整理了 %1 项日程调整建议。")
.arg(creates.size() + updates.size() + deletes.size());
explanation = QStringLiteral("我整理了 %1 项日程/长期项目建议。")
.arg(creates.size() + updates.size() + deletes.size() + projectCreates.size());
Q_EMIT streamDelta(explanation);
}
@@ -1567,6 +1634,7 @@ void AIService::buildProposalFromOperations(const QJsonArray& operations, const
{QStringLiteral("creates"), creates},
{QStringLiteral("updates"), updates},
{QStringLiteral("deletes"), deletes},
{QStringLiteral("projects"), projectCreates},
};
if (!m_store.insertProposedDiff(diff))
{
@@ -1577,6 +1645,7 @@ void AIService::buildProposalFromOperations(const QJsonArray& operations, const
m_pendingDiffs.insert(diff.id, diff);
proposal.diffId = diff.id;
proposal.explanation = explanation;
proposal.projects = projectEntries;
appendHistory(explanation);
Q_EMIT proposalReady(proposal);
finishRequest();
+1
View File
@@ -79,6 +79,7 @@ private:
QString buildSystemPrompt();
QString scheduleSummary();
QString projectSummary();
QJsonValue buildUserContent() const;
void buildProposalFromOperations(const QJsonArray& operations, const QString& visibleReply);
bool tryLocalDeleteAllMeetings();
+15
View File
@@ -1,5 +1,6 @@
#pragma once
#include <QDate>
#include <QDateTime>
#include <QMetaType>
#include <QString>
@@ -43,6 +44,19 @@ struct ProposedScheduleEntry
int energyRequired = -1;
};
struct ProposedProjectEntry
{
QString tempId;
ProposedOperation operation = ProposedOperation::Create;
QString projectId;
QString title;
QString oldTitle;
QString description;
std::optional<QDate> deadline;
std::optional<QDate> oldDeadline;
int priority = 1;
};
/*
* 类名: ScheduleProposal
* 功能: AI 生成并已落库的待确认日程建议,供 UI 展示与选择性接受
@@ -53,6 +67,7 @@ struct ScheduleProposal
QString diffId;
QString explanation;
QVector<ProposedScheduleEntry> entries;
QVector<ProposedProjectEntry> projects;
};
Q_DECLARE_METATYPE(ScheduleProposal)
+273
View File
@@ -0,0 +1,273 @@
#include "DailyInsights.h"
#include <algorithm>
#include <cmath>
#include "core/DateTimeUtils.h"
namespace
{
bool isActiveStatus(const QString& status)
{
return status == QStringLiteral("scheduled") || status == QStringLiteral("in_progress");
}
bool occupiesTime(const QString& status)
{
return status != QStringLiteral("dropped") && status != QStringLiteral("missed");
}
QDateTime dayBoundary(const QDate& date, int hour)
{
if (hour >= 24)
{
return QDateTime(date.addDays(1), QTime(0, 0), Qt::LocalTime);
}
return QDateTime(date, QTime(std::max(0, hour), 0), Qt::LocalTime);
}
QString formatWindow(const FreeWindow& window)
{
return QStringLiteral("%1–%2").arg(window.start.toString(QStringLiteral("HH:mm")),
window.end.toString(QStringLiteral("HH:mm")));
}
} // namespace
QVector<FreeWindow> findFreeWindows(const QVector<ScheduleItem>& items,
const QDate& date,
const QDateTime& from,
int workStartHour,
int workEndHour,
int minMinutes)
{
QVector<FreeWindow> result;
if (!date.isValid())
{
return result;
}
QDateTime rangeStart = dayBoundary(date, workStartHour);
const QDateTime rangeEnd = dayBoundary(date, workEndHour);
if (from.isValid() && from > rangeStart)
{
rangeStart = from;
}
if (rangeStart >= rangeEnd || minMinutes <= 0)
{
return result;
}
QVector<QPair<QDateTime, QDateTime>> busy;
for (const ScheduleItem& item : items)
{
if (!occupiesTime(item.block.status))
{
continue;
}
const QDateTime start = std::max(item.block.startAt, rangeStart);
const QDateTime end = std::min(item.block.endAt, rangeEnd);
if (start < end)
{
busy.append({start, end});
}
}
std::sort(busy.begin(), busy.end(), [](const auto& a, const auto& b) {
return a.first < b.first;
});
QDateTime cursor = rangeStart;
for (const auto& interval : busy)
{
if (interval.second <= cursor)
{
continue;
}
if (interval.first > cursor)
{
const int minutes = DateTimeUtils::minutesBetween(cursor, interval.first);
if (minutes >= minMinutes)
{
result.append({cursor, interval.first, minutes});
}
}
cursor = std::max(cursor, interval.second);
}
if (cursor < rangeEnd)
{
const int minutes = DateTimeUtils::minutesBetween(cursor, rangeEnd);
if (minutes >= minMinutes)
{
result.append({cursor, rangeEnd, minutes});
}
}
return result;
}
QVector<FreeWindow> findFreeWindows(const QVector<ScheduleItem>& items,
const QDate& date,
int workStartHour,
int workEndHour,
int minMinutes)
{
return findFreeWindows(items, date, dayBoundary(date, workStartHour), workStartHour, workEndHour, minMinutes);
}
DailyReview buildDailyReview(const QVector<ScheduleItem>& items,
const QDate& date,
const QDateTime& now)
{
DailyReview review;
review.date = date;
review.total = items.size();
for (const ScheduleItem& item : items)
{
const QString& status = item.block.status;
if (status == QStringLiteral("done"))
{
++review.done;
review.focusedMinutes +=
std::max(0, DateTimeUtils::minutesBetween(item.block.startAt, item.block.endAt));
}
else if (isActiveStatus(status))
{
++review.active;
if (item.block.endAt < now)
{
++review.overdue;
}
}
else if (status == QStringLiteral("missed"))
{
++review.missed;
}
else if (status == QStringLiteral("dropped"))
{
++review.dropped;
}
}
review.completionPercent =
review.total > 0 ? static_cast<int>(std::lround(review.done * 100.0 / review.total)) : 0;
const QDateTime reviewFrom = date < now.date() ? dayBoundary(date, 8) : now;
review.ghostWindows = findFreeWindows(items, date, reviewFrom, 8, 22, 30);
if (review.total == 0)
{
review.summary = QStringLiteral("今天还没有安排;可以先留出一段专注时间。");
}
else
{
review.summary = QStringLiteral("完成 %1/%2 项(%3%),累计专注 %4。")
.arg(review.done)
.arg(review.total)
.arg(review.completionPercent)
.arg(DateTimeUtils::formatDuration(review.focusedMinutes));
}
if (review.overdue > 0)
{
review.highlights.append(QStringLiteral("%1 项日程已超时").arg(review.overdue));
}
if (review.active > 0)
{
review.highlights.append(QStringLiteral("还有 %1 项待办").arg(review.active));
}
if (review.missed > 0 || review.dropped > 0)
{
review.highlights.append(
QStringLiteral("错过 %1 项,放弃 %2 项").arg(review.missed).arg(review.dropped));
}
if (review.done > 0)
{
review.highlights.append(QStringLiteral("今日专注 %1 分钟").arg(review.focusedMinutes));
}
if (review.ghostWindows.isEmpty())
{
review.highlights.append(QStringLiteral("今天没有 30 分钟以上的幽灵时间"));
}
else
{
review.highlights.append(
QStringLiteral("幽灵时间最早一段:%1").arg(formatWindow(review.ghostWindows.first())));
}
return review;
}
QVector<Suggestion> buildSuggestions(const QVector<ScheduleItem>& items,
const QDateTime& now,
int maxCount)
{
QVector<Suggestion> result;
if (maxCount <= 0)
{
return result;
}
QVector<ScheduleItem> overdue;
for (const ScheduleItem& item : items)
{
if (isActiveStatus(item.block.status) && item.block.endAt < now)
{
overdue.append(item);
}
}
if (!overdue.isEmpty())
{
Suggestion suggestion;
suggestion.kind = Suggestion::Kind::Overdue;
suggestion.title = QStringLiteral("处理超时日程");
suggestion.detail = QStringLiteral("「%1」%2已超时,建议重新安排或标记完成。")
.arg(overdue.first().task.title)
.arg(overdue.size() > 1
? QStringLiteral("等 %1 项").arg(overdue.size())
: QString());
result.append(suggestion);
}
if (result.size() >= maxCount)
{
return result;
}
const QVector<FreeWindow> ghost =
findFreeWindows(items, now.date(), now, 8, 22, 30);
if (!ghost.isEmpty())
{
Suggestion suggestion;
suggestion.kind = Suggestion::Kind::GhostTime;
suggestion.title = QStringLiteral("发现幽灵时间");
const FreeWindow& window = ghost.first();
suggestion.detail = QStringLiteral("%1 空出 %2,可安排一件重要的事。")
.arg(formatWindow(window), DateTimeUtils::formatDuration(window.minutes));
suggestion.start = window.start;
suggestion.end = window.end;
result.append(suggestion);
}
if (result.size() >= maxCount)
{
return result;
}
int doneCount = 0;
int activeCount = 0;
for (const ScheduleItem& item : items)
{
if (item.block.status == QStringLiteral("done"))
{
++doneCount;
}
else if (isActiveStatus(item.block.status))
{
++activeCount;
}
}
if (now.time().hour() >= 18 && (doneCount > 0 || activeCount > 0))
{
Suggestion suggestion;
suggestion.kind = Suggestion::Kind::Review;
suggestion.title = QStringLiteral("做一次今日复盘");
suggestion.detail = QStringLiteral("今天完成 %1 项,还有 %2 项待办,花 2 分钟回顾一下。")
.arg(doneCount)
.arg(activeCount);
result.append(suggestion);
}
return result;
}
+71
View File
@@ -0,0 +1,71 @@
#pragma once
#include <QDate>
#include <QDateTime>
#include <QString>
#include <QStringList>
#include <QVector>
#include "core/ScheduleItem.h"
struct FreeWindow
{
QDateTime start;
QDateTime end;
int minutes = 0;
};
struct DailyReview
{
QDate date;
int total = 0;
int done = 0;
int active = 0;
int missed = 0;
int dropped = 0;
int overdue = 0;
int focusedMinutes = 0;
int completionPercent = 0;
QVector<FreeWindow> ghostWindows;
QStringList highlights;
QString summary;
QString energySummary;
};
struct Suggestion
{
enum class Kind
{
Overdue,
GhostTime,
Review,
Energy,
};
Kind kind = Kind::Review;
QString title;
QString detail;
QDateTime start;
QDateTime end;
};
QVector<FreeWindow> findFreeWindows(const QVector<ScheduleItem>& items,
const QDate& date,
const QDateTime& from,
int workStartHour = 8,
int workEndHour = 22,
int minMinutes = 30);
QVector<FreeWindow> findFreeWindows(const QVector<ScheduleItem>& items,
const QDate& date,
int workStartHour = 8,
int workEndHour = 22,
int minMinutes = 30);
DailyReview buildDailyReview(const QVector<ScheduleItem>& items,
const QDate& date,
const QDateTime& now = QDateTime::currentDateTime());
QVector<Suggestion> buildSuggestions(const QVector<ScheduleItem>& items,
const QDateTime& now,
int maxCount = 3);
+147
View File
@@ -0,0 +1,147 @@
#include "EnergyProfile.h"
#include <algorithm>
#include <cmath>
namespace
{
int clampedLevel(int level)
{
return std::clamp(level, 0, 2);
}
int clampedWeekday(int weekday)
{
return std::clamp(weekday, 1, 7);
}
int clampedHour(int hour)
{
return std::clamp(hour, 0, 23);
}
} // namespace
EnergyProfile EnergyProfile::defaults()
{
EnergyProfile profile;
for (int weekday = 1; weekday <= 7; ++weekday)
{
for (int hour = 0; hour < 24; ++hour)
{
int level = 0;
if (weekday <= 5)
{
if (hour >= 9 && hour <= 11)
{
level = 2;
}
else if (hour == 8 || hour == 12 || hour == 14 || (hour >= 15 && hour <= 18))
{
level = 1;
}
}
else if ((hour >= 10 && hour <= 11) || (hour >= 14 && hour <= 17))
{
level = 1;
}
profile.m_levels[weekday][hour] = level;
}
}
return profile;
}
EnergyProfile EnergyProfile::fromLevels(const QVector<EnergyLevel>& levels)
{
EnergyProfile profile = defaults();
for (const EnergyLevel& level : levels)
{
profile.m_levels[clampedWeekday(level.weekday)][clampedHour(level.hour)] =
clampedLevel(level.level);
}
return profile;
}
QString EnergyProfile::label(int level)
{
switch (clampedLevel(level))
{
case 2:
return QStringLiteral("高");
case 1:
return QStringLiteral("中");
default:
return QStringLiteral("低");
}
}
int EnergyProfile::level(int weekday, int hour) const
{
if (weekday < 1 || weekday > 7 || hour < 0 || hour > 23)
{
return -1;
}
return m_levels[weekday][hour];
}
int EnergyProfile::level(const QDateTime& localDateTime) const
{
if (!localDateTime.isValid())
{
return -1;
}
return level(localDateTime.date().dayOfWeek(), localDateTime.time().hour());
}
bool EnergyProfile::setLevel(int weekday, int hour, int levelValue)
{
if (weekday < 1 || weekday > 7 || hour < 0 || hour > 23)
{
return false;
}
m_levels[weekday][hour] = clampedLevel(levelValue);
return true;
}
QVector<EnergyLevel> EnergyProfile::levels() const
{
QVector<EnergyLevel> result;
result.reserve(7 * 24);
for (int weekday = 1; weekday <= 7; ++weekday)
{
for (int hour = 0; hour < 24; ++hour)
{
result.append({weekday, hour, m_levels[weekday][hour]});
}
}
return result;
}
void EnergyProfile::learn(const QVector<EnergySample>& samples)
{
std::array<std::array<int, 24>, 8> sums{};
std::array<std::array<int, 24>, 8> counts{};
for (const EnergySample& sample : samples)
{
if (sample.weekday < 1 || sample.weekday > 7 || sample.hour < 0 || sample.hour > 23)
{
continue;
}
sums[sample.weekday][sample.hour] += clampedLevel(sample.level);
++counts[sample.weekday][sample.hour];
}
for (int weekday = 1; weekday <= 7; ++weekday)
{
for (int hour = 0; hour < 24; ++hour)
{
if (counts[weekday][hour] == 0)
{
continue;
}
const double average =
static_cast<double>(sums[weekday][hour]) / counts[weekday][hour];
m_levels[weekday][hour] =
std::clamp(static_cast<int>(std::lround(average)), 0, 2);
}
}
}
+43
View File
@@ -0,0 +1,43 @@
#pragma once
#include <QDateTime>
#include <QString>
#include <QVector>
#include <array>
/*
* 类名: EnergyProfile
* 功能: 按星期与小时保存精力水平(0 低 / 1 中 / 2 高),并从完成记录学习
* 线程安全: 否(值类型)
*/
struct EnergyLevel
{
int weekday = 1;
int hour = 0;
int level = 1;
};
struct EnergySample
{
int weekday = 1;
int hour = 0;
int level = 1;
};
class EnergyProfile
{
public:
static EnergyProfile defaults();
static EnergyProfile fromLevels(const QVector<EnergyLevel>& levels);
static QString label(int level);
int level(int weekday, int hour) const;
int level(const QDateTime& localDateTime) const;
bool setLevel(int weekday, int hour, int level);
QVector<EnergyLevel> levels() const;
void learn(const QVector<EnergySample>& samples);
private:
std::array<std::array<int, 24>, 8> m_levels{};
};
+28
View File
@@ -0,0 +1,28 @@
#pragma once
#include <QDate>
#include <QDateTime>
#include <QString>
#include <optional>
/*
* 类名: Project
* 功能: 跨多天的长期项目/目标,只持有模糊截止日期,不占用细粒度时间块
* 线程安全: 否(值类型)
*/
struct Project
{
QString id;
QString title;
QString description;
QString source = QStringLiteral("manual");
QString sourceRef;
std::optional<QDate> deadline;
int priority = 1;
QString status = QStringLiteral("active");
QDateTime createdAt;
QDateTime updatedAt;
int version = 0;
QString deviceId;
};
+28
View File
@@ -0,0 +1,28 @@
#pragma once
#include <QDate>
#include <QString>
#include <optional>
enum class RecurrenceFrequency
{
None = 0,
Daily,
Weekly,
Monthly,
};
struct RecurrenceSpec
{
RecurrenceFrequency frequency = RecurrenceFrequency::None;
QDate until;
};
struct Recurrence
{
QString id;
QString taskId;
QString rule;
std::optional<QDate> until;
};
+48 -22
View File
@@ -65,16 +65,35 @@ std::optional<TimeRange> findSlot(const std::vector<TimeRange>& windows,
SysTime rangeStart,
std::optional<SysTime> deadline,
std::chrono::seconds duration,
int granularityMinutes)
int granularityMinutes,
int energyRequired,
const Options& options)
{
const auto energySatisfied = [&](SysTime start) {
if (energyRequired < 0 || !options.energyAt)
{
return true;
}
const int level = options.energyAt(start);
return level < 0 || level >= energyRequired;
};
const auto nextGrid = [granularityMinutes](SysTime value) {
return ceilToGranularity(value + std::chrono::seconds{std::max(1, granularityMinutes) * 60},
granularityMinutes);
};
for (const TimeRange& window : windows)
{
SysTime cursor = ceilToGranularity(std::max(window.start, rangeStart), granularityMinutes);
if (cursor >= window.end)
while (cursor + duration <= window.end)
{
continue;
if (deadline && cursor + duration > *deadline)
{
break;
}
SysTime occupiedUntil = cursor;
bool conflict = false;
for (const TimeRange& occupied : busy)
{
if (occupied.end <= cursor)
@@ -83,30 +102,26 @@ std::optional<TimeRange> findSlot(const std::vector<TimeRange>& windows,
}
if (occupied.start >= cursor + duration)
{
if (deadline && cursor + duration > *deadline)
{
return std::nullopt;
break;
}
return TimeRange{cursor, cursor + duration};
}
if (occupied.end > cursor)
{
cursor = ceilToGranularity(occupied.end, granularityMinutes);
if (cursor >= window.end)
if (occupied.start < cursor + duration && occupied.end > cursor)
{
occupiedUntil = std::max(occupiedUntil, occupied.end);
conflict = true;
break;
}
}
}
if (cursor + duration <= window.end)
{
if (deadline && cursor + duration > *deadline)
if (conflict)
{
cursor = ceilToGranularity(occupiedUntil, granularityMinutes);
continue;
}
if (energySatisfied(cursor))
{
return TimeRange{cursor, cursor + duration};
}
cursor = nextGrid(cursor);
}
}
return std::nullopt;
}
@@ -187,9 +202,11 @@ Result schedule(const std::vector<TaskInput>& tasks,
{
const int clampedMinutes = std::clamp(task.durationMinutes, 5, 24 * 60);
const std::chrono::seconds duration{clampedMinutes * 60};
const std::optional<SysTime> deadline =
task.deadline.has_value() ? std::optional<SysTime>(std::min(*task.deadline, rangeEnd))
: std::nullopt;
std::optional<SysTime> deadline;
if (task.deadline.has_value())
{
deadline = std::min(*task.deadline, rangeEnd);
}
if (deadline && *deadline <= rangeStart)
{
result.failures.push_back({task.id, "截止时间已经过去"});
@@ -212,7 +229,9 @@ Result schedule(const std::vector<TaskInput>& tasks,
rangeStart,
deadline,
duration,
options.granularityMinutes);
options.granularityMinutes,
task.energyRequired,
options);
}
}
@@ -220,7 +239,14 @@ Result schedule(const std::vector<TaskInput>& tasks,
{
const SysTime upper = deadline.value_or(rangeEnd);
const std::vector<TimeRange> generalWindows = intersect(windows, rangeStart, upper);
slot = findSlot(generalWindows, busy, rangeStart, deadline, duration, options.granularityMinutes);
slot = findSlot(generalWindows,
busy,
rangeStart,
deadline,
duration,
options.granularityMinutes,
task.energyRequired,
options);
}
if (!slot.has_value())
+3
View File
@@ -1,6 +1,7 @@
#pragma once
#include <chrono>
#include <functional>
#include <optional>
#include <string>
#include <vector>
@@ -50,6 +51,8 @@ struct Failure
struct Options
{
int granularityMinutes = 15;
// 返回某个开始时刻的精力水平(0 低 / 1 中 / 2 高);返回 -1 表示未知。
std::function<int(SysTime)> energyAt;
};
struct Result
+1
View File
@@ -76,6 +76,7 @@ int main(int argc, char* argv[])
ScheduleService scheduleService(store, settings.deviceId());
NotificationService notificationService(scheduleService);
notificationService.setLeadMinutes(settings.reminderLeadMinutes());
AIService aiService(scheduleService, store, settings);
SyncService syncService(scheduleService, store, settings);
+99 -1
View File
@@ -3,12 +3,43 @@
#include <QAction>
#include <QSystemTrayIcon>
#ifdef Q_OS_LINUX
#include <QDBusConnection>
#include <QDBusInterface>
#include <QDBusReply>
#include <QStringList>
#include <QVariantMap>
#endif
#include "ElaMenu.h"
#include "ui/AppIcon.h"
SystemTray::SystemTray(QObject* parent)
: QObject(parent)
{
#ifdef Q_OS_LINUX
m_notifications = new QDBusInterface(QStringLiteral("org.freedesktop.Notifications"),
QStringLiteral("/org/freedesktop/Notifications"),
QStringLiteral("org.freedesktop.Notifications"),
QDBusConnection::sessionBus(),
this);
if (m_notifications->isValid())
{
QDBusConnection::sessionBus().connect(QStringLiteral("org.freedesktop.Notifications"),
QStringLiteral("/org/freedesktop/Notifications"),
QStringLiteral("org.freedesktop.Notifications"),
QStringLiteral("ActionInvoked"),
this,
SLOT(handleDbusAction(uint, QString)));
QDBusConnection::sessionBus().connect(QStringLiteral("org.freedesktop.Notifications"),
QStringLiteral("/org/freedesktop/Notifications"),
QStringLiteral("org.freedesktop.Notifications"),
QStringLiteral("NotificationClosed"),
this,
SLOT(handleDbusClosed(uint, uint)));
}
#endif
if (!QSystemTrayIcon::isSystemTrayAvailable())
{
return;
@@ -33,7 +64,18 @@ SystemTray::SystemTray(QObject* parent)
break;
}
});
connect(m_trayIcon, &QSystemTrayIcon::messageClicked, this, &SystemTray::showRequested);
connect(m_trayIcon, &QSystemTrayIcon::messageClicked, this, [this]() {
if (!m_pendingBlockId.isEmpty())
{
const QString blockId = m_pendingBlockId;
m_pendingBlockId.clear();
Q_EMIT notificationClicked(blockId);
}
else
{
Q_EMIT showRequested();
}
});
}
SystemTray::~SystemTray()
@@ -73,13 +115,69 @@ void SystemTray::hide()
void SystemTray::showNotification(const QString& title, const QString& message, int timeoutMs)
{
showNotification(title, message, timeoutMs, QString());
}
void SystemTray::showNotification(const QString& title,
const QString& message,
int timeoutMs,
const QString& blockId)
{
#ifdef Q_OS_LINUX
if (m_notifications && m_notifications->isValid())
{
QStringList actions;
actions << QStringLiteral("default")
<< (blockId.isEmpty() ? QStringLiteral("打开应用") : QStringLiteral("打开日程"));
QVariantMap hints;
hints.insert(QStringLiteral("desktop-entry"), QStringLiteral("Schedule"));
const QDBusReply<uint> reply = m_notifications->call(QStringLiteral("Notify"),
QStringLiteral("AI 日程"),
0u,
QStringLiteral("x-office-calendar"),
title,
message,
actions,
hints,
timeoutMs);
if (reply.isValid())
{
m_dbusTargets.insert(reply.value(), blockId);
return;
}
}
#endif
if (!m_trayIcon || !m_trayIcon->isVisible())
{
return;
}
m_pendingBlockId = blockId;
m_trayIcon->showMessage(title, message, QSystemTrayIcon::Information, timeoutMs);
}
void SystemTray::handleDbusAction(uint id, const QString& key)
{
if (!key.isEmpty() && key != QStringLiteral("default"))
{
return;
}
const QString blockId = m_dbusTargets.take(id);
if (!blockId.isEmpty())
{
Q_EMIT notificationClicked(blockId);
}
else
{
Q_EMIT showRequested();
}
}
void SystemTray::handleDbusClosed(uint id, uint reason)
{
Q_UNUSED(reason)
m_dbusTargets.remove(id);
}
void SystemTray::setOverdueCount(int count)
{
m_overdueCount = count;
+15
View File
@@ -1,5 +1,6 @@
#pragma once
#include <QHash>
#include <QObject>
#include <QString>
@@ -27,12 +28,21 @@ public:
void hide();
void showNotification(const QString& title, const QString& message, int timeoutMs = 6000);
void showNotification(const QString& title,
const QString& message,
int timeoutMs,
const QString& blockId);
void setOverdueCount(int count);
signals:
void showRequested();
void newBlockRequested();
void quitRequested();
void notificationClicked(const QString& blockId);
private slots:
void handleDbusAction(uint id, const QString& key);
void handleDbusClosed(uint id, uint reason);
private:
void rebuildMenu();
@@ -41,4 +51,9 @@ private:
ElaMenu* m_menu = nullptr;
QAction* m_statusAction = nullptr;
int m_overdueCount = 0;
QString m_pendingBlockId;
QHash<uint, QString> m_dbusTargets;
#ifdef Q_OS_LINUX
class QDBusInterface* m_notifications = nullptr;
#endif
};
+51 -1
View File
@@ -32,7 +32,8 @@ void NotificationService::stop()
void NotificationService::checkNow()
{
const QVector<ScheduleItem> current = m_scheduleService.overdueItems(QDateTime::currentDateTime());
const QDateTime now = QDateTime::currentDateTime();
const QVector<ScheduleItem> current = m_scheduleService.overdueItems(now);
QSet<QString> currentIds;
currentIds.reserve(current.size());
@@ -84,6 +85,55 @@ void NotificationService::checkNow()
{
Q_EMIT overdueListChanged(m_overdueItems);
}
const QVector<ScheduleItem> upcoming =
m_scheduleService.itemsForRange(now.date().addDays(-1), now.date().addDays(2));
for (const ScheduleItem& item : upcoming)
{
if (item.block.status != QStringLiteral("scheduled") &&
item.block.status != QStringLiteral("in_progress"))
{
continue;
}
if (!item.block.startAt.isValid() || !item.block.endAt.isValid())
{
continue;
}
const QString startKey = QStringLiteral("%1@%2")
.arg(item.block.id,
item.block.startAt.toUTC().toString(Qt::ISODateWithMs));
if (m_leadMinutes > 0 && now >= item.block.startAt.addSecs(-m_leadMinutes * 60) &&
now < item.block.startAt)
{
const QString leadKey = QStringLiteral("%1@%2").arg(startKey).arg(m_leadMinutes);
if (!m_leadNotifiedKeys.contains(leadKey))
{
m_leadNotifiedKeys.insert(leadKey);
Q_EMIT leadReminderDue(item, m_leadMinutes);
}
}
if (now >= item.block.startAt &&
now < item.block.endAt &&
now < item.block.startAt.addSecs(10 * 60))
{
const QString key = startKey + QStringLiteral("@start");
if (!m_startNotifiedKeys.contains(key))
{
m_startNotifiedKeys.insert(key);
Q_EMIT startReminderDue(item);
}
}
}
}
int NotificationService::leadMinutes() const
{
return m_leadMinutes;
}
void NotificationService::setLeadMinutes(int minutes)
{
m_leadMinutes = qBound(0, minutes, 24 * 60);
}
QVector<ScheduleItem> NotificationService::overdueItems() const
@@ -26,13 +26,21 @@ public:
void checkNow();
QVector<ScheduleItem> overdueItems() const;
int leadMinutes() const;
void setLeadMinutes(int minutes);
signals:
void overdueDetected(const ScheduleItem& item);
void leadReminderDue(const ScheduleItem& item, int minutesBefore);
void startReminderDue(const ScheduleItem& item);
void overdueListChanged(const QVector<ScheduleItem>& items);
private:
ScheduleService& m_scheduleService;
QTimer m_timer;
QSet<QString> m_notifiedIds;
QSet<QString> m_leadNotifiedKeys;
QSet<QString> m_startNotifiedKeys;
QVector<ScheduleItem> m_overdueItems;
int m_leadMinutes = 10;
};
+554 -1
View File
@@ -9,6 +9,7 @@
#include <algorithm>
#include "core/DailyInsights.h"
#include "core/DateTimeUtils.h"
#include "storage/SqliteStore.h"
@@ -21,6 +22,36 @@ QDateTime truncateToMinute(const QDateTime& value)
{
return QDateTime(value.date(), QTime(value.time().hour(), value.time().minute()), value.timeSpec());
}
QString energySummaryForDate(const EnergyProfile& profile, const QDate& date)
{
if (!date.isValid())
{
return {};
}
QStringList windows;
int runStart = -1;
for (int hour = 0; hour <= 24; ++hour)
{
const bool high = hour < 24 && profile.level(date.dayOfWeek(), hour) == 2;
if (high && runStart < 0)
{
runStart = hour;
}
else if (!high && runStart >= 0)
{
windows.append(QStringLiteral("%1:00–%2:00")
.arg(runStart, 2, 10, QLatin1Char('0'))
.arg(hour, 2, 10, QLatin1Char('0')));
runStart = -1;
}
}
if (windows.isEmpty())
{
return QStringLiteral("今天没有明显的高精力时段");
}
return QStringLiteral("精力高峰:%1").arg(windows.join(QStringLiteral("、")));
}
} // namespace
ScheduleService::ScheduleService(SqliteStore& store, QString deviceId, QObject* parent)
@@ -28,6 +59,7 @@ ScheduleService::ScheduleService(SqliteStore& store, QString deviceId, QObject*
, m_store(store)
, m_deviceId(std::move(deviceId))
{
rebuildEnergyProfile();
}
bool ScheduleService::validateRange(const QDateTime& start, const QDateTime& end, QString* error)
@@ -154,6 +186,376 @@ bool ScheduleService::createBlock(const QString& title,
return true;
}
bool ScheduleService::createRecurringBlock(const QString& title,
const QDateTime& start,
const QDateTime& end,
RecurrenceFrequency frequency,
const QDate& until,
int* createdCount,
QString* error)
{
if (createdCount)
{
*createdCount = 0;
}
if (frequency == RecurrenceFrequency::None)
{
return createBlock(title, start, end, error);
}
const QDateTime normalizedStart = truncateToMinute(start);
const QDateTime normalizedEnd = truncateToMinute(end);
if (!validateRange(normalizedStart, normalizedEnd, error))
{
return false;
}
if (!until.isValid() || until < normalizedStart.date())
{
m_lastError = QStringLiteral("重复结束日期必须不早于开始日期");
if (error)
{
*error = m_lastError;
}
return false;
}
const QDate firstDate = normalizedStart.date();
const QDate horizon = firstDate.addDays(366);
const QDate effectiveUntil = std::min(until, horizon);
const int durationSeconds = DateTimeUtils::minutesBetween(normalizedStart, normalizedEnd) * 60;
QVector<QDateTime> candidates;
candidates.reserve(64);
for (int index = 0; index < 200; ++index)
{
QDate date;
switch (frequency)
{
case RecurrenceFrequency::Daily:
date = firstDate.addDays(index);
break;
case RecurrenceFrequency::Weekly:
date = firstDate.addDays(index * 7);
break;
case RecurrenceFrequency::Monthly:
date = firstDate.addMonths(index);
break;
case RecurrenceFrequency::None:
break;
}
if (!date.isValid() || date > effectiveUntil)
{
break;
}
candidates.append(QDateTime(date, normalizedStart.time(), normalizedStart.timeSpec()));
}
if (candidates.isEmpty())
{
m_lastError = QStringLiteral("没有生成有效的重复日期");
if (error)
{
*error = m_lastError;
}
return false;
}
const QDateTime lastEnd = candidates.last().addSecs(durationSeconds);
const QVector<ScheduleItem> existing =
m_store.blocksInRange(DateTimeUtils::localDayStartUtc(firstDate),
DateTimeUtils::localDayEndUtc(lastEnd.date()));
QVector<QPair<QDateTime, QDateTime>> busy;
for (const ScheduleItem& item : existing)
{
if (item.block.status == QStringLiteral("dropped") ||
item.block.status == QStringLiteral("missed"))
{
continue;
}
busy.append({item.block.startAt, item.block.endAt});
}
QVector<QDateTime> accepted;
for (const QDateTime& occurrence : candidates)
{
const QDateTime occurrenceEnd = occurrence.addSecs(durationSeconds);
const bool conflict = std::any_of(busy.cbegin(), busy.cend(), [&](const auto& interval) {
return occurrence < interval.second && occurrenceEnd > interval.first;
});
if (conflict)
{
continue;
}
accepted.append(occurrence);
busy.append({occurrence, occurrenceEnd});
}
if (accepted.isEmpty())
{
m_lastError = QStringLiteral("重复日程的时段均已被占用");
if (error)
{
*error = m_lastError;
}
return false;
}
const QDateTime now = QDateTime::currentDateTime();
Task task;
task.id = newId();
task.title = title.trimmed().isEmpty() ? QStringLiteral("未命名日程") : title.trimmed();
task.source = QStringLiteral("manual");
task.estimatedMin = durationSeconds / 60;
task.createdAt = now;
task.updatedAt = now;
task.version = 0;
task.deviceId = m_deviceId;
QVector<TimeBlock> blocks;
blocks.reserve(accepted.size());
for (const QDateTime& occurrence : accepted)
{
TimeBlock block;
block.id = newId();
block.taskId = task.id;
block.startAt = occurrence;
block.endAt = occurrence.addSecs(durationSeconds);
block.createdAt = now;
block.updatedAt = now;
block.version = 0;
block.deviceId = m_deviceId;
blocks.append(block);
}
Recurrence recurrence;
recurrence.id = newId();
recurrence.taskId = task.id;
recurrence.rule = frequency == RecurrenceFrequency::Daily
? QStringLiteral("FREQ=DAILY")
: (frequency == RecurrenceFrequency::Weekly ? QStringLiteral("FREQ=WEEKLY")
: QStringLiteral("FREQ=MONTHLY"));
recurrence.until = effectiveUntil;
if (!m_store.beginTransaction())
{
m_lastError = m_store.lastError();
if (error)
{
*error = m_lastError;
}
return false;
}
if (!m_store.insertTask(task))
{
m_store.rollback();
m_lastError = m_store.lastError();
if (error)
{
*error = m_lastError;
}
return false;
}
for (const TimeBlock& block : blocks)
{
if (!m_store.insertTimeBlock(block))
{
m_store.rollback();
m_lastError = m_store.lastError();
if (error)
{
*error = m_lastError;
}
return false;
}
}
if (!m_store.insertRecurrence(recurrence))
{
m_store.rollback();
m_lastError = m_store.lastError();
if (error)
{
*error = m_lastError;
}
return false;
}
if (!m_store.commit())
{
m_store.rollback();
m_lastError = m_store.lastError();
if (error)
{
*error = m_lastError;
}
return false;
}
if (createdCount)
{
*createdCount = accepted.size();
}
m_lastError.clear();
Q_EMIT dataChanged();
return true;
}
bool ScheduleService::createProject(const QString& title,
const QString& description,
const QDate& deadline,
QString* error)
{
if (title.trimmed().isEmpty())
{
m_lastError = QStringLiteral("项目标题不能为空");
if (error)
{
*error = m_lastError;
}
return false;
}
if (!deadline.isValid())
{
m_lastError = QStringLiteral("长期项目需要截止日期");
if (error)
{
*error = m_lastError;
}
return false;
}
const QDateTime now = QDateTime::currentDateTime();
Project project;
project.id = newId();
project.title = title.trimmed().left(200);
project.description = description.trimmed().left(2000);
project.source = QStringLiteral("manual");
project.deadline = deadline;
project.priority = 1;
project.status = QStringLiteral("active");
project.createdAt = now;
project.updatedAt = now;
project.version = 0;
project.deviceId = m_deviceId;
if (!m_store.insertProject(project))
{
m_lastError = m_store.lastError();
if (error)
{
*error = m_lastError;
}
return false;
}
m_lastError.clear();
Q_EMIT dataChanged();
return true;
}
bool ScheduleService::updateProject(const QString& projectId,
const QString& title,
const QString& description,
const QDate& deadline,
QString* error)
{
auto project = m_store.projectById(projectId);
if (!project.has_value())
{
m_lastError = QStringLiteral("长期项目不存在: %1").arg(projectId);
if (error)
{
*error = m_lastError;
}
return false;
}
if (title.trimmed().isEmpty() || !deadline.isValid())
{
m_lastError = QStringLiteral("长期项目标题或截止日期无效");
if (error)
{
*error = m_lastError;
}
return false;
}
project->title = title.trimmed().left(200);
project->description = description.trimmed().left(2000);
project->deadline = deadline;
project->updatedAt = QDateTime::currentDateTime();
project->version += 1;
project->deviceId = m_deviceId;
if (!m_store.updateProject(*project))
{
m_lastError = m_store.lastError();
if (error)
{
*error = m_lastError;
}
return false;
}
m_lastError.clear();
Q_EMIT dataChanged();
return true;
}
bool ScheduleService::setProjectStatus(const QString& projectId, const QString& status, QString* error)
{
if (status != QStringLiteral("active") && status != QStringLiteral("done"))
{
m_lastError = QStringLiteral("非法长期项目状态: %1").arg(status);
if (error)
{
*error = m_lastError;
}
return false;
}
auto project = m_store.projectById(projectId);
if (!project.has_value())
{
m_lastError = QStringLiteral("长期项目不存在: %1").arg(projectId);
if (error)
{
*error = m_lastError;
}
return false;
}
project->status = status;
project->updatedAt = QDateTime::currentDateTime();
project->version += 1;
project->deviceId = m_deviceId;
if (!m_store.updateProject(*project))
{
m_lastError = m_store.lastError();
if (error)
{
*error = m_lastError;
}
return false;
}
m_lastError.clear();
Q_EMIT dataChanged();
return true;
}
bool ScheduleService::deleteProject(const QString& projectId, QString* error)
{
if (!m_store.deleteProject(projectId))
{
m_lastError = m_store.lastError();
if (error)
{
*error = m_lastError;
}
return false;
}
m_lastError.clear();
Q_EMIT dataChanged();
return true;
}
QVector<Project> ScheduleService::projects() const
{
return m_store.projects(false);
}
std::optional<Project> ScheduleService::projectById(const QString& projectId) const
{
return m_store.projectById(projectId);
}
bool ScheduleService::updateBlock(const QString& blockId,
const QString& title,
const QDateTime& start,
@@ -315,6 +717,7 @@ bool ScheduleService::setBlockStatus(const QString& blockId, const QString& stat
return false;
}
m_lastError.clear();
rebuildEnergyProfile();
Q_EMIT dataChanged();
return true;
}
@@ -404,6 +807,7 @@ bool ScheduleService::deleteBlock(const QString& blockId, QString* error)
}
m_lastError.clear();
rebuildEnergyProfile();
Q_EMIT dataChanged();
return true;
}
@@ -444,10 +848,15 @@ bool ScheduleService::applyProposedDiff(const ProposedDiff& diff,
QString blockId;
QString taskId;
};
struct PendingProject
{
Project project;
};
QVector<PendingCreate> creates;
QVector<PendingUpdate> updates;
QVector<PendingDelete> deletes;
QVector<PendingProject> projects;
QSet<QString> updatedBlockIds;
QSet<QString> deletedBlockIds;
const QDateTime now = QDateTime::currentDateTime();
@@ -689,7 +1098,44 @@ bool ScheduleService::applyProposedDiff(const ProposedDiff& diff,
deletedBlockIds.insert(blockId);
}
if (creates.isEmpty() && updates.isEmpty() && deletes.isEmpty())
const QJsonArray projectArray = diff.payload.value(QStringLiteral("projects")).toArray();
for (const QJsonValue& value : projectArray)
{
const QJsonObject object = value.toObject();
const QString tempId = object.value(QStringLiteral("temp_id")).toString();
if (!accepted.contains(tempId))
{
continue;
}
const QString title = object.value(QStringLiteral("title")).toString().trimmed();
const QString deadlineText = object.value(QStringLiteral("deadline")).toString().trimmed();
const QDate deadline = QDate::fromString(deadlineText.left(10), Qt::ISODate);
if (title.isEmpty() || !deadline.isValid())
{
m_lastError = QStringLiteral("AI 提议中的长期项目数据无效: %1").arg(tempId);
if (error)
{
*error = m_lastError;
}
return false;
}
Project project;
project.id = newId();
project.title = title.left(200);
project.description = object.value(QStringLiteral("description")).toString().left(2000);
project.source = QStringLiteral("ai_chat");
project.sourceRef = object.value(QStringLiteral("source_ref")).toString();
project.deadline = deadline;
project.priority = qBound(1, object.value(QStringLiteral("priority")).toInt(2), 5);
project.status = QStringLiteral("active");
project.createdAt = now;
project.updatedAt = now;
project.version = 0;
project.deviceId = m_deviceId;
projects.append({project});
}
if (creates.isEmpty() && updates.isEmpty() && deletes.isEmpty() && projects.isEmpty())
{
m_lastError = QStringLiteral("AI 提议中没有选中的有效操作");
if (error)
@@ -877,6 +1323,20 @@ bool ScheduleService::applyProposedDiff(const ProposedDiff& diff,
}
}
for (const PendingProject& entry : projects)
{
if (!m_store.insertProject(entry.project))
{
m_store.rollback();
m_lastError = m_store.lastError();
if (error)
{
*error = m_lastError;
}
return false;
}
}
if (!m_store.commit())
{
m_store.rollback();
@@ -889,6 +1349,7 @@ bool ScheduleService::applyProposedDiff(const ProposedDiff& diff,
}
m_lastError.clear();
rebuildEnergyProfile();
Q_EMIT dataChanged();
return true;
}
@@ -900,6 +1361,21 @@ bool ScheduleService::applyProposedCreates(const ProposedDiff& diff,
return applyProposedDiff(diff, acceptedTempIds, error);
}
std::optional<ScheduleItem> ScheduleService::itemForBlock(const QString& blockId) const
{
const auto block = m_store.timeBlockById(blockId);
if (!block.has_value())
{
return std::nullopt;
}
const auto task = m_store.taskById(block->taskId);
if (!task.has_value())
{
return std::nullopt;
}
return ScheduleItem{*task, *block};
}
QVector<ScheduleItem> ScheduleService::itemsForDay(const QDate& date) const
{
auto items = m_store.blocksInRange(DateTimeUtils::localDayStartUtc(date),
@@ -941,6 +1417,46 @@ QVector<ScheduleItem> ScheduleService::overdueItems(const QDateTime& now) const
return items;
}
QVector<ScheduleItem> ScheduleService::search(const QString& query, int limit) const
{
return m_store.search(query, limit);
}
QVector<ScheduleItem> ScheduleService::completedItems(const QDate& from, const QDate& to) const
{
if (!from.isValid() || !to.isValid() || from > to)
{
return {};
}
return m_store.completedBlocks(DateTimeUtils::localDayStartUtc(from),
DateTimeUtils::localDayEndUtc(to));
}
QVector<Project> ScheduleService::completedProjects(const QDate& from, const QDate& to) const
{
if (!from.isValid() || !to.isValid() || from > to)
{
return {};
}
QVector<Project> result;
for (const Project& project : m_store.projects(true))
{
if (project.status != QStringLiteral("done"))
{
continue;
}
const QDate completed = project.updatedAt.date();
if (completed >= from && completed <= to)
{
result.append(project);
}
}
std::sort(result.begin(), result.end(), [](const Project& a, const Project& b) {
return a.updatedAt > b.updatedAt;
});
return result;
}
QString ScheduleService::lastError() const
{
return m_lastError;
@@ -948,5 +1464,42 @@ QString ScheduleService::lastError() const
void ScheduleService::notifyDataChanged()
{
rebuildEnergyProfile();
Q_EMIT dataChanged();
}
const EnergyProfile& ScheduleService::energyProfile() const
{
return m_energyProfile;
}
int ScheduleService::energyLevelFor(const QDateTime& localDateTime) const
{
return m_energyProfile.level(localDateTime);
}
DailyReview ScheduleService::dailyReview(const QDate& date) const
{
QDateTime now = QDateTime::currentDateTime();
if (date != now.date())
{
now = date < now.date() ? QDateTime(date, QTime(23, 59), Qt::LocalTime)
: QDateTime(date, QTime(0, 0), Qt::LocalTime);
}
DailyReview review = buildDailyReview(itemsForDay(date), date, now);
review.energySummary = energySummaryForDate(m_energyProfile, date);
return review;
}
QVector<Suggestion> ScheduleService::suggestions(const QDateTime& now) const
{
return buildSuggestions(itemsForDay(now.date()), now);
}
void ScheduleService::rebuildEnergyProfile()
{
EnergyProfile profile = EnergyProfile::defaults();
profile.learn(m_store.completedEnergySamples());
m_energyProfile = profile;
m_store.replaceEnergyLevels(m_energyProfile.levels());
}
+37
View File
@@ -5,7 +5,11 @@
#include <QString>
#include <QVector>
#include "core/DailyInsights.h"
#include "core/EnergyProfile.h"
#include "core/Project.h"
#include "core/ProposedDiff.h"
#include "core/Recurrence.h"
#include "core/ScheduleItem.h"
class SqliteStore;
@@ -26,6 +30,26 @@ public:
const QDateTime& start,
const QDateTime& end,
QString* error = nullptr);
bool createProject(const QString& title,
const QString& description,
const QDate& deadline,
QString* error = nullptr);
bool updateProject(const QString& projectId,
const QString& title,
const QString& description,
const QDate& deadline,
QString* error = nullptr);
bool setProjectStatus(const QString& projectId, const QString& status, QString* error = nullptr);
bool deleteProject(const QString& projectId, QString* error = nullptr);
QVector<Project> projects() const;
std::optional<Project> projectById(const QString& projectId) const;
bool createRecurringBlock(const QString& title,
const QDateTime& start,
const QDateTime& end,
RecurrenceFrequency frequency,
const QDate& until,
int* createdCount = nullptr,
QString* error = nullptr);
bool updateBlock(const QString& blockId,
const QString& title,
const QDateTime& start,
@@ -48,10 +72,22 @@ public:
QString* error = nullptr);
QVector<ScheduleItem> itemsForDay(const QDate& date) const;
std::optional<ScheduleItem> itemForBlock(const QString& blockId) const;
// 返回 [from, to] 闭区间内的所有日程,按开始时间升序。
QVector<ScheduleItem> itemsForRange(const QDate& from, const QDate& to) const;
QVector<ScheduleItem> overdueItems(const QDateTime& now = QDateTime::currentDateTime()) const;
QVector<ScheduleItem> search(const QString& query, int limit = 100) const;
QVector<ScheduleItem> completedItems(const QDate& from, const QDate& to) const;
QVector<Project> completedProjects(const QDate& from, const QDate& to) const;
QString lastError() const;
const EnergyProfile& energyProfile() const;
int energyLevelFor(const QDateTime& localDateTime) const;
void rebuildEnergyProfile();
DailyReview dailyReview(const QDate& date) const;
QVector<Suggestion> suggestions(const QDateTime& now = QDateTime::currentDateTime()) const;
// 供同步层在外部写入后通知 UI 刷新。
void notifyDataChanged();
@@ -67,4 +103,5 @@ private:
SqliteStore& m_store;
QString m_deviceId;
QString m_lastError;
EnergyProfile m_energyProfile;
};
+46 -1
View File
@@ -180,7 +180,52 @@ QVector<Migration> all()
" VALUES('timeblock', OLD.id, 'delete', %1, %2); END")
.arg(blockDeletePayload, nowExpression),
};
migrations.append(v3);
Migration v4;
v4.version = 4;
v4.name = QStringLiteral("long_term_projects");
const QString projectJson = QStringLiteral(
"json_object('id',%1.id,'title',%1.title,'description',%1.description,'source',%1.source,"
"'source_ref',%1.source_ref,'deadline',%1.deadline,'priority',%1.priority,'status',%1.status,"
"'created_at',%1.created_at,'updated_at',%1.updated_at,'version',%1.version,'device_id',%1.device_id)");
const QString projectNow = QStringLiteral("strftime('%Y-%m-%dT%H:%M:%fZ','now')");
v4.statements = {
QStringLiteral(
"CREATE TABLE IF NOT EXISTS project ("
" id TEXT PRIMARY KEY,"
" title TEXT NOT NULL,"
" description TEXT,"
" source TEXT,"
" source_ref TEXT,"
" deadline TEXT,"
" priority INTEGER DEFAULT 1,"
" status TEXT DEFAULT 'active',"
" created_at TEXT NOT NULL,"
" updated_at TEXT NOT NULL,"
" version INTEGER DEFAULT 0,"
" device_id TEXT NOT NULL"
")"),
QStringLiteral("CREATE INDEX IF NOT EXISTS idx_project_deadline ON project(status, deadline)"),
QStringLiteral(
"CREATE TRIGGER IF NOT EXISTS trg_project_outbox_insert AFTER INSERT ON project "
"WHEN NOT EXISTS (SELECT 1 FROM sync_remote_apply) BEGIN "
" INSERT INTO sync_outbox(entity_type, entity_id, op, payload, created_at) "
" VALUES('project', NEW.id, 'upsert', %1, NEW.updated_at); END")
.arg(projectJson.arg("NEW")),
QStringLiteral(
"CREATE TRIGGER IF NOT EXISTS trg_project_outbox_update AFTER UPDATE ON project "
"WHEN NOT EXISTS (SELECT 1 FROM sync_remote_apply) BEGIN "
" INSERT INTO sync_outbox(entity_type, entity_id, op, payload, created_at) "
" VALUES('project', NEW.id, 'upsert', %1, NEW.updated_at); END")
.arg(projectJson.arg("NEW")),
QStringLiteral(
"CREATE TRIGGER IF NOT EXISTS trg_project_outbox_delete AFTER DELETE ON project "
"WHEN NOT EXISTS (SELECT 1 FROM sync_remote_apply) BEGIN "
" INSERT INTO sync_outbox(entity_type, entity_id, op, payload, created_at) "
" VALUES('project', OLD.id, 'delete', json_set(%1, '$.updated_at', %2), %2); END")
.arg(projectJson.arg("OLD"), projectNow),
};
migrations.append(v4);
return migrations;
}
+462 -4
View File
@@ -1,5 +1,7 @@
#include "SqliteStore.h"
#include <algorithm>
#include <QDir>
#include <QJsonDocument>
#include <QFileInfo>
@@ -85,6 +87,36 @@ TimeBlock mapTimeBlock(const QSqlQuery& query, int offset)
return block;
}
Project mapProject(const QSqlQuery& query, int offset = 0)
{
Project project;
project.id = query.value(offset + 0).toString();
project.title = query.value(offset + 1).toString();
project.description = query.value(offset + 2).toString();
project.source = query.value(offset + 3).toString();
project.sourceRef = query.value(offset + 4).toString();
const QVariant deadline = query.value(offset + 5);
if (!deadline.isNull())
{
const QDate date = QDate::fromString(deadline.toString(), Qt::ISODate);
if (date.isValid())
{
project.deadline = date;
}
}
project.priority = query.value(offset + 6).toInt();
project.status = query.value(offset + 7).toString();
project.createdAt = DateTimeUtils::fromDb(query.value(offset + 8).toString());
project.updatedAt = DateTimeUtils::fromDb(query.value(offset + 9).toString());
project.version = query.value(offset + 10).toInt();
project.deviceId = query.value(offset + 11).toString();
return project;
}
constexpr const char* kProjectColumns =
"p.id, p.title, p.description, p.source, p.source_ref, p.deadline, p.priority, p.status, "
"p.created_at, p.updated_at, p.version, p.device_id";
constexpr const char* kTaskColumns =
"t.id, t.title, t.description, t.source, t.source_ref, t.estimated_min, t.energy_req, "
"t.deadline, t.priority, t.status, t.created_at, t.updated_at, t.version, t.device_id";
@@ -500,6 +532,141 @@ bool SqliteStore::hasBlocksForTask(const QString& taskId)
return query.next();
}
bool SqliteStore::insertProject(const Project& project)
{
m_lastError.clear();
if (!isOpenInternal())
{
return setError(QStringLiteral("数据库未打开"));
}
QSqlQuery query(m_database);
query.prepare(QStringLiteral(
"INSERT INTO project (id, title, description, source, source_ref, deadline, priority, "
"status, created_at, updated_at, version, device_id) "
"VALUES (:id, :title, :description, :source, :source_ref, :deadline, :priority, "
":status, :created_at, :updated_at, :version, :device_id)"));
query.bindValue(QStringLiteral(":id"), project.id);
query.bindValue(QStringLiteral(":title"), project.title);
query.bindValue(QStringLiteral(":description"), project.description);
query.bindValue(QStringLiteral(":source"), project.source);
query.bindValue(QStringLiteral(":source_ref"), project.sourceRef);
query.bindValue(QStringLiteral(":deadline"),
project.deadline.has_value() ? QVariant(project.deadline->toString(Qt::ISODate))
: QVariant());
query.bindValue(QStringLiteral(":priority"), project.priority);
query.bindValue(QStringLiteral(":status"), project.status);
query.bindValue(QStringLiteral(":created_at"), DateTimeUtils::toDb(project.createdAt));
query.bindValue(QStringLiteral(":updated_at"), DateTimeUtils::toDb(project.updatedAt));
query.bindValue(QStringLiteral(":version"), project.version);
query.bindValue(QStringLiteral(":device_id"), project.deviceId);
if (!query.exec())
{
return setError(QStringLiteral("插入长期项目失败: %1").arg(query.lastError().text()));
}
return true;
}
bool SqliteStore::updateProject(const Project& project)
{
m_lastError.clear();
if (!isOpenInternal())
{
return setError(QStringLiteral("数据库未打开"));
}
QSqlQuery query(m_database);
query.prepare(QStringLiteral(
"UPDATE project SET title = :title, description = :description, source = :source, "
"source_ref = :source_ref, deadline = :deadline, priority = :priority, status = :status, "
"updated_at = :updated_at, version = :version, device_id = :device_id WHERE id = :id"));
query.bindValue(QStringLiteral(":title"), project.title);
query.bindValue(QStringLiteral(":description"), project.description);
query.bindValue(QStringLiteral(":source"), project.source);
query.bindValue(QStringLiteral(":source_ref"), project.sourceRef);
query.bindValue(QStringLiteral(":deadline"),
project.deadline.has_value() ? QVariant(project.deadline->toString(Qt::ISODate))
: QVariant());
query.bindValue(QStringLiteral(":priority"), project.priority);
query.bindValue(QStringLiteral(":status"), project.status);
query.bindValue(QStringLiteral(":updated_at"), DateTimeUtils::toDb(project.updatedAt));
query.bindValue(QStringLiteral(":version"), project.version);
query.bindValue(QStringLiteral(":device_id"), project.deviceId);
query.bindValue(QStringLiteral(":id"), project.id);
if (!query.exec())
{
return setError(QStringLiteral("更新长期项目失败: %1").arg(query.lastError().text()));
}
return true;
}
bool SqliteStore::deleteProject(const QString& id)
{
m_lastError.clear();
if (!isOpenInternal())
{
return setError(QStringLiteral("数据库未打开"));
}
QSqlQuery query(m_database);
query.prepare(QStringLiteral("DELETE FROM project WHERE id = :id"));
query.bindValue(QStringLiteral(":id"), id);
if (!query.exec())
{
return setError(QStringLiteral("删除长期项目失败: %1").arg(query.lastError().text()));
}
return true;
}
std::optional<Project> SqliteStore::projectById(const QString& id) const
{
m_lastError.clear();
if (!isOpenInternal())
{
setError(QStringLiteral("数据库未打开"));
return std::nullopt;
}
QSqlQuery query(m_database);
query.prepare(QStringLiteral("SELECT %1 FROM project p WHERE p.id = :id")
.arg(QString::fromLatin1(kProjectColumns)));
query.bindValue(QStringLiteral(":id"), id);
if (!query.exec())
{
setError(QStringLiteral("查询长期项目失败: %1").arg(query.lastError().text()));
return std::nullopt;
}
if (!query.next())
{
return std::nullopt;
}
return mapProject(query);
}
QVector<Project> SqliteStore::projects(bool includeDone) const
{
m_lastError.clear();
QVector<Project> result;
if (!isOpenInternal())
{
setError(QStringLiteral("数据库未打开"));
return result;
}
QSqlQuery query(m_database);
const QString sql = QStringLiteral(
"SELECT %1 FROM project p %2 "
"ORDER BY CASE WHEN p.deadline IS NULL THEN 1 ELSE 0 END, "
"p.deadline ASC, p.priority DESC, p.title ASC")
.arg(QString::fromLatin1(kProjectColumns),
includeDone ? QString() : QStringLiteral("WHERE p.status = 'active'"));
if (!query.exec(sql))
{
setError(QStringLiteral("查询长期项目失败: %1").arg(query.lastError().text()));
return result;
}
while (query.next())
{
result.append(mapProject(query));
}
return result;
}
bool SqliteStore::insertTimeBlock(const TimeBlock& block)
{
m_lastError.clear();
@@ -914,7 +1081,9 @@ bool SqliteStore::applyRemoteChange(const RemoteChange& change, QString* error)
{
return setError(QStringLiteral("数据库未打开"));
}
if (change.entityType != QStringLiteral("task") && change.entityType != QStringLiteral("timeblock"))
if (change.entityType != QStringLiteral("task") &&
change.entityType != QStringLiteral("timeblock") &&
change.entityType != QStringLiteral("project"))
{
return true;
}
@@ -929,7 +1098,8 @@ bool SqliteStore::applyRemoteChange(const RemoteChange& change, QString* error)
QSqlQuery current(m_database);
const QString table = change.entityType == QStringLiteral("task")
? QStringLiteral("task")
: QStringLiteral("timeblock");
: (change.entityType == QStringLiteral("project") ? QStringLiteral("project")
: QStringLiteral("timeblock"));
current.prepare(QStringLiteral("SELECT updated_at FROM %1 WHERE id = :id").arg(table));
current.bindValue(QStringLiteral(":id"), change.entityId);
if (!current.exec())
@@ -957,7 +1127,8 @@ bool SqliteStore::applyRemoteChange(const RemoteChange& change, QString* error)
const QString table = change.entityType == QStringLiteral("task")
? QStringLiteral("task")
: QStringLiteral("timeblock");
: (change.entityType == QStringLiteral("project") ? QStringLiteral("project")
: QStringLiteral("timeblock"));
QSqlQuery current(m_database);
current.prepare(QStringLiteral("SELECT updated_at FROM %1 WHERE id = :id").arg(table));
current.bindValue(QStringLiteral(":id"), change.entityId);
@@ -965,7 +1136,26 @@ bool SqliteStore::applyRemoteChange(const RemoteChange& change, QString* error)
{
return setError(QStringLiteral("查询远程 upsert 目标失败: %1").arg(current.lastError().text()));
}
if (current.next() && !remoteWins(current.value(0).toString(), remoteTime, false))
bool hasLocal = current.next();
const QString localUpdated = hasLocal ? current.value(0).toString() : QString();
bool forceCompletion = false;
if (change.entityType == QStringLiteral("timeblock"))
{
const QString remoteStatus = jsonString(change.payload, "status").toString();
if (remoteStatus == QStringLiteral("done"))
{
QSqlQuery statusQuery(m_database);
statusQuery.prepare(QStringLiteral("SELECT status FROM timeblock WHERE id = :id"));
statusQuery.bindValue(QStringLiteral(":id"), change.entityId);
if (statusQuery.exec() && statusQuery.next())
{
const QString localStatus = statusQuery.value(0).toString();
forceCompletion = localStatus == QStringLiteral("scheduled") ||
localStatus == QStringLiteral("in_progress");
}
}
}
if (hasLocal && !forceCompletion && !remoteWins(localUpdated, remoteTime, false))
{
return true;
}
@@ -1007,6 +1197,40 @@ bool SqliteStore::applyRemoteChange(const RemoteChange& change, QString* error)
return true;
}
if (change.entityType == QStringLiteral("project"))
{
const QJsonObject object = change.payload;
QSqlQuery upsert(m_database);
upsert.prepare(QStringLiteral(
"INSERT INTO project (id, title, description, source, source_ref, deadline, priority, "
"status, created_at, updated_at, version, device_id) "
"VALUES (:id, :title, :description, :source, :source_ref, :deadline, :priority, "
":status, :created_at, :updated_at, :version, :device_id) "
"ON CONFLICT(id) DO UPDATE SET title=excluded.title, description=excluded.description, "
"source=excluded.source, source_ref=excluded.source_ref, deadline=excluded.deadline, "
"priority=excluded.priority, status=excluded.status, updated_at=excluded.updated_at, "
"version=excluded.version, device_id=excluded.device_id"));
upsert.bindValue(QStringLiteral(":id"), change.entityId);
upsert.bindValue(QStringLiteral(":title"),
jsonString(object, "title").isValid() ? jsonString(object, "title")
: QVariant(QStringLiteral("未命名项目")));
upsert.bindValue(QStringLiteral(":description"), jsonString(object, "description"));
upsert.bindValue(QStringLiteral(":source"), jsonString(object, "source"));
upsert.bindValue(QStringLiteral(":source_ref"), jsonString(object, "source_ref"));
upsert.bindValue(QStringLiteral(":deadline"), jsonString(object, "deadline"));
upsert.bindValue(QStringLiteral(":priority"), jsonInt(object, "priority"));
upsert.bindValue(QStringLiteral(":status"), jsonString(object, "status"));
upsert.bindValue(QStringLiteral(":created_at"), jsonString(object, "created_at"));
upsert.bindValue(QStringLiteral(":updated_at"), remoteTime);
upsert.bindValue(QStringLiteral(":version"), change.version);
upsert.bindValue(QStringLiteral(":device_id"), change.deviceId);
if (!upsert.exec())
{
return setError(QStringLiteral("应用远程长期项目失败: %1").arg(upsert.lastError().text()));
}
return true;
}
// timeblock
const QJsonObject object = change.payload;
const QString taskId = object.value(QStringLiteral("task_id")).toString();
@@ -1053,6 +1277,240 @@ bool SqliteStore::applyRemoteChange(const RemoteChange& change, QString* error)
return true;
}
bool SqliteStore::insertRecurrence(const Recurrence& recurrence)
{
m_lastError.clear();
if (!isOpenInternal())
{
return setError(QStringLiteral("数据库未打开"));
}
QSqlQuery query(m_database);
query.prepare(QStringLiteral(
"INSERT INTO recurrence(id, task_id, rrule, until) VALUES(:id, :task_id, :rrule, :until)"));
query.bindValue(QStringLiteral(":id"), recurrence.id);
query.bindValue(QStringLiteral(":task_id"), recurrence.taskId);
query.bindValue(QStringLiteral(":rrule"), recurrence.rule);
query.bindValue(QStringLiteral(":until"),
recurrence.until.has_value() ? QVariant(recurrence.until->toString(Qt::ISODate))
: QVariant());
if (!query.exec())
{
return setError(QStringLiteral("写入重复规则失败: %1").arg(query.lastError().text()));
}
return true;
}
std::optional<Recurrence> SqliteStore::recurrenceForTask(const QString& taskId) const
{
m_lastError.clear();
if (!isOpenInternal())
{
setError(QStringLiteral("数据库未打开"));
return std::nullopt;
}
QSqlQuery query(m_database);
query.prepare(QStringLiteral("SELECT id, task_id, rrule, until FROM recurrence WHERE task_id = :task_id"));
query.bindValue(QStringLiteral(":task_id"), taskId);
if (!query.exec())
{
setError(QStringLiteral("查询重复规则失败: %1").arg(query.lastError().text()));
return std::nullopt;
}
if (!query.next())
{
return std::nullopt;
}
Recurrence recurrence;
recurrence.id = query.value(0).toString();
recurrence.taskId = query.value(1).toString();
recurrence.rule = query.value(2).toString();
const QString until = query.value(3).toString();
if (!until.isEmpty())
{
recurrence.until = QDate::fromString(until, Qt::ISODate);
}
return recurrence;
}
QVector<ScheduleItem> SqliteStore::completedBlocks(const QDateTime& fromUtc,
const QDateTime& toUtc) const
{
m_lastError.clear();
QVector<ScheduleItem> items;
if (!isOpenInternal())
{
setError(QStringLiteral("数据库未打开"));
return items;
}
QSqlQuery query(m_database);
query.prepare(QStringLiteral(
"SELECT %1, %2 FROM timeblock b JOIN task t ON t.id = b.task_id "
"WHERE b.status = 'done' "
"AND COALESCE(b.done_at, b.end_at) >= :from "
"AND COALESCE(b.done_at, b.end_at) < :to "
"ORDER BY COALESCE(b.done_at, b.end_at) DESC")
.arg(QString::fromLatin1(kBlockColumns), QString::fromLatin1(kTaskColumns)));
query.bindValue(QStringLiteral(":from"), DateTimeUtils::toDb(fromUtc));
query.bindValue(QStringLiteral(":to"), DateTimeUtils::toDb(toUtc));
if (!query.exec())
{
setError(QStringLiteral("查询已完成日程失败: %1").arg(query.lastError().text()));
return items;
}
while (query.next())
{
ScheduleItem item;
item.block = mapTimeBlock(query, 0);
item.task = mapTask(query, 13);
items.append(item);
}
return items;
}
QVector<ScheduleItem> SqliteStore::search(const QString& query, int limit) const
{
m_lastError.clear();
QVector<ScheduleItem> items;
if (!isOpenInternal())
{
setError(QStringLiteral("数据库未打开"));
return items;
}
QString escaped = query.trimmed();
escaped.replace(QLatin1Char('\\'), QStringLiteral("\\\\"));
escaped.replace(QLatin1Char('%'), QStringLiteral("\\%"));
escaped.replace(QLatin1Char('_'), QStringLiteral("\\_"));
const QString pattern = QStringLiteral("%%1%").arg(escaped);
const QString sql =
QStringLiteral("SELECT ") + QLatin1String(kTaskColumns) + QStringLiteral(", ") +
QLatin1String(kBlockColumns) +
QStringLiteral(" FROM task t JOIN timeblock b ON b.task_id = t.id "
"WHERE t.title LIKE :q ESCAPE '\\' "
"OR IFNULL(t.description, '') LIKE :q ESCAPE '\\' "
"OR IFNULL(t.source_ref, '') LIKE :q ESCAPE '\\' "
"ORDER BY ABS(julianday(b.start_at) - julianday('now')) ASC, b.start_at ASC "
"LIMIT :limit");
QSqlQuery statement(m_database);
statement.prepare(sql);
statement.bindValue(QStringLiteral(":q"), pattern);
statement.bindValue(QStringLiteral(":limit"), qBound(1, limit, 500));
if (!statement.exec())
{
setError(QStringLiteral("搜索日程失败: %1").arg(statement.lastError().text()));
return items;
}
while (statement.next())
{
ScheduleItem item;
item.task = mapTask(statement, 0);
item.block = mapTimeBlock(statement, 14);
items.append(item);
}
return items;
}
QVector<EnergyLevel> SqliteStore::energyLevels() const
{
m_lastError.clear();
QVector<EnergyLevel> levels;
if (!isOpenInternal())
{
setError(QStringLiteral("数据库未打开"));
return levels;
}
QSqlQuery query(m_database);
if (!query.exec(QStringLiteral(
"SELECT weekday, hour_slot, level FROM energy_profile ORDER BY weekday, hour_slot")))
{
setError(QStringLiteral("查询精力档案失败: %1").arg(query.lastError().text()));
return levels;
}
while (query.next())
{
levels.append({query.value(0).toInt(), query.value(1).toInt(), query.value(2).toInt()});
}
return levels;
}
bool SqliteStore::replaceEnergyLevels(const QVector<EnergyLevel>& levels)
{
m_lastError.clear();
if (!isOpenInternal())
{
return setError(QStringLiteral("数据库未打开"));
}
if (!m_database.transaction())
{
return setError(QStringLiteral("开启精力档案事务失败: %1").arg(m_database.lastError().text()));
}
QSqlQuery clear(m_database);
if (!clear.exec(QStringLiteral("DELETE FROM energy_profile")))
{
m_database.rollback();
return setError(QStringLiteral("清理精力档案失败: %1").arg(clear.lastError().text()));
}
QSqlQuery insert(m_database);
insert.prepare(QStringLiteral(
"INSERT OR REPLACE INTO energy_profile(id, weekday, hour_slot, level) "
"VALUES (:id, :weekday, :hour_slot, :level)"));
for (const EnergyLevel& level : levels)
{
insert.bindValue(QStringLiteral(":id"),
QStringLiteral("%1-%2").arg(level.weekday).arg(level.hour));
insert.bindValue(QStringLiteral(":weekday"), level.weekday);
insert.bindValue(QStringLiteral(":hour_slot"), level.hour);
insert.bindValue(QStringLiteral(":level"), std::clamp(level.level, 0, 2));
if (!insert.exec())
{
m_database.rollback();
return setError(QStringLiteral("写入精力档案失败: %1").arg(insert.lastError().text()));
}
}
if (!m_database.commit())
{
m_database.rollback();
return setError(QStringLiteral("提交精力档案失败: %1").arg(m_database.lastError().text()));
}
return true;
}
QVector<EnergySample> SqliteStore::completedEnergySamples() const
{
m_lastError.clear();
QVector<EnergySample> samples;
if (!isOpenInternal())
{
setError(QStringLiteral("数据库未打开"));
return samples;
}
QSqlQuery query(m_database);
if (!query.exec(QStringLiteral(
"SELECT t.energy_req, b.start_at, b.end_at FROM timeblock b "
"JOIN task t ON t.id = b.task_id "
"WHERE b.status = 'done' AND t.energy_req IS NOT NULL")))
{
setError(QStringLiteral("查询精力样本失败: %1").arg(query.lastError().text()));
return samples;
}
while (query.next())
{
const int level = std::clamp(query.value(0).toInt(), 0, 2);
const QDateTime start = DateTimeUtils::fromDb(query.value(1).toString());
const QDateTime end = DateTimeUtils::fromDb(query.value(2).toString());
if (!start.isValid() || !end.isValid() || start >= end)
{
continue;
}
for (QDateTime cursor = start; cursor < end; cursor = cursor.addSecs(3600))
{
samples.append({cursor.date().dayOfWeek(), cursor.time().hour(), level});
}
}
return samples;
}
qint64 SqliteStore::syncCursor(const QString& deviceId, QString* error) const
{
m_lastError.clear();
+17
View File
@@ -7,7 +7,10 @@
#include <atomic>
#include <optional>
#include "core/EnergyProfile.h"
#include "core/Project.h"
#include "core/ProposedDiff.h"
#include "core/Recurrence.h"
#include "core/SyncTypes.h"
#include "core/ScheduleItem.h"
@@ -41,6 +44,14 @@ public:
std::optional<Task> taskById(const QString& id);
bool deleteTask(const QString& id);
bool hasBlocksForTask(const QString& taskId);
bool insertRecurrence(const Recurrence& recurrence);
std::optional<Recurrence> recurrenceForTask(const QString& taskId) const;
bool insertProject(const Project& project);
bool updateProject(const Project& project);
bool deleteProject(const QString& id);
std::optional<Project> projectById(const QString& id) const;
QVector<Project> projects(bool includeDone = false) const;
bool insertTimeBlock(const TimeBlock& block);
bool updateTimeBlock(const TimeBlock& block);
@@ -55,6 +66,8 @@ public:
QVector<ScheduleItem> blocksInRange(const QDateTime& fromUtc, const QDateTime& toUtc) const;
// 已结束但仍未完成、且结束时间在最近 windowDays 内的块。
QVector<ScheduleItem> overdueBefore(const QDateTime& nowUtc, int windowDays = 30) const;
QVector<ScheduleItem> search(const QString& query, int limit = 100) const;
QVector<ScheduleItem> completedBlocks(const QDateTime& fromUtc, const QDateTime& toUtc) const;
QVector<SyncOutboxItem> outboxBatch(int limit, QString* error = nullptr) const;
int outboxCount(QString* error = nullptr) const;
@@ -64,6 +77,10 @@ public:
qint64 syncCursor(const QString& deviceId, QString* error = nullptr) const;
bool setSyncCursor(const QString& deviceId, qint64 seq, QString* error = nullptr);
QVector<EnergyLevel> energyLevels() const;
bool replaceEnergyLevels(const QVector<EnergyLevel>& levels);
QVector<EnergySample> completedEnergySamples() const;
private:
bool openDatabase(QString* error);
bool configureConnection(QString* error);
+141 -2
View File
@@ -10,6 +10,7 @@
#include <QLabel>
#include <QPainter>
#include <QShortcut>
#include <QShowEvent>
#include <QSplitter>
#include <QTimer>
#include <QVBoxLayout>
@@ -28,9 +29,13 @@
#include "sync/SyncService.h"
#include "ui/MainWindow.h"
#include "ui/dialogs/BlockEditDialog.h"
#include "ui/dialogs/CompletedSummaryDialog.h"
#include "ui/dialogs/DailyReviewDialog.h"
#include "ui/dialogs/ProjectDialog.h"
#include "ui/dialogs/SettingsDialog.h"
#include "ui/panels/ChatPanel.h"
#include "ui/panels/TodayPanel.h"
#include "ui/theme/AnimationUtils.h"
#include "ui/theme/ThemeManager.h"
#include "ui/theme/WindowEffects.h"
#include "utils/AppSettings.h"
@@ -175,11 +180,29 @@ void CompactWindow::buildUi()
connect(openShortcut, &QShortcut::activated, this, &CompactWindow::openSchedule);
auto* settingsShortcut = new QShortcut(QKeySequence(QStringLiteral("Ctrl+,")), this);
connect(settingsShortcut, &QShortcut::activated, this, &CompactWindow::openSettings);
auto* reviewShortcut = new QShortcut(QKeySequence(QStringLiteral("Ctrl+R")), this);
connect(reviewShortcut, &QShortcut::activated, this, &CompactWindow::openDailyReview);
auto* searchShortcut = new QShortcut(QKeySequence::Find, this);
connect(searchShortcut, &QShortcut::activated, this, [this]() {
openSchedule();
if (m_scheduleWindow)
{
m_scheduleWindow->openSearch();
}
});
}
void CompactWindow::setupTray()
{
m_tray = new SystemTray(this);
connect(m_tray, &SystemTray::notificationClicked, this, [this](const QString& blockId) {
const auto item = m_scheduleService.itemForBlock(blockId);
openSchedule();
if (m_scheduleWindow && item.has_value())
{
m_scheduleWindow->focusBlock(item->block.startAt.date(), blockId);
}
});
if (!SystemTray::isAvailable())
{
return;
@@ -244,6 +267,24 @@ void CompactWindow::connectSignals()
m_scheduleWindow->focusBlock(QDate::currentDate(), id);
}
});
connect(m_todayPanel, &TodayPanel::reviewRequested, this, &CompactWindow::openDailyReview);
connect(m_todayPanel, &TodayPanel::achievementsRequested, this, &CompactWindow::openCompletedSummary);
connect(m_todayPanel, &TodayPanel::newProjectRequested, this, &CompactWindow::openNewProject);
connect(m_todayPanel, &TodayPanel::editProjectRequested, this, &CompactWindow::openEditProject);
connect(m_todayPanel, &TodayPanel::projectStatusRequested, this, [this](const QString& id, const QString& status) {
QString error;
if (!m_scheduleService.setProjectStatus(id, status, &error))
{
showError(QStringLiteral("更新长期项目失败"), error);
}
});
connect(m_todayPanel, &TodayPanel::deleteProjectRequested, this, [this](const QString& id) {
QString error;
if (!m_scheduleService.deleteProject(id, &error))
{
showError(QStringLiteral("删除长期项目失败"), error);
}
});
connect(&m_notificationService,
&NotificationService::overdueListChanged,
@@ -262,7 +303,7 @@ void CompactWindow::connectSignals()
QStringLiteral("「%1」原定 %2 尚未完成,点击打开处理。")
.arg(item.task.title,
DateTimeUtils::formatTimeRange(item.block.startAt, item.block.endAt));
m_tray->showNotification(QStringLiteral("日程超时"), body);
m_tray->showNotification(QStringLiteral("日程超时"), body, 6000, item.block.id);
}
if (isVisible())
{
@@ -274,6 +315,26 @@ void CompactWindow::connectSignals()
}
});
connect(&m_notificationService, &NotificationService::leadReminderDue, this, [this](const ScheduleItem& item, int minutesBefore) {
if (m_tray)
{
const QString body = QStringLiteral("「%1」将在 %2 分钟后开始(%3)。")
.arg(item.task.title)
.arg(minutesBefore)
.arg(item.block.startAt.toString(QStringLiteral("HH:mm")));
m_tray->showNotification(QStringLiteral("日程即将开始"), body, 6000, item.block.id);
}
});
connect(&m_notificationService, &NotificationService::startReminderDue, this, [this](const ScheduleItem& item) {
if (m_tray)
{
const QString body = QStringLiteral("「%1」现在开始(%2)。")
.arg(item.task.title,
DateTimeUtils::formatTimeRange(item.block.startAt, item.block.endAt));
m_tray->showNotification(QStringLiteral("日程开始"), body, 6000, item.block.id);
}
});
connect(&m_themeManager, &ThemeManager::themeChanged, this, &CompactWindow::applyTheme);
connect(&m_themeManager, &ThemeManager::preferenceChanged, this, [this](ThemeManager::Preference) {
applyTheme(m_themeManager.tokens());
@@ -332,8 +393,14 @@ void CompactWindow::reloadToday()
.arg(today.day())
.arg(weekdayLabel(today)));
m_todayItems = m_scheduleService.itemsForDay(today);
const QDateTime now = QDateTime::currentDateTime();
m_todayPanel->setDate(today);
m_todayPanel->setItems(m_todayItems, QDateTime::currentDateTime());
m_todayPanel->setItems(m_todayItems, now);
m_todayPanel->setProjects(m_scheduleService.projects());
const QVector<Suggestion> suggestions = m_scheduleService.suggestions(now);
m_todayPanel->setInsightText(
suggestions.isEmpty() ? QString()
: QStringLiteral("建议:%1").arg(suggestions.first().detail));
}
void CompactWindow::openSchedule()
@@ -358,10 +425,72 @@ void CompactWindow::openSettings()
{
connect(&dialog, &SettingsDialog::syncSettingsChanged, m_syncService, &SyncService::reloadConfig);
}
connect(&dialog, &SettingsDialog::reminderSettingsChanged, this, [this]() {
m_notificationService.setLeadMinutes(m_settings.reminderLeadMinutes());
m_notificationService.checkNow();
});
dialog.moveToCenter();
dialog.exec();
}
void CompactWindow::openDailyReview()
{
DailyReviewDialog dialog(m_scheduleService.dailyReview(QDate::currentDate()), m_tokens, this);
dialog.moveToCenter();
dialog.exec();
}
void CompactWindow::openCompletedSummary()
{
CompletedSummaryDialog dialog(m_scheduleService, m_tokens, this);
dialog.moveToCenter();
dialog.exec();
}
void CompactWindow::openNewProject()
{
ProjectDialog dialog(m_tokens, this);
dialog.moveToCenter();
if (dialog.exec() != QDialog::Accepted)
{
return;
}
QString error;
if (!m_scheduleService.createProject(dialog.titleValue(),
dialog.descriptionValue(),
dialog.deadlineValue(),
&error))
{
showError(QStringLiteral("创建长期项目失败"), error);
}
}
void CompactWindow::openEditProject(const QString& projectId)
{
const auto project = m_scheduleService.projectById(projectId);
if (!project.has_value())
{
showError(QStringLiteral("编辑长期项目失败"), QStringLiteral("找不到该项目"));
return;
}
ProjectDialog dialog(m_tokens, this);
dialog.setValues(project->title, project->description, project->deadline.value_or(QDate()));
dialog.moveToCenter();
if (dialog.exec() != QDialog::Accepted)
{
return;
}
QString error;
if (!m_scheduleService.updateProject(projectId,
dialog.titleValue(),
dialog.descriptionValue(),
dialog.deadlineValue(),
&error))
{
showError(QStringLiteral("保存长期项目失败"), error);
}
}
void CompactWindow::updateSyncStatus(const QString& status)
{
if (!m_syncLabel)
@@ -452,6 +581,16 @@ void CompactWindow::showAndRaise()
reloadToday();
}
void CompactWindow::showEvent(QShowEvent* event)
{
ElaWindow::showEvent(event);
if (!m_firstShowAnimated)
{
m_firstShowAnimated = true;
QTimer::singleShot(0, this, [this]() { AnimationUtils::fadeWindow(this); });
}
}
void CompactWindow::paintEvent(QPaintEvent* event)
{
ElaWindow::paintEvent(event);
+7
View File
@@ -23,6 +23,7 @@ class TodayPanel;
class QCloseEvent;
class QLabel;
class QPaintEvent;
class QShowEvent;
class QSplitter;
class QTimer;
@@ -50,6 +51,7 @@ public:
protected:
void closeEvent(QCloseEvent* event) override;
void paintEvent(QPaintEvent* event) override;
void showEvent(QShowEvent* event) override;
private:
void buildUi();
@@ -62,6 +64,10 @@ private:
void reloadToday();
void openSchedule();
void openSettings();
void openDailyReview();
void openCompletedSummary();
void openNewProject();
void openEditProject(const QString& projectId);
void openEditDialog(const QString& blockId);
void showError(const QString& title, const QString& message);
void updateSyncStatus(const QString& status);
@@ -89,4 +95,5 @@ private:
QTimer* m_refreshTimer = nullptr;
bool m_quitting = false;
bool m_firstShowAnimated = false;
};
+163 -5
View File
@@ -34,8 +34,13 @@
#include "services/ScheduleService.h"
#include "sync/SyncService.h"
#include "ui/dialogs/BlockEditDialog.h"
#include "ui/dialogs/CompletedSummaryDialog.h"
#include "ui/dialogs/DailyReviewDialog.h"
#include "ui/dialogs/ProjectDialog.h"
#include "ui/dialogs/SearchDialog.h"
#include "ui/dialogs/SettingsDialog.h"
#include "ui/panels/TodayPanel.h"
#include "ui/theme/AnimationUtils.h"
#include "ui/theme/ThemeManager.h"
#include "ui/theme/WindowEffects.h"
#include "ui/views/MonthView.h"
@@ -144,10 +149,10 @@ void MainWindow::buildUi()
m_newButton->setToolTip(QStringLiteral("新建日程 (Ctrl+N)"));
m_searchEdit = new ElaLineEdit(m_toolbar);
m_searchEdit->setPlaceholderText(QStringLiteral("搜索(阶段 4)"));
m_searchEdit->setFixedSize(140, 30);
m_searchEdit->setEnabled(false);
m_searchEdit->setToolTip(QStringLiteral("搜索将在阶段 4 接入"));
m_searchEdit->setPlaceholderText(QStringLiteral("搜索日程 (Ctrl+F)"));
m_searchEdit->setFixedSize(160, 30);
m_searchEdit->setClearButtonEnabled(true);
m_searchEdit->setToolTip(QStringLiteral("搜索标题或说明,回车打开结果"));
m_snapCombo = new ElaComboBox(m_toolbar);
m_snapCombo->addItems({QStringLiteral("吸附 15 分"),
@@ -252,6 +257,7 @@ void MainWindow::buildUi()
connect(m_newButton, &ElaPushButton::clicked, this, &MainWindow::openCreateDialogForNew);
connect(m_themeButton, &ElaToolButton::clicked, this, [this]() { m_themeManager.cyclePreference(); });
connect(m_settingsButton, &ElaToolButton::clicked, this, &MainWindow::openSettings);
connect(m_searchEdit, &ElaLineEdit::returnPressed, this, &MainWindow::openSearch);
if (m_syncService)
{
connect(m_syncService, &SyncService::statusChanged, this, &MainWindow::updateSyncStatus);
@@ -310,6 +316,19 @@ void MainWindow::buildUi()
auto* settingsShortcut = new QShortcut(QKeySequence(QStringLiteral("Ctrl+,")), this);
connect(settingsShortcut, &QShortcut::activated, this, &MainWindow::openSettings);
auto* reviewShortcut = new QShortcut(QKeySequence(QStringLiteral("Ctrl+R")), this);
connect(reviewShortcut, &QShortcut::activated, this, &MainWindow::openDailyReview);
auto* searchShortcut = new QShortcut(QKeySequence::Find, this);
connect(searchShortcut, &QShortcut::activated, this, [this]() {
if (m_searchEdit)
{
m_searchEdit->setFocus();
m_searchEdit->selectAll();
}
openSearch();
});
auto* compactShortcut = new QShortcut(QKeySequence(QStringLiteral("Ctrl+W")), this);
connect(compactShortcut, &QShortcut::activated, this, &MainWindow::close);
}
@@ -405,6 +424,24 @@ void MainWindow::connectSignals()
m_grid->scrollToBlock(id);
m_grid->setFocus(Qt::OtherFocusReason);
});
connect(m_todayPanel, &TodayPanel::reviewRequested, this, &MainWindow::openDailyReview);
connect(m_todayPanel, &TodayPanel::achievementsRequested, this, &MainWindow::openCompletedSummary);
connect(m_todayPanel, &TodayPanel::newProjectRequested, this, &MainWindow::openNewProject);
connect(m_todayPanel, &TodayPanel::editProjectRequested, this, &MainWindow::openEditProject);
connect(m_todayPanel, &TodayPanel::projectStatusRequested, this, [this](const QString& id, const QString& status) {
QString error;
if (!m_scheduleService.setProjectStatus(id, status, &error))
{
showError(QStringLiteral("更新长期项目失败"), error);
}
});
connect(m_todayPanel, &TodayPanel::deleteProjectRequested, this, [this](const QString& id) {
QString error;
if (!m_scheduleService.deleteProject(id, &error))
{
showError(QStringLiteral("删除长期项目失败"), error);
}
});
connect(&m_notificationService,
&NotificationService::overdueListChanged,
@@ -523,6 +560,7 @@ void MainWindow::setView(View view)
{
m_currentView = view;
const int index = static_cast<int>(view);
const int previousIndex = m_viewStack ? m_viewStack->currentIndex() : -1;
if (m_viewStack)
{
m_viewStack->setCurrentIndex(index);
@@ -538,6 +576,10 @@ void MainWindow::setView(View view)
{
m_grid->scrollToCurrentTime();
}
if (m_viewStack && previousIndex >= 0 && previousIndex != index)
{
AnimationUtils::fadeIn(m_viewStack, 160);
}
}
MainWindow::View MainWindow::view() const
@@ -590,8 +632,31 @@ void MainWindow::reloadCurrentView()
}
}
if (m_currentView == View::Day)
{
const QDateTime ghostFrom =
m_currentDate == now.date() ? now : QDateTime(m_currentDate, QTime(8, 0), Qt::LocalTime);
m_grid->setGhostWindows(findFreeWindows(agendaItems, m_currentDate, ghostFrom, 8, 22, 30));
}
else
{
m_grid->setGhostWindows({});
}
m_todayPanel->setDate(m_currentDate);
m_todayPanel->setItems(agendaItems, now);
m_todayPanel->setProjects(m_scheduleService.projects());
if (m_currentDate == QDate::currentDate())
{
const QVector<Suggestion> suggestions = m_scheduleService.suggestions(now);
m_todayPanel->setInsightText(
suggestions.isEmpty() ? QString()
: QStringLiteral("建议:%1").arg(suggestions.first().detail));
}
else
{
m_todayPanel->setInsightText(QString());
}
}
void MainWindow::navigateToDate(const QDate& date)
@@ -751,7 +816,17 @@ void MainWindow::openCreateDialog(const QDateTime& start, const QDateTime& end)
}
QString error;
if (!m_scheduleService.createBlock(dialog.titleValue(), dialog.startValue(), dialog.endValue(), &error))
const RecurrenceFrequency frequency = dialog.recurrenceFrequency();
const bool created = frequency == RecurrenceFrequency::None
? m_scheduleService.createBlock(dialog.titleValue(), dialog.startValue(), dialog.endValue(), &error)
: m_scheduleService.createRecurringBlock(dialog.titleValue(),
dialog.startValue(),
dialog.endValue(),
frequency,
dialog.recurrenceUntil(),
nullptr,
&error);
if (!created)
{
showError(QStringLiteral("创建日程失败"), error);
return;
@@ -812,6 +887,88 @@ void MainWindow::openSettings()
{
connect(&dialog, &SettingsDialog::syncSettingsChanged, m_syncService, &SyncService::reloadConfig);
}
connect(&dialog, &SettingsDialog::reminderSettingsChanged, this, [this]() {
m_notificationService.setLeadMinutes(m_settings.reminderLeadMinutes());
m_notificationService.checkNow();
});
dialog.moveToCenter();
dialog.exec();
}
void MainWindow::openDailyReview()
{
DailyReviewDialog dialog(m_scheduleService.dailyReview(m_currentDate), m_tokens, this);
dialog.moveToCenter();
dialog.exec();
}
void MainWindow::openCompletedSummary()
{
CompletedSummaryDialog dialog(m_scheduleService, m_tokens, this);
dialog.moveToCenter();
dialog.exec();
}
void MainWindow::openNewProject()
{
ProjectDialog dialog(m_tokens, this);
dialog.moveToCenter();
if (dialog.exec() != QDialog::Accepted)
{
return;
}
QString error;
if (!m_scheduleService.createProject(dialog.titleValue(),
dialog.descriptionValue(),
dialog.deadlineValue(),
&error))
{
showError(QStringLiteral("创建长期项目失败"), error);
}
}
void MainWindow::openEditProject(const QString& projectId)
{
const auto project = m_scheduleService.projectById(projectId);
if (!project.has_value())
{
showError(QStringLiteral("编辑长期项目失败"), QStringLiteral("找不到该项目"));
return;
}
ProjectDialog dialog(m_tokens, this);
dialog.setValues(project->title, project->description, project->deadline.value_or(QDate()));
dialog.moveToCenter();
if (dialog.exec() != QDialog::Accepted)
{
return;
}
QString error;
if (!m_scheduleService.updateProject(projectId,
dialog.titleValue(),
dialog.descriptionValue(),
dialog.deadlineValue(),
&error))
{
showError(QStringLiteral("保存长期项目失败"), error);
}
}
void MainWindow::openSearch()
{
SearchDialog dialog(m_scheduleService,
m_tokens,
m_searchEdit ? m_searchEdit->text() : QString(),
this);
connect(&dialog, &SearchDialog::blockSelected, this, [this](const QDate& date, const QString& blockId) {
if (m_searchEdit)
{
m_searchEdit->setText(QString());
}
m_currentDate = date;
setView(View::Day);
m_grid->scrollToBlock(blockId);
m_grid->setFocus(Qt::OtherFocusReason);
});
dialog.moveToCenter();
dialog.exec();
}
@@ -937,6 +1094,7 @@ void MainWindow::showEvent(QShowEvent* event)
{
m_firstShowHandled = true;
QTimer::singleShot(0, this, [this]() {
AnimationUtils::fadeWindow(this);
if (m_grid && m_currentView == View::Day)
{
m_grid->scrollToCurrentTime();
+5
View File
@@ -63,6 +63,7 @@ public:
void showAndRaise();
void openNewBlock();
void openSearch();
void focusBlock(const QDate& date, const QString& blockId);
signals:
@@ -89,6 +90,10 @@ private:
void openCreateDialogForNew();
void openEditDialog(const QString& blockId);
void openSettings();
void openDailyReview();
void openCompletedSummary();
void openNewProject();
void openEditProject(const QString& projectId);
void updateOverdueBanner(const QVector<ScheduleItem>& items);
void showError(const QString& title, const QString& message);
void updateSyncStatus(const QString& status);
+90 -1
View File
@@ -1,14 +1,18 @@
#include "BlockEditDialog.h"
#include <QDateEdit>
#include <QDateTimeEdit>
#include <QFormLayout>
#include <QHBoxLayout>
#include <QSignalBlocker>
#include <QVBoxLayout>
#include <QTimer>
#include "ElaComboBox.h"
#include "ElaLineEdit.h"
#include "ElaPushButton.h"
#include "ElaText.h"
#include "ui/theme/AnimationUtils.h"
BlockEditDialog::BlockEditDialog(const ThemeTokens& tokens, QWidget* parent)
: ElaDialog(parent)
@@ -17,7 +21,7 @@ BlockEditDialog::BlockEditDialog(const ThemeTokens& tokens, QWidget* parent)
setWindowTitle(QStringLiteral("新建日程"));
setWindowButtonFlags(ElaAppBarType::CloseButtonHint);
setMinimumWidth(440);
resize(440, 320);
resize(440, 430);
auto* root = new QVBoxLayout(this);
root->setContentsMargins(22, 8, 22, 18);
@@ -47,9 +51,26 @@ BlockEditDialog::BlockEditDialog(const ThemeTokens& tokens, QWidget* parent)
m_endEdit->setDisplayFormat(QStringLiteral("yyyy-MM-dd HH:mm"));
m_endEdit->setMinimumHeight(34);
m_repeatLabel = new ElaText(QStringLiteral("重复"), 13, this);
m_repeatCombo = new ElaComboBox(this);
m_repeatCombo->addItems({QStringLiteral("不重复"),
QStringLiteral("每天"),
QStringLiteral("每周"),
QStringLiteral("每月")});
m_repeatCombo->setMinimumHeight(34);
m_repeatUntilLabel = new ElaText(QStringLiteral("重复结束"), 13, this);
m_repeatUntilEdit = new QDateEdit(this);
m_repeatUntilEdit->setCalendarPopup(true);
m_repeatUntilEdit->setDisplayFormat(QStringLiteral("yyyy-MM-dd"));
m_repeatUntilEdit->setDate(QDate::currentDate().addMonths(3));
m_repeatUntilEdit->setMinimumHeight(34);
form->addRow(titleLabel, m_titleEdit);
form->addRow(startLabel, m_startEdit);
form->addRow(endLabel, m_endEdit);
form->addRow(m_repeatLabel, m_repeatCombo);
form->addRow(m_repeatUntilLabel, m_repeatUntilEdit);
root->addLayout(form);
m_errorLabel = new ElaText(this);
@@ -79,12 +100,42 @@ BlockEditDialog::BlockEditDialog(const ThemeTokens& tokens, QWidget* parent)
const QSignalBlocker blocker(m_endEdit);
m_endEdit->setDateTime(start.addSecs(60 * 60));
}
if (m_repeatUntilEdit && start.isValid() && m_repeatUntilEdit->date() < start.date())
{
m_repeatUntilEdit->setDate(start.date().addMonths(3));
}
});
connect(m_repeatCombo, &ElaComboBox::currentIndexChanged, this, [this](int index) {
if (m_repeatUntilEdit)
{
m_repeatUntilEdit->setEnabled(index > 0);
}
});
m_repeatUntilEdit->setEnabled(false);
QTimer::singleShot(0, this, [this]() { AnimationUtils::fadeWindow(this); });
}
void BlockEditDialog::setCreateMode(bool create)
{
m_createMode = create;
setWindowTitle(create ? QStringLiteral("新建日程") : QStringLiteral("编辑日程"));
resize(width(), create ? 430 : 320);
if (m_repeatLabel)
{
m_repeatLabel->setVisible(create);
}
if (m_repeatCombo)
{
m_repeatCombo->setVisible(create);
}
if (m_repeatUntilLabel)
{
m_repeatUntilLabel->setVisible(create);
}
if (m_repeatUntilEdit)
{
m_repeatUntilEdit->setVisible(create);
}
}
void BlockEditDialog::setValues(const QString& title, const QDateTime& start, const QDateTime& end)
@@ -94,6 +145,10 @@ void BlockEditDialog::setValues(const QString& title, const QDateTime& start, co
m_titleEdit->setText(title);
m_startEdit->setDateTime(start);
m_endEdit->setDateTime(end);
if (m_repeatUntilEdit && start.isValid())
{
m_repeatUntilEdit->setDate(start.date().addMonths(3));
}
m_titleEdit->setFocus();
m_titleEdit->selectAll();
}
@@ -113,6 +168,34 @@ QDateTime BlockEditDialog::endValue() const
return m_endEdit->dateTime();
}
RecurrenceFrequency BlockEditDialog::recurrenceFrequency() const
{
if (!m_createMode || !m_repeatCombo)
{
return RecurrenceFrequency::None;
}
switch (m_repeatCombo->currentIndex())
{
case 1:
return RecurrenceFrequency::Daily;
case 2:
return RecurrenceFrequency::Weekly;
case 3:
return RecurrenceFrequency::Monthly;
default:
return RecurrenceFrequency::None;
}
}
QDate BlockEditDialog::recurrenceUntil() const
{
if (recurrenceFrequency() == RecurrenceFrequency::None || !m_repeatUntilEdit)
{
return {};
}
return m_repeatUntilEdit->date();
}
void BlockEditDialog::updateError(const QString& message)
{
m_errorLabel->setText(message);
@@ -130,6 +213,12 @@ void BlockEditDialog::accept()
updateError(QStringLiteral("日程时长至少为 5 分钟"));
return;
}
if (recurrenceFrequency() != RecurrenceFrequency::None &&
recurrenceUntil() < startValue().date())
{
updateError(QStringLiteral("重复结束日期不能早于开始日期"));
return;
}
updateError(QString());
QDialog::accept();
}
+10
View File
@@ -4,10 +4,13 @@
#include <QString>
#include "ElaDialog.h"
#include "core/Recurrence.h"
#include "ui/theme/ThemeTokens.h"
class ElaComboBox;
class ElaLineEdit;
class ElaText;
class QDateEdit;
class QDateTimeEdit;
/*
@@ -28,6 +31,8 @@ public:
QString titleValue() const;
QDateTime startValue() const;
QDateTime endValue() const;
RecurrenceFrequency recurrenceFrequency() const;
QDate recurrenceUntil() const;
public slots:
void accept() override;
@@ -38,6 +43,11 @@ private:
ElaLineEdit* m_titleEdit = nullptr;
QDateTimeEdit* m_startEdit = nullptr;
QDateTimeEdit* m_endEdit = nullptr;
ElaText* m_repeatLabel = nullptr;
ElaComboBox* m_repeatCombo = nullptr;
ElaText* m_repeatUntilLabel = nullptr;
QDateEdit* m_repeatUntilEdit = nullptr;
ElaText* m_errorLabel = nullptr;
QString m_errorColor;
bool m_createMode = true;
};
@@ -0,0 +1,288 @@
#include "CompletedSummaryDialog.h"
#include <QDate>
#include <QFrame>
#include <QLayoutItem>
#include <QSet>
#include <QTimer>
#include <QHBoxLayout>
#include <QLabel>
#include <QVBoxLayout>
#include "ElaComboBox.h"
#include "ElaPushButton.h"
#include "ElaScrollArea.h"
#include "ElaText.h"
#include "core/DateTimeUtils.h"
#include "services/ScheduleService.h"
#include "storage/SqliteStore.h"
#include "ui/theme/AnimationUtils.h"
namespace
{
QString formatMinutes(int minutes)
{
if (minutes <= 0)
{
return QStringLiteral("0 分钟");
}
return DateTimeUtils::formatDuration(minutes);
}
} // namespace
CompletedSummaryDialog::CompletedSummaryDialog(ScheduleService& scheduleService,
const ThemeTokens& tokens,
QWidget* parent)
: ElaDialog(parent)
, m_scheduleService(scheduleService)
, m_tokens(tokens)
{
setWindowTitle(QStringLiteral("已完成汇总"));
setWindowButtonFlags(ElaAppBarType::CloseButtonHint);
resize(640, 680);
setMinimumWidth(560);
auto* root = new QVBoxLayout(this);
root->setContentsMargins(24, 8, 24, 18);
root->setSpacing(10);
auto* title = new ElaText(QStringLiteral("已完成汇总"), 18, this);
QFont titleFont = title->font();
titleFont.setWeight(QFont::DemiBold);
title->setFont(titleFont);
root->addWidget(title);
auto* subtitle = new ElaText(QStringLiteral("把完成的事情放在一起,看看你已经走了多远。"), 11, this);
subtitle->setTextStyle(ElaTextType::Caption);
root->addWidget(subtitle);
auto* rangeRow = new QHBoxLayout();
rangeRow->setSpacing(10);
auto* rangeLabel = new ElaText(QStringLiteral("范围"), 12, this);
m_rangeCombo = new ElaComboBox(this);
m_rangeCombo->addItems({QStringLiteral("本周"),
QStringLiteral("本月"),
QStringLiteral("全部")});
m_rangeCombo->setCurrentIndex(2);
m_rangeCombo->setFixedSize(130, 32);
rangeRow->addWidget(rangeLabel, 0, Qt::AlignVCenter);
rangeRow->addWidget(m_rangeCombo, 0, Qt::AlignVCenter);
rangeRow->addStretch(1);
root->addLayout(rangeRow);
auto* stats = new QHBoxLayout();
stats->setSpacing(28);
const auto addStat = [this, stats](const QString& label, ElaText** valueOut) {
auto* column = new QVBoxLayout();
column->setSpacing(2);
auto* title = new ElaText(label, 11, this);
title->setTextStyle(ElaTextType::Caption);
auto* value = new ElaText(QStringLiteral("0"), 19, this);
QFont font = value->font();
font.setWeight(QFont::DemiBold);
value->setFont(font);
column->addWidget(title);
column->addWidget(value);
stats->addLayout(column);
*valueOut = value;
};
addStat(QStringLiteral("短期任务"), &m_taskStat);
addStat(QStringLiteral("专注时长"), &m_focusStat);
addStat(QStringLiteral("长期项目"), &m_projectStat);
addStat(QStringLiteral("连续完成"), &m_streakStat);
root->addLayout(stats);
auto* divider = new QFrame(this);
divider->setFrameShape(QFrame::HLine);
divider->setFrameShadow(QFrame::Plain);
root->addWidget(divider);
m_scrollArea = new ElaScrollArea(this);
m_scrollArea->setWidgetResizable(true);
m_scrollArea->setFrameShape(QFrame::NoFrame);
m_scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
m_scrollArea->setStyleSheet(QStringLiteral("QScrollArea{background:transparent;border:none;}"));
m_scrollArea->viewport()->setAutoFillBackground(false);
m_scrollArea->viewport()->setStyleSheet(QStringLiteral("background:transparent;"));
m_listWidget = new QWidget(m_scrollArea);
m_listWidget->setAutoFillBackground(false);
m_listWidget->setStyleSheet(QStringLiteral("background:transparent;"));
m_listLayout = new QVBoxLayout(m_listWidget);
m_listLayout->setContentsMargins(0, 0, 4, 0);
m_listLayout->setSpacing(6);
m_listLayout->addStretch(1);
m_scrollArea->setWidget(m_listWidget);
root->addWidget(m_scrollArea, 1);
auto* closeRow = new QHBoxLayout();
closeRow->addStretch(1);
auto* close = new ElaPushButton(QStringLiteral("完成"), this);
close->setFixedSize(88, 34);
close->setDefault(true);
closeRow->addWidget(close);
root->addLayout(closeRow);
connect(close, &ElaPushButton::clicked, this, &CompletedSummaryDialog::accept);
connect(m_rangeCombo, &ElaComboBox::currentIndexChanged, this, [this](int) { rebuild(); });
rebuild();
QTimer::singleShot(0, this, [this]() { AnimationUtils::fadeWindow(this); });
}
void CompletedSummaryDialog::clearLayout(QVBoxLayout* layout)
{
while (QLayoutItem* item = layout->takeAt(0))
{
if (QWidget* widget = item->widget())
{
widget->hide();
widget->deleteLater();
}
delete item;
}
}
QString CompletedSummaryDialog::shortRangeStart() const
{
const QDate today = QDate::currentDate();
switch (m_rangeCombo->currentIndex())
{
case 0:
return today.addDays(1 - today.dayOfWeek()).toString(Qt::ISODate);
case 1:
return QDate(today.year(), today.month(), 1).toString(Qt::ISODate);
default:
return QDate(2000, 1, 1).toString(Qt::ISODate);
}
}
void CompletedSummaryDialog::rebuild()
{
if (!m_listLayout)
{
return;
}
clearLayout(m_listLayout);
const QDate today = QDate::currentDate();
const QDate start = QDate::fromString(shortRangeStart(), Qt::ISODate);
const auto items = m_scheduleService.completedItems(start, today);
const auto projects = m_scheduleService.completedProjects(start, today);
int focusedMinutes = 0;
QSet<QDate> completionDays;
for (const ScheduleItem& item : items)
{
focusedMinutes += qMax(0, DateTimeUtils::minutesBetween(item.block.startAt, item.block.endAt));
completionDays.insert(item.block.doneAt.has_value() ? item.block.doneAt->date()
: item.block.endAt.date());
}
for (const Project& project : projects)
{
completionDays.insert(project.updatedAt.date());
}
int streak = 0;
QDate cursor = completionDays.contains(today) ? today : today.addDays(-1);
while (completionDays.contains(cursor))
{
++streak;
cursor = cursor.addDays(-1);
}
m_taskStat->setText(QString::number(items.size()));
m_focusStat->setText(formatMinutes(focusedMinutes));
m_projectStat->setText(QString::number(projects.size()));
m_streakStat->setText(QStringLiteral("%1 天").arg(streak));
const auto addSection = [this](const QString& text) {
auto* label = new ElaText(text, 13, m_listWidget);
QFont font = label->font();
font.setWeight(QFont::DemiBold);
label->setFont(font);
label->setContentsMargins(2, 8, 0, 2);
m_listLayout->addWidget(label);
};
const auto addEmpty = [this](const QString& text) {
auto* label = new ElaText(text, 12, m_listWidget);
label->setTextStyle(ElaTextType::Caption);
label->setContentsMargins(2, 2, 0, 2);
m_listLayout->addWidget(label);
};
if (items.isEmpty() && projects.isEmpty())
{
addEmpty(QStringLiteral("这个范围内还没有已完成记录。"));
m_listLayout->addStretch(1);
return;
}
addSection(QStringLiteral("短期任务 · %1").arg(items.size()));
if (items.isEmpty())
{
addEmpty(QStringLiteral("暂无已完成短期任务。"));
}
int shown = 0;
for (const ScheduleItem& item : items)
{
if (shown++ >= 80)
{
break;
}
auto* card = new QFrame(m_listWidget);
card->setStyleSheet(
QStringLiteral("QFrame{background:%1;border:1px solid %2;border-radius:8px;}")
.arg(m_tokens.cardBackground.name(), m_tokens.cardBorder.name()));
auto* layout = new QVBoxLayout(card);
layout->setContentsMargins(10, 7, 10, 7);
layout->setSpacing(2);
auto* name = new QLabel(item.task.title, card);
name->setStyleSheet(QStringLiteral("background:transparent;border:none;color:%1;font-size:12px;font-weight:600;")
.arg(m_tokens.textPrimary.name()));
const QDateTime doneAt = item.block.doneAt.value_or(item.block.endAt);
auto* detail = new QLabel(
QStringLiteral("完成于 %1 · %2–%3")
.arg(doneAt.toString(QStringLiteral("MM-dd HH:mm")),
item.block.startAt.toString(QStringLiteral("HH:mm")),
item.block.endAt.toString(QStringLiteral("HH:mm"))),
card);
detail->setStyleSheet(QStringLiteral("background:transparent;border:none;color:%1;font-size:11px;")
.arg(m_tokens.textMuted.name()));
layout->addWidget(name);
layout->addWidget(detail);
m_listLayout->addWidget(card);
}
addSection(QStringLiteral("长期项目 · %1").arg(projects.size()));
if (projects.isEmpty())
{
addEmpty(QStringLiteral("暂无已完成长期项目。"));
}
for (const Project& project : projects)
{
auto* card = new QFrame(m_listWidget);
card->setStyleSheet(
QStringLiteral("QFrame{background:%1;border:1px solid %2;border-left:3px solid %3;border-radius:8px;}")
.arg(m_tokens.cardBackground.name(),
m_tokens.cardBorder.name(),
m_tokens.success.name()));
auto* layout = new QVBoxLayout(card);
layout->setContentsMargins(10, 7, 10, 7);
layout->setSpacing(2);
auto* name = new QLabel(project.title, card);
name->setStyleSheet(QStringLiteral("background:transparent;border:none;color:%1;font-size:12px;font-weight:600;")
.arg(m_tokens.textPrimary.name()));
auto* detail = new QLabel(
QStringLiteral("完成于 %1%2")
.arg(project.updatedAt.toString(QStringLiteral("MM-dd HH:mm")),
project.deadline.has_value()
? QStringLiteral(" · 截止 %1").arg(project.deadline->toString(QStringLiteral("yyyy-MM-dd")))
: QString()),
card);
detail->setStyleSheet(QStringLiteral("background:transparent;border:none;color:%1;font-size:11px;")
.arg(m_tokens.textMuted.name()));
layout->addWidget(name);
layout->addWidget(detail);
m_listLayout->addWidget(card);
}
m_listLayout->addStretch(1);
AnimationUtils::fadeIn(m_listWidget, 150);
}
@@ -0,0 +1,41 @@
#pragma once
#include "ElaDialog.h"
#include "ui/theme/ThemeTokens.h"
class ElaComboBox;
class ElaScrollArea;
class ElaText;
class QVBoxLayout;
class ScheduleService;
/*
* 类名: CompletedSummaryDialog
* 功能: 汇总已完成的短期任务与长期项目,展示统计、连续天数和完成记录
* 线程安全: 否;UI 线程
*/
class CompletedSummaryDialog : public ElaDialog
{
Q_OBJECT
public:
CompletedSummaryDialog(ScheduleService& scheduleService,
const ThemeTokens& tokens,
QWidget* parent = nullptr);
private:
void rebuild();
static void clearLayout(QVBoxLayout* layout);
QString shortRangeStart() const;
ScheduleService& m_scheduleService;
ThemeTokens m_tokens;
ElaComboBox* m_rangeCombo = nullptr;
ElaText* m_taskStat = nullptr;
ElaText* m_focusStat = nullptr;
ElaText* m_projectStat = nullptr;
ElaText* m_streakStat = nullptr;
ElaScrollArea* m_scrollArea = nullptr;
QWidget* m_listWidget = nullptr;
QVBoxLayout* m_listLayout = nullptr;
};
+149
View File
@@ -0,0 +1,149 @@
#include "DailyReviewDialog.h"
#include <QGridLayout>
#include <algorithm>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QTimer>
#include "ElaPushButton.h"
#include "ElaText.h"
#include "ui/theme/AnimationUtils.h"
namespace
{
QString formatWindow(const FreeWindow& window)
{
return QStringLiteral("%1–%2 · %3")
.arg(window.start.toString(QStringLiteral("HH:mm")),
window.end.toString(QStringLiteral("HH:mm")),
window.minutes >= 60
? QStringLiteral("%1 小时 %2 分").arg(window.minutes / 60).arg(window.minutes % 60)
: QStringLiteral("%1 分钟").arg(window.minutes));
}
} // namespace
DailyReviewDialog::DailyReviewDialog(const DailyReview& review,
const ThemeTokens& tokens,
QWidget* parent)
: ElaDialog(parent)
{
setWindowTitle(QStringLiteral("今日复盘"));
setWindowButtonFlags(ElaAppBarType::CloseButtonHint);
resize(520, 560);
setMinimumWidth(480);
auto* root = new QVBoxLayout(this);
root->setContentsMargins(24, 8, 24, 18);
root->setSpacing(10);
auto* title = new ElaText(QStringLiteral("%1月%2日 · %3复盘")
.arg(review.date.month())
.arg(review.date.day())
.arg(weekdayLabel(review.date)),
17,
this);
QFont titleFont = title->font();
titleFont.setWeight(QFont::DemiBold);
title->setFont(titleFont);
root->addWidget(title);
auto* summary = new ElaText(review.summary, 14, this);
summary->setWordWrap(true);
summary->setStyleSheet(QStringLiteral("color:%1;").arg(tokens.textPrimary.name()));
root->addWidget(summary);
auto* grid = new QGridLayout();
grid->setHorizontalSpacing(28);
grid->setVerticalSpacing(8);
const auto addStat = [this, grid](int row, int column, const QString& label, const QString& value) {
auto* labelText = new ElaText(label, 11, this);
labelText->setTextStyle(ElaTextType::Caption);
auto* valueText = new ElaText(value, 14, this);
QFont valueFont = valueText->font();
valueFont.setWeight(QFont::DemiBold);
valueText->setFont(valueFont);
grid->addWidget(labelText, row, column);
grid->addWidget(valueText, row + 1, column);
};
addStat(0, 0, QStringLiteral("完成"), QStringLiteral("%1 / %2").arg(review.done).arg(review.total));
addStat(0, 1, QStringLiteral("完成率"), QStringLiteral("%1%").arg(review.completionPercent));
addStat(0, 2, QStringLiteral("专注"), QStringLiteral("%1 分钟").arg(review.focusedMinutes));
addStat(2, 0, QStringLiteral("待办"), QString::number(review.active));
addStat(2, 1, QStringLiteral("超时"), QString::number(review.overdue));
addStat(2, 2, QStringLiteral("错过 / 放弃"),
QStringLiteral("%1 / %2").arg(review.missed).arg(review.dropped));
root->addLayout(grid);
if (!review.energySummary.isEmpty())
{
auto* energy = new ElaText(review.energySummary, 12, this);
energy->setWordWrap(true);
energy->setStyleSheet(QStringLiteral("color:%1;").arg(tokens.accent.name()));
root->addWidget(energy);
}
auto* highlightsTitle = new ElaText(QStringLiteral("今日概览"), 13, this);
QFont sectionFont = highlightsTitle->font();
sectionFont.setWeight(QFont::DemiBold);
highlightsTitle->setFont(sectionFont);
root->addWidget(highlightsTitle);
for (const QString& highlight : review.highlights)
{
auto* line = new ElaText(QStringLiteral("· %1").arg(highlight), 12, this);
line->setWordWrap(true);
root->addWidget(line);
}
auto* ghostTitle = new ElaText(QStringLiteral("幽灵时间"), 13, this);
ghostTitle->setFont(sectionFont);
root->addWidget(ghostTitle);
if (review.ghostWindows.isEmpty())
{
auto* empty = new ElaText(QStringLiteral("今天没有 30 分钟以上的空档。"), 12, this);
empty->setTextStyle(ElaTextType::Caption);
root->addWidget(empty);
}
else
{
const qsizetype count = std::min<qsizetype>(5, review.ghostWindows.size());
for (int i = 0; i < count; ++i)
{
auto* line = new ElaText(QStringLiteral("· %1").arg(formatWindow(review.ghostWindows.at(i))),
12,
this);
root->addWidget(line);
}
if (review.ghostWindows.size() > count)
{
auto* more = new ElaText(QStringLiteral("还有 %1 段空档")
.arg(review.ghostWindows.size() - count),
11,
this);
more->setTextStyle(ElaTextType::Caption);
root->addWidget(more);
}
}
root->addStretch(1);
auto* buttonRow = new QHBoxLayout();
buttonRow->addStretch(1);
auto* closeButton = new ElaPushButton(QStringLiteral("完成"), this);
closeButton->setFixedSize(88, 34);
closeButton->setDefault(true);
buttonRow->addWidget(closeButton);
root->addLayout(buttonRow);
connect(closeButton, &ElaPushButton::clicked, this, &DailyReviewDialog::accept);
QTimer::singleShot(0, this, [this]() { AnimationUtils::fadeWindow(this); });
}
QString DailyReviewDialog::weekdayLabel(const QDate& date) const
{
if (!date.isValid())
{
return {};
}
static const char* labels[] = {"周一", "周二", "周三", "周四", "周五", "周六", "周日"};
return QString::fromUtf8(labels[date.dayOfWeek() - 1]);
}
+21
View File
@@ -0,0 +1,21 @@
#pragma once
#include "ElaDialog.h"
#include "core/DailyInsights.h"
#include "ui/theme/ThemeTokens.h"
/*
* 类名: DailyReviewDialog
* 功能: 展示每日完成情况、精力高峰与幽灵时间
* 线程安全: 否;UI 线程
*/
class DailyReviewDialog : public ElaDialog
{
Q_OBJECT
public:
DailyReviewDialog(const DailyReview& review, const ThemeTokens& tokens, QWidget* parent = nullptr);
private:
QString weekdayLabel(const QDate& date) const;
};
+123
View File
@@ -0,0 +1,123 @@
#include "ProjectDialog.h"
#include <QDateEdit>
#include <QFormLayout>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include "ElaLineEdit.h"
#include "ElaPlainTextEdit.h"
#include "ElaPushButton.h"
#include "ElaText.h"
ProjectDialog::ProjectDialog(const ThemeTokens& tokens, QWidget* parent)
: ElaDialog(parent)
, m_errorColor(tokens.blockOverdueBorder.name())
{
setWindowTitle(QStringLiteral("新建长期项目"));
setWindowButtonFlags(ElaAppBarType::CloseButtonHint);
setMinimumWidth(460);
resize(460, 390);
auto* root = new QVBoxLayout(this);
root->setContentsMargins(22, 8, 22, 18);
root->setSpacing(12);
auto* form = new QFormLayout();
form->setLabelAlignment(Qt::AlignLeft | Qt::AlignTop);
form->setHorizontalSpacing(14);
form->setVerticalSpacing(12);
auto* titleLabel = new ElaText(QStringLiteral("项目标题"), 13, this);
m_titleEdit = new ElaLineEdit(this);
m_titleEdit->setPlaceholderText(QStringLiteral("例如:完成飞行控制器项目"));
m_titleEdit->setClearButtonEnabled(true);
m_titleEdit->setMinimumHeight(34);
auto* descriptionLabel = new ElaText(QStringLiteral("说明"), 13, this);
m_descriptionEdit = new ElaPlainTextEdit(this);
m_descriptionEdit->setPlaceholderText(QStringLiteral("目标、范围或验收标准(可选)"));
m_descriptionEdit->setMinimumHeight(130);
auto* deadlineLabel = new ElaText(QStringLiteral("模糊截止"), 13, this);
m_deadlineEdit = new QDateEdit(this);
m_deadlineEdit->setCalendarPopup(true);
m_deadlineEdit->setDisplayFormat(QStringLiteral("yyyy-MM-dd"));
m_deadlineEdit->setDate(QDate::currentDate().addMonths(1));
m_deadlineEdit->setMinimumHeight(34);
form->addRow(titleLabel, m_titleEdit);
form->addRow(descriptionLabel, m_descriptionEdit);
form->addRow(deadlineLabel, m_deadlineEdit);
root->addLayout(form);
m_errorLabel = new ElaText(this);
m_errorLabel->setTextPixelSize(12);
m_errorLabel->setStyleSheet(QStringLiteral("color:%1;").arg(m_errorColor));
m_errorLabel->setMinimumHeight(18);
root->addWidget(m_errorLabel);
root->addStretch(1);
auto* buttonRow = new QHBoxLayout();
buttonRow->addStretch(1);
auto* cancel = new ElaPushButton(QStringLiteral("取消"), this);
auto* save = new ElaPushButton(QStringLiteral("保存"), this);
cancel->setFixedSize(88, 34);
save->setFixedSize(88, 34);
save->setDefault(true);
buttonRow->addWidget(cancel);
buttonRow->addWidget(save);
root->addLayout(buttonRow);
connect(cancel, &ElaPushButton::clicked, this, &ProjectDialog::reject);
connect(save, &ElaPushButton::clicked, this, &ProjectDialog::accept);
}
void ProjectDialog::setValues(const QString& title, const QString& description, const QDate& deadline)
{
m_titleEdit->setText(title);
m_descriptionEdit->setPlainText(description);
if (deadline.isValid())
{
m_deadlineEdit->setDate(deadline);
}
m_titleEdit->setFocus();
m_titleEdit->selectAll();
}
QString ProjectDialog::titleValue() const
{
return m_titleEdit->text().trimmed();
}
QString ProjectDialog::descriptionValue() const
{
return m_descriptionEdit->toPlainText().trimmed();
}
QDate ProjectDialog::deadlineValue() const
{
return m_deadlineEdit->date();
}
void ProjectDialog::updateError(const QString& message)
{
m_errorLabel->setText(message);
}
void ProjectDialog::accept()
{
const QString title = titleValue();
if (title.isEmpty())
{
updateError(QStringLiteral("请输入项目标题"));
return;
}
if (!deadlineValue().isValid())
{
updateError(QStringLiteral("请选择截止日期"));
return;
}
updateError(QString());
QDialog::accept();
}
+42
View File
@@ -0,0 +1,42 @@
#pragma once
#include <QDate>
#include <QString>
#include "ElaDialog.h"
#include "ui/theme/ThemeTokens.h"
class ElaLineEdit;
class ElaPlainTextEdit;
class ElaText;
class QDateEdit;
/*
* 类名: ProjectDialog
* 功能: 手工创建/编辑长期项目(标题、说明、模糊截止日期)
* 线程安全: 否;UI 线程
*/
class ProjectDialog : public ElaDialog
{
Q_OBJECT
public:
explicit ProjectDialog(const ThemeTokens& tokens, QWidget* parent = nullptr);
void setValues(const QString& title, const QString& description, const QDate& deadline);
QString titleValue() const;
QString descriptionValue() const;
QDate deadlineValue() const;
public slots:
void accept() override;
private:
void updateError(const QString& message);
ElaLineEdit* m_titleEdit = nullptr;
ElaPlainTextEdit* m_descriptionEdit = nullptr;
QDateEdit* m_deadlineEdit = nullptr;
ElaText* m_errorLabel = nullptr;
QString m_errorColor;
};
+156
View File
@@ -0,0 +1,156 @@
#include "SearchDialog.h"
#include <QHBoxLayout>
#include <QListWidget>
#include <QTimer>
#include <QVBoxLayout>
#include "ElaLineEdit.h"
#include "ElaText.h"
#include "ui/theme/AnimationUtils.h"
#include "core/DateTimeUtils.h"
#include "services/ScheduleService.h"
namespace
{
QString statusLabel(const QString& status)
{
if (status == QStringLiteral("done"))
{
return QStringLiteral("已完成");
}
if (status == QStringLiteral("in_progress"))
{
return QStringLiteral("进行中");
}
if (status == QStringLiteral("dropped"))
{
return QStringLiteral("已放弃");
}
if (status == QStringLiteral("missed"))
{
return QStringLiteral("已错过");
}
return QStringLiteral("待办");
}
} // namespace
SearchDialog::SearchDialog(ScheduleService& scheduleService,
const ThemeTokens& tokens,
const QString& initialQuery,
QWidget* parent)
: ElaDialog(parent)
, m_scheduleService(scheduleService)
, m_tokens(tokens)
{
setWindowTitle(QStringLiteral("搜索日程"));
setWindowButtonFlags(ElaAppBarType::CloseButtonHint);
resize(620, 520);
setMinimumWidth(520);
auto* root = new QVBoxLayout(this);
root->setContentsMargins(22, 8, 22, 18);
root->setSpacing(10);
auto* searchRow = new QHBoxLayout();
searchRow->setSpacing(10);
m_searchEdit = new ElaLineEdit(this);
m_searchEdit->setPlaceholderText(QStringLiteral("输入标题或说明,回车打开第一条结果"));
m_searchEdit->setClearButtonEnabled(true);
m_searchEdit->setMinimumHeight(36);
m_searchEdit->setText(initialQuery);
m_countLabel = new ElaText(this);
m_countLabel->setTextPixelSize(11);
m_countLabel->setTextStyle(ElaTextType::Caption);
searchRow->addWidget(m_searchEdit, 1);
searchRow->addWidget(m_countLabel, 0, Qt::AlignVCenter);
root->addLayout(searchRow);
m_results = new QListWidget(this);
m_results->setFrameShape(QFrame::NoFrame);
m_results->setAlternatingRowColors(false);
m_results->setUniformItemSizes(false);
m_results->setWordWrap(true);
m_results->setSelectionMode(QAbstractItemView::SingleSelection);
m_results->setStyleSheet(
QStringLiteral("QListWidget{background:transparent;border:none;outline:none;}"
"QListWidget::item{padding:9px 10px;border-radius:8px;color:%1;}"
"QListWidget::item:selected{background:%2;color:%3;}")
.arg(tokens.textPrimary.name(), tokens.accent.name(), tokens.onAccent.name()));
root->addWidget(m_results, 1);
m_searchTimer = new QTimer(this);
m_searchTimer->setSingleShot(true);
m_searchTimer->setInterval(140);
connect(m_searchTimer, &QTimer::timeout, this, &SearchDialog::executeSearch);
connect(m_searchEdit, &ElaLineEdit::textChanged, this, &SearchDialog::scheduleSearch);
connect(m_searchEdit, &ElaLineEdit::returnPressed, this, &SearchDialog::selectCurrent);
connect(m_results, &QListWidget::itemActivated, this, [this](QListWidgetItem* item) {
if (!item)
{
return;
}
Q_EMIT blockSelected(item->data(Qt::UserRole + 1).toDate(),
item->data(Qt::UserRole).toString());
accept();
});
connect(m_results, &QListWidget::itemDoubleClicked, this, [this](QListWidgetItem* item) {
if (!item)
{
return;
}
Q_EMIT blockSelected(item->data(Qt::UserRole + 1).toDate(),
item->data(Qt::UserRole).toString());
accept();
});
m_searchEdit->setFocus();
m_searchEdit->selectAll();
executeSearch();
QTimer::singleShot(0, this, [this]() { AnimationUtils::fadeWindow(this); });
}
void SearchDialog::scheduleSearch()
{
m_searchTimer->start();
}
void SearchDialog::executeSearch()
{
if (!m_results)
{
return;
}
const QVector<ScheduleItem> items = m_scheduleService.search(m_searchEdit->text(), 100);
m_results->clear();
for (const ScheduleItem& item : items)
{
const QString text = QStringLiteral("%1 · %2 %3 · %4")
.arg(item.task.title,
item.block.startAt.date().toString(QStringLiteral("MM-dd")),
DateTimeUtils::formatTimeRange(item.block.startAt, item.block.endAt),
statusLabel(item.block.status));
auto* row = new QListWidgetItem(text, m_results);
row->setData(Qt::UserRole, item.block.id);
row->setData(Qt::UserRole + 1, item.block.startAt.date());
row->setSizeHint(QSize(0, 40));
}
m_countLabel->setText(items.isEmpty() ? QStringLiteral("无结果")
: QStringLiteral("%1 条结果").arg(items.size()));
if (!items.isEmpty())
{
m_results->setCurrentRow(0);
}
}
void SearchDialog::selectCurrent()
{
QListWidgetItem* item = m_results->currentItem();
if (!item)
{
return;
}
Q_EMIT blockSelected(item->data(Qt::UserRole + 1).toDate(),
item->data(Qt::UserRole).toString());
accept();
}
+44
View File
@@ -0,0 +1,44 @@
#pragma once
#include <QDate>
#include <QString>
#include "ElaDialog.h"
#include "ui/theme/ThemeTokens.h"
class ElaLineEdit;
class ElaText;
class QListWidget;
class QTimer;
class ScheduleService;
/*
* 类名: SearchDialog
* 功能: 按标题/说明搜索日程,选择结果后跳转到对应日期
* 线程安全: 否;UI 线程
*/
class SearchDialog : public ElaDialog
{
Q_OBJECT
public:
SearchDialog(ScheduleService& scheduleService,
const ThemeTokens& tokens,
const QString& initialQuery = {},
QWidget* parent = nullptr);
signals:
void blockSelected(const QDate& date, const QString& blockId);
private:
void scheduleSearch();
void executeSearch();
void selectCurrent();
ScheduleService& m_scheduleService;
ThemeTokens m_tokens;
ElaLineEdit* m_searchEdit = nullptr;
ElaText* m_countLabel = nullptr;
QListWidget* m_results = nullptr;
QTimer* m_searchTimer = nullptr;
};
+45 -1
View File
@@ -5,6 +5,7 @@
#include <QHBoxLayout>
#include <QLineEdit>
#include <QVBoxLayout>
#include <QTimer>
#include "ElaComboBox.h"
#include "ElaLineEdit.h"
@@ -12,6 +13,7 @@
#include "ElaText.h"
#include "ElaToggleSwitch.h"
#include "ElaToolButton.h"
#include "ui/theme/AnimationUtils.h"
#include "ui/theme/ThemeManager.h"
#include "ui/theme/WindowEffects.h"
#include "utils/AppSettings.h"
@@ -23,7 +25,7 @@ SettingsDialog::SettingsDialog(ThemeManager& themeManager, AppSettings& settings
{
setWindowTitle(QStringLiteral("设置"));
setWindowButtonFlags(ElaAppBarType::CloseButtonHint);
resize(560, 720);
resize(560, 820);
setMinimumWidth(520);
auto* root = new QVBoxLayout(this);
@@ -153,6 +155,39 @@ SettingsDialog::SettingsDialog(ThemeManager& themeManager, AppSettings& settings
keyNote->setWordWrap(true);
root->addWidget(keyNote);
addDivider();
addSectionTitle(QStringLiteral("日程提醒"));
auto* reminderDescription = new ElaText(
QStringLiteral("日程开始时发送系统通知;可额外提前 N 分钟再提醒一次。"),
11,
this);
reminderDescription->setTextStyle(ElaTextType::Caption);
reminderDescription->setWordWrap(true);
root->addWidget(reminderDescription);
auto* reminderRow = new QHBoxLayout();
reminderRow->setSpacing(16);
auto* reminderLabel = new ElaText(QStringLiteral("提前提醒"), 13, this);
m_reminderLeadCombo = new ElaComboBox(this);
const QList<int> leadValues = {0, 5, 10, 15, 30, 60};
for (int minutes : leadValues)
{
m_reminderLeadCombo->addItem(minutes == 0 ? QStringLiteral("仅开始时")
: QStringLiteral("提前 %1 分钟").arg(minutes));
}
int leadIndex = leadValues.indexOf(m_settings.reminderLeadMinutes());
if (leadIndex < 0)
{
leadIndex = 2;
}
m_reminderLeadCombo->setCurrentIndex(leadIndex);
m_reminderLeadCombo->setFixedSize(180, 32);
reminderRow->addWidget(reminderLabel, 0, Qt::AlignVCenter);
reminderRow->addWidget(m_reminderLeadCombo, 0, Qt::AlignVCenter);
reminderRow->addStretch(1);
root->addLayout(reminderRow);
addDivider();
addSectionTitle(QStringLiteral("同步服务"));
@@ -236,6 +271,14 @@ SettingsDialog::SettingsDialog(ThemeManager& themeManager, AppSettings& settings
connect(m_modelEdit, &ElaLineEdit::editingFinished, this, &SettingsDialog::saveAiConfig);
connect(m_apiKeyEdit, &ElaLineEdit::editingFinished, this, &SettingsDialog::saveAiConfig);
connect(m_keyVisibilityButton, &ElaToolButton::clicked, this, &SettingsDialog::toggleKeyVisibility);
connect(m_reminderLeadCombo, &ElaComboBox::currentIndexChanged, this, [this](int index) {
static const int values[] = {0, 5, 10, 15, 30, 60};
if (index >= 0 && index < 6)
{
m_settings.setReminderLeadMinutes(values[index]);
Q_EMIT reminderSettingsChanged();
}
});
connect(m_syncUrlEdit, &ElaLineEdit::editingFinished, this, &SettingsDialog::saveSyncConfig);
connect(m_syncEnabledSwitch, &ElaToggleSwitch::toggled, this, [this](bool) { saveSyncConfig(); });
connect(doneButton, &ElaPushButton::clicked, this, [this]() {
@@ -247,6 +290,7 @@ SettingsDialog::SettingsDialog(ThemeManager& themeManager, AppSettings& settings
saveAiConfig();
saveSyncConfig();
});
QTimer::singleShot(0, this, [this]() { AnimationUtils::fadeWindow(this); });
}
void SettingsDialog::saveAiConfig()
+2
View File
@@ -24,6 +24,7 @@ public:
signals:
void micaChanged(bool enabled);
void syncSettingsChanged();
void reminderSettingsChanged();
private:
void saveAiConfig();
@@ -38,6 +39,7 @@ private:
ElaLineEdit* m_modelEdit = nullptr;
ElaLineEdit* m_apiKeyEdit = nullptr;
ElaToolButton* m_keyVisibilityButton = nullptr;
ElaComboBox* m_reminderLeadCombo = nullptr;
ElaLineEdit* m_syncUrlEdit = nullptr;
ElaToggleSwitch* m_syncEnabledSwitch = nullptr;
};
+2
View File
@@ -19,6 +19,7 @@
#include "ElaScrollArea.h"
#include "ElaText.h"
#include "ui/panels/DiffPreviewCard.h"
#include "ui/theme/AnimationUtils.h"
ChatPanel::ChatPanel(AIService& aiService, QWidget* parent)
: QWidget(parent)
@@ -178,6 +179,7 @@ void ChatPanel::rebuildMessages()
m_aiService.rejectDiff(diffId);
});
m_messageLayout->addWidget(card);
AnimationUtils::fadeIn(card, 180);
continue;
}
+62 -3
View File
@@ -105,6 +105,7 @@ DiffPreviewCard::DiffPreviewCard(const ScheduleProposal& proposal,
break;
}
}
const int projectCount = proposal.projects.size();
QStringList parts;
if (creates > 0)
{
@@ -118,10 +119,14 @@ DiffPreviewCard::DiffPreviewCard(const ScheduleProposal& proposal,
{
parts.append(QStringLiteral("删除 %1").arg(deletes));
}
if (projectCount > 0)
{
parts.append(QStringLiteral("长期项目 %1").arg(projectCount));
}
auto* header = new QHBoxLayout();
header->setSpacing(8);
auto* title = new QLabel(QStringLiteral("AI 日程建议"), this);
auto* title = new QLabel(QStringLiteral("AI 计划建议"), this);
title->setStyleSheet(QStringLiteral("background:transparent;border:none;color:%1;font-size:13px;font-weight:600;")
.arg(m_tokens.textPrimary.name()));
auto* count = new QLabel(parts.join(QStringLiteral(" · ")), this);
@@ -140,6 +145,7 @@ DiffPreviewCard::DiffPreviewCard(const ScheduleProposal& proposal,
check->setChecked(state == State::Pending);
check->setEnabled(state == State::Pending);
m_checks.append(check);
m_tempIds.append(entry.tempId);
auto* textLayout = new QVBoxLayout();
textLayout->setSpacing(1);
@@ -232,6 +238,59 @@ DiffPreviewCard::DiffPreviewCard(const ScheduleProposal& proposal,
connect(check, &ElaCheckBox::toggled, this, &DiffPreviewCard::updateAcceptEnabled);
}
for (const ProposedProjectEntry& project : proposal.projects)
{
auto* row = new QHBoxLayout();
row->setSpacing(8);
auto* check = new ElaCheckBox(this);
check->setChecked(state == State::Pending);
check->setEnabled(state == State::Pending);
m_checks.append(check);
m_tempIds.append(project.tempId);
auto* textLayout = new QVBoxLayout();
textLayout->setSpacing(1);
auto* titleRow = new QHBoxLayout();
titleRow->setSpacing(6);
auto* opLabel = new QLabel(QStringLiteral("长期项目"), this);
opLabel->setStyleSheet(
QStringLiteral("background:transparent;border:none;color:%1;font-size:10px;font-weight:600;")
.arg(m_tokens.diffAdd.name()));
auto* titleLabel = new QLabel(project.title, this);
titleLabel->setWordWrap(true);
titleLabel->setStyleSheet(
QStringLiteral("background:transparent;border:none;color:%1;font-size:12px;font-weight:600;")
.arg(m_tokens.textPrimary.name()));
titleRow->addWidget(opLabel, 0, Qt::AlignTop);
titleRow->addWidget(titleLabel, 1);
textLayout->addLayout(titleRow);
if (project.deadline.has_value())
{
auto* deadline = new QLabel(
QStringLiteral("截止 %1(剩余 %2 天)")
.arg(project.deadline->toString(QStringLiteral("yyyy-MM-dd")))
.arg(QDate::currentDate().daysTo(*project.deadline)),
this);
deadline->setStyleSheet(
QStringLiteral("background:transparent;border:none;color:%1;font-size:11px;")
.arg(m_tokens.textSecondary.name()));
textLayout->addWidget(deadline);
}
if (!project.description.isEmpty())
{
auto* description = new QLabel(project.description, this);
description->setWordWrap(true);
description->setStyleSheet(
QStringLiteral("background:transparent;border:none;color:%1;font-size:11px;")
.arg(m_tokens.textMuted.name()));
textLayout->addWidget(description);
}
row->addWidget(check, 0, Qt::AlignTop);
row->addLayout(textLayout, 1);
root->addLayout(row);
connect(check, &ElaCheckBox::toggled, this, &DiffPreviewCard::updateAcceptEnabled);
}
auto* buttonRow = new QHBoxLayout();
buttonRow->setSpacing(8);
buttonRow->addStretch(1);
@@ -257,9 +316,9 @@ DiffPreviewCard::DiffPreviewCard(const ScheduleProposal& proposal,
QStringList tempIds;
for (int i = 0; i < m_checks.size(); ++i)
{
if (m_checks.at(i)->isChecked() && i < m_proposal.entries.size())
if (m_checks.at(i)->isChecked() && i < m_tempIds.size())
{
tempIds.append(m_proposal.entries.at(i).tempId);
tempIds.append(m_tempIds.at(i));
}
}
setResolved(State::Applied);
+1
View File
@@ -45,6 +45,7 @@ private:
ThemeTokens m_tokens;
State m_state;
QVector<ElaCheckBox*> m_checks;
QStringList m_tempIds;
ElaPushButton* m_acceptButton = nullptr;
ElaPushButton* m_rejectButton = nullptr;
QLabel* m_statusLabel = nullptr;
+97
View File
@@ -0,0 +1,97 @@
#include "ProjectCard.h"
#include <QAction>
#include <QHBoxLayout>
#include <QLabel>
#include <QMouseEvent>
#include <QVBoxLayout>
#include "ElaMenu.h"
#include "ElaToolButton.h"
ProjectCard::ProjectCard(const Project& project, const ThemeTokens& tokens, QWidget* parent)
: QFrame(parent)
, m_project(project)
, m_tokens(tokens)
{
setObjectName(QStringLiteral("ProjectCard"));
setCursor(Qt::PointingHandCursor);
setStyleSheet(QStringLiteral(
"QFrame#ProjectCard{background:%1;border:1px solid %2;border-left:3px solid %3;"
"border-radius:9px;}"
"QFrame#ProjectCard:hover{background:%4;}")
.arg(m_tokens.cardBackground.name(),
m_tokens.cardBorder.name(),
m_tokens.accent.name(),
m_tokens.cardHoverBackground.name()));
auto* row = new QHBoxLayout(this);
row->setContentsMargins(10, 7, 6, 7);
row->setSpacing(4);
auto* textLayout = new QVBoxLayout();
textLayout->setSpacing(2);
auto* title = new QLabel(m_project.title, this);
title->setWordWrap(true);
title->setStyleSheet(QStringLiteral("background:transparent;border:none;color:%1;font-size:12px;font-weight:600;")
.arg(m_tokens.textPrimary.name()));
auto* deadline = new QLabel(deadlineText(), this);
const bool overdue = m_project.deadline.has_value() &&
m_project.deadline->isValid() &&
QDate::currentDate().daysTo(*m_project.deadline) < 0;
deadline->setStyleSheet(QStringLiteral("background:transparent;border:none;color:%1;font-size:11px;")
.arg(overdue ? m_tokens.blockOverdueBorder.name() : m_tokens.textMuted.name()));
textLayout->addWidget(title);
textLayout->addWidget(deadline);
row->addLayout(textLayout, 1);
m_menuButton = new ElaToolButton(this);
m_menuButton->setIsTransparent(true);
m_menuButton->setFixedSize(26, 26);
m_menuButton->setElaIcon(ElaIconType::EllipsisVertical);
m_menuButton->setToolTip(QStringLiteral("项目操作"));
auto* menu = new ElaMenu(this);
QAction* edit = menu->addAction(QStringLiteral("编辑"));
connect(edit, &QAction::triggered, this, [this]() { Q_EMIT editRequested(m_project.id); });
QAction* done = menu->addAction(QStringLiteral("标记完成"));
connect(done, &QAction::triggered, this, [this]() { Q_EMIT statusChangeRequested(m_project.id, QStringLiteral("done")); });
menu->addSeparator();
QAction* remove = menu->addAction(QStringLiteral("删除"));
connect(remove, &QAction::triggered, this, [this]() { Q_EMIT deleteRequested(m_project.id); });
m_menuButton->setMenu(menu);
m_menuButton->setPopupMode(QToolButton::InstantPopup);
row->addWidget(m_menuButton, 0, Qt::AlignTop);
}
QString ProjectCard::deadlineText() const
{
if (!m_project.deadline.has_value() || !m_project.deadline->isValid())
{
return QStringLiteral("无截止日期");
}
const int days = QDate::currentDate().daysTo(*m_project.deadline);
if (days < 0)
{
return QStringLiteral("截止 %1 · 已逾期 %2 天")
.arg(m_project.deadline->toString(QStringLiteral("M月d日")))
.arg(-days);
}
if (days == 0)
{
return QStringLiteral("截止 今天");
}
return QStringLiteral("截止 %1 · 剩余 %2 天")
.arg(m_project.deadline->toString(QStringLiteral("M月d日")))
.arg(days);
}
void ProjectCard::mouseReleaseEvent(QMouseEvent* event)
{
if (event->button() == Qt::LeftButton && rect().contains(event->position().toPoint()))
{
Q_EMIT editRequested(m_project.id);
event->accept();
return;
}
QFrame::mouseReleaseEvent(event);
}
+36
View File
@@ -0,0 +1,36 @@
#pragma once
#include <QFrame>
#include "core/Project.h"
#include "ui/theme/ThemeTokens.h"
class ElaToolButton;
/*
* 类名: ProjectCard
* 功能: 长期项目卡片;显示模糊截止日期与剩余天数
* 线程安全: 否;UI 线程
*/
class ProjectCard : public QFrame
{
Q_OBJECT
public:
ProjectCard(const Project& project, const ThemeTokens& tokens, QWidget* parent = nullptr);
signals:
void editRequested(const QString& projectId);
void statusChangeRequested(const QString& projectId, const QString& status);
void deleteRequested(const QString& projectId);
protected:
void mouseReleaseEvent(QMouseEvent* event) override;
private:
QString deadlineText() const;
Project m_project;
ThemeTokens m_tokens;
ElaToolButton* m_menuButton = nullptr;
};
+81 -3
View File
@@ -10,7 +10,10 @@
#include "ElaScrollArea.h"
#include "ElaText.h"
#include "ElaToolButton.h"
#include "ProjectCard.h"
#include "TodayItemCard.h"
#include "ui/theme/AnimationUtils.h"
TodayPanel::TodayPanel(QWidget* parent)
: QWidget(parent)
@@ -31,11 +34,42 @@ TodayPanel::TodayPanel(QWidget* parent)
m_titleLabel->setFont(titleFont);
m_countLabel = new ElaText(this);
m_countLabel->setTextPixelSize(11);
m_reviewButton = new ElaToolButton(this);
m_reviewButton->setIsTransparent(true);
m_reviewButton->setElaIcon(ElaIconType::ClipboardCheck);
m_reviewButton->setFixedSize(26, 26);
m_reviewButton->setToolTip(QStringLiteral("今日复盘 (Ctrl+R)"));
connect(m_reviewButton, &ElaToolButton::clicked, this, &TodayPanel::reviewRequested);
m_achievementsButton = new ElaToolButton(this);
m_achievementsButton->setIsTransparent(true);
m_achievementsButton->setElaIcon(ElaIconType::Medal);
m_achievementsButton->setFixedSize(26, 26);
m_achievementsButton->setToolTip(QStringLiteral("已完成汇总"));
connect(m_achievementsButton, &ElaToolButton::clicked, this, &TodayPanel::achievementsRequested);
m_newProjectButton = new ElaToolButton(this);
m_newProjectButton->setIsTransparent(true);
m_newProjectButton->setElaIcon(ElaIconType::FolderPlus);
m_newProjectButton->setFixedSize(26, 26);
m_newProjectButton->setToolTip(QStringLiteral("新建长期项目"));
connect(m_newProjectButton, &ElaToolButton::clicked, this, &TodayPanel::newProjectRequested);
header->addWidget(m_titleLabel);
header->addStretch(1);
header->addWidget(m_countLabel, 0, Qt::AlignVCenter);
header->addWidget(m_achievementsButton, 0, Qt::AlignVCenter);
header->addWidget(m_newProjectButton, 0, Qt::AlignVCenter);
header->addWidget(m_reviewButton, 0, Qt::AlignVCenter);
root->addLayout(header);
m_insightLabel = new ElaText(this);
m_insightLabel->setTextPixelSize(11);
m_insightLabel->setTextStyle(ElaTextType::Caption);
m_insightLabel->setWordWrap(true);
m_insightLabel->setVisible(false);
root->addWidget(m_insightLabel);
m_scrollArea = new ElaScrollArea(this);
m_scrollArea->setWidgetResizable(true);
m_scrollArea->setFrameShape(QFrame::NoFrame);
@@ -59,9 +93,23 @@ TodayPanel::TodayPanel(QWidget* parent)
void TodayPanel::setTokens(const ThemeTokens& tokens)
{
m_tokens = tokens;
if (m_insightLabel)
{
m_insightLabel->setStyleSheet(QStringLiteral("color:%1;").arg(tokens.accent.name()));
}
rebuild();
}
void TodayPanel::setInsightText(const QString& text)
{
if (!m_insightLabel)
{
return;
}
m_insightLabel->setText(text);
m_insightLabel->setVisible(!text.trimmed().isEmpty());
}
void TodayPanel::setDate(const QDate& date)
{
if (!m_titleLabel)
@@ -83,6 +131,12 @@ void TodayPanel::setItems(const QVector<ScheduleItem>& items, const QDateTime& n
rebuild();
}
void TodayPanel::setProjects(const QVector<Project>& projects)
{
m_projects = projects;
rebuild();
}
void TodayPanel::clearLayout(QVBoxLayout* layout)
{
while (QLayoutItem* item = layout->takeAt(0))
@@ -168,15 +222,32 @@ void TodayPanel::rebuild()
return a.block.id < b.block.id;
});
if (!m_projects.isEmpty())
{
auto* section = new ElaText(QStringLiteral("长期项目 · %1").arg(m_projects.size()), 13, m_listWidget);
QFont sectionFont = section->font();
sectionFont.setWeight(QFont::DemiBold);
section->setFont(sectionFont);
section->setContentsMargins(2, 8, 0, 2);
m_listLayout->addWidget(section);
for (const Project& project : m_projects)
{
auto* card = new ProjectCard(project, m_tokens, m_listWidget);
connect(card, &ProjectCard::editRequested, this, &TodayPanel::editProjectRequested);
connect(card, &ProjectCard::statusChangeRequested, this, &TodayPanel::projectStatusRequested);
connect(card, &ProjectCard::deleteRequested, this, &TodayPanel::deleteProjectRequested);
m_listLayout->addWidget(card);
}
}
if (sorted.isEmpty())
{
auto* empty = new ElaText(QStringLiteral("今天还没有安排\n双击时间网格即可新建"), 13, m_listWidget);
empty->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
empty->setMinimumHeight(120);
empty->setMinimumHeight(90);
empty->setTextStyle(ElaTextType::Caption);
m_listLayout->addWidget(empty);
m_listLayout->addStretch(1);
return;
}
for (const ScheduleItem& item : sorted)
@@ -189,5 +260,12 @@ void TodayPanel::rebuild()
connect(card, &TodayItemCard::deleteRequested, this, &TodayPanel::deleteRequested);
m_listLayout->addWidget(card);
}
m_listLayout->addStretch(1);
const int renderedCount = sorted.size() + m_projects.size();
if (m_renderedCount != renderedCount)
{
m_renderedCount = renderedCount;
AnimationUtils::fadeIn(m_listWidget, 150);
}
}
+16
View File
@@ -4,11 +4,13 @@
#include <QVector>
#include <QWidget>
#include "core/Project.h"
#include "core/ScheduleItem.h"
#include "ui/theme/ThemeTokens.h"
class ElaScrollArea;
class ElaText;
class ElaToolButton;
class QVBoxLayout;
/*
@@ -26,6 +28,8 @@ public:
void setTokens(const ThemeTokens& tokens);
void setDate(const QDate& date);
void setItems(const QVector<ScheduleItem>& items, const QDateTime& now);
void setProjects(const QVector<Project>& projects);
void setInsightText(const QString& text);
signals:
void editRequested(const QString& blockId);
@@ -33,6 +37,12 @@ signals:
void postponeRequested(const QString& blockId, int minutes);
void deleteRequested(const QString& blockId);
void focusRequested(const QString& blockId);
void reviewRequested();
void achievementsRequested();
void newProjectRequested();
void editProjectRequested(const QString& projectId);
void projectStatusRequested(const QString& projectId, const QString& status);
void deleteProjectRequested(const QString& projectId);
private:
void rebuild();
@@ -40,11 +50,17 @@ private:
ThemeTokens m_tokens;
QVector<ScheduleItem> m_items;
QVector<Project> m_projects;
QDateTime m_now;
ElaText* m_titleLabel = nullptr;
ElaText* m_countLabel = nullptr;
ElaText* m_insightLabel = nullptr;
ElaToolButton* m_reviewButton = nullptr;
ElaToolButton* m_newProjectButton = nullptr;
ElaToolButton* m_achievementsButton = nullptr;
ElaScrollArea* m_scrollArea = nullptr;
QWidget* m_listWidget = nullptr;
QVBoxLayout* m_listLayout = nullptr;
int m_renderedCount = -1;
};
+46
View File
@@ -0,0 +1,46 @@
#include "AnimationUtils.h"
#include <QGraphicsOpacityEffect>
#include <QPropertyAnimation>
#include <QWidget>
namespace AnimationUtils
{
void fadeIn(QWidget* widget, int durationMs)
{
if (!widget)
{
return;
}
widget->setGraphicsEffect(nullptr);
auto* effect = new QGraphicsOpacityEffect(widget);
effect->setOpacity(0.0);
widget->setGraphicsEffect(effect);
auto* animation = new QPropertyAnimation(effect, "opacity", widget);
animation->setDuration(durationMs);
animation->setStartValue(0.0);
animation->setEndValue(1.0);
animation->setEasingCurve(QEasingCurve::OutCubic);
QObject::connect(animation, &QPropertyAnimation::finished, widget, [widget, animation]() {
widget->setGraphicsEffect(nullptr);
animation->deleteLater();
});
animation->start();
}
void fadeWindow(QWidget* window, int durationMs)
{
if (!window)
{
return;
}
auto* animation = new QPropertyAnimation(window, "windowOpacity", window);
animation->setDuration(durationMs);
animation->setStartValue(0.0);
animation->setEndValue(1.0);
animation->setEasingCurve(QEasingCurve::OutCubic);
QObject::connect(animation, &QPropertyAnimation::finished, animation, &QPropertyAnimation::deleteLater);
window->setWindowOpacity(0.0);
animation->start();
}
} // namespace AnimationUtils

Some files were not shown because too many files have changed in this diff Show More