feat: implement AI schedule app with multi-device sync

- Qt 6 desktop client with day/month/year views, AI scheduling, and TOML settings\n- Go sync server with SQLite change stream, WebSocket notifications, and Docker deployment\n- Client outbox/LWW sync, offline retry, and dual-client integration tests\n- Linux fcitx5 setup, validation reports, and Windows MinGW preset
This commit is contained in:
Misaki
2026-10-26 13:58:45 +08:00
commit 5be7f7f04b
151 changed files with 38485 additions and 0 deletions
+9
View File
@@ -0,0 +1,9 @@
* text=auto
*.png binary
*.jpg binary
*.ico binary
*.db binary
*.sh text eol=lf
*.bat text eol=crlf
+15
View File
@@ -0,0 +1,15 @@
build/
cmake-build-*/
*.user
*.autosave
compile_commands.json
.cache/
.idea/
.vscode/
*.db
*.db-wal
*.db-shm
server/bin/
config.toml
config.toml.bak
server/data/
+3
View File
@@ -0,0 +1,3 @@
[submodule "client/3rd/ElaWidgetTools"]
path = client/3rd/ElaWidgetTools
url = https://github.com/Liniyous/ElaWidgetTools.git
+32
View File
@@ -0,0 +1,32 @@
cmake_minimum_required(VERSION 3.24)
project(Schedule VERSION 0.1.0 LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
option(SCHEDULE_WARNINGS_AS_ERRORS "Treat compiler warnings as errors" ON)
if(MSVC)
add_compile_options(/utf-8)
endif()
enable_testing()
find_program(GO_EXECUTABLE go)
if(GO_EXECUTABLE)
add_custom_target(schedule-sync-server ALL
COMMAND ${GO_EXECUTABLE} build -trimpath -o
${CMAKE_BINARY_DIR}/bin/schedule-sync-server${CMAKE_EXECUTABLE_SUFFIX} ./cmd/server
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}/server
COMMENT "Building Go sync server"
VERBATIM
)
add_test(NAME go_server_tests COMMAND ${GO_EXECUTABLE} test ./...)
set_tests_properties(go_server_tests PROPERTIES
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}/server
)
endif()
add_subdirectory(client)
+148
View File
@@ -0,0 +1,148 @@
{
"version": 6,
"cmakeMinimumRequired": {
"major": 3,
"minor": 24,
"patch": 0
},
"configurePresets": [
{
"name": "linux-gcc",
"displayName": "Linux GCC (Qt 6.6.3)",
"description": "Debug build using the local Qt 6.6.3 installation",
"generator": "Ninja",
"binaryDir": "${sourceDir}/build/linux-gcc",
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Debug",
"CMAKE_PREFIX_PATH": "/home/misaki/Qt6.3/6.6.3/gcc_64",
"CMAKE_EXPORT_COMPILE_COMMANDS": "ON",
"SCHEDULE_WARNINGS_AS_ERRORS": "ON"
},
"warnings": {
"deprecated": false
}
},
{
"name": "linux-gcc-release",
"displayName": "Linux GCC Release (Qt 6.6.3)",
"inherits": "linux-gcc",
"binaryDir": "${sourceDir}/build/linux-gcc-release",
"cacheVariables": {
"CMAKE_BUILD_TYPE": "RelWithDebInfo"
},
"warnings": {
"deprecated": false
}
},
{
"name": "windows-msvc",
"displayName": "Windows MSVC (set QT_ROOT)",
"generator": "Ninja",
"binaryDir": "${sourceDir}/build/windows-msvc",
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Debug",
"CMAKE_PREFIX_PATH": "$env{QT_ROOT}"
},
"warnings": {
"deprecated": false
}
},
{
"name": "windows-mingw",
"displayName": "Windows MinGW-w64 (set QT_ROOT and MINGW_ROOT)",
"description": "Debug build using Qt's MinGW kit and the matching MinGW toolchain",
"generator": "Ninja",
"binaryDir": "${sourceDir}/build/windows-mingw",
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Debug",
"CMAKE_PREFIX_PATH": "$env{QT_ROOT}",
"CMAKE_C_COMPILER": "$env{MINGW_ROOT}/bin/gcc.exe",
"CMAKE_CXX_COMPILER": "$env{MINGW_ROOT}/bin/g++.exe",
"CMAKE_RC_COMPILER": "$env{MINGW_ROOT}/bin/windres.exe",
"CMAKE_EXPORT_COMPILE_COMMANDS": "ON"
},
"warnings": {
"deprecated": false
}
},
{
"name": "macos-clang",
"displayName": "macOS Clang (set QT_ROOT)",
"generator": "Ninja",
"binaryDir": "${sourceDir}/build/macos-clang",
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Debug",
"CMAKE_PREFIX_PATH": "$env{QT_ROOT}"
},
"warnings": {
"deprecated": false
}
}
],
"buildPresets": [
{
"name": "linux-gcc",
"configurePreset": "linux-gcc"
},
{
"name": "linux-gcc-release",
"configurePreset": "linux-gcc-release"
},
{
"name": "windows-msvc",
"configurePreset": "windows-msvc"
},
{
"name": "windows-mingw",
"configurePreset": "windows-mingw"
},
{
"name": "macos-clang",
"configurePreset": "macos-clang"
}
],
"testPresets": [
{
"name": "linux-gcc",
"configurePreset": "linux-gcc",
"output": {
"outputOnFailure": true
},
"environment": {
"QT_QPA_PLATFORM": "offscreen"
}
},
{
"name": "linux-gcc-release",
"configurePreset": "linux-gcc-release",
"output": {
"outputOnFailure": true
},
"environment": {
"QT_QPA_PLATFORM": "offscreen"
}
},
{
"name": "windows-msvc",
"configurePreset": "windows-msvc",
"output": {
"outputOnFailure": true
},
"environment": {
"QT_QPA_PLATFORM": "offscreen",
"PATH": "$env{QT_ROOT}/bin;$penv{PATH}"
}
},
{
"name": "windows-mingw",
"configurePreset": "windows-mingw",
"output": {
"outputOnFailure": true
},
"environment": {
"QT_QPA_PLATFORM": "offscreen",
"PATH": "$env{QT_ROOT}/bin;$env{MINGW_ROOT}/bin;$penv{PATH}"
}
}
]
}
+210
View File
@@ -0,0 +1,210 @@
# AI 驱动日程软件
细粒度个人日程 + AI 自然语言排程 + 自部署多设备同步。
当前进度:**阶段 0 + 阶段 1 + 界面重构 + TOML 配置 + AI 日程闭环 + AI 增强(更新/删除/涟漪/拆分)+ 多设备同步**。
本地模型 50 条指令回归已完成:完整 49/50(98%),失败项 #42 单独复测通过。
详细计划见 [`docs/PLAN.md`](docs/PLAN.md),验证记录见 [`docs/validation/`](docs/validation/)。
## 界面结构
- **紧凑主窗口**(默认启动):AI 助手 + 今日任务,顶部可打开详细日程或设置。
- **详细日程窗口**:日 / 月 / 年三种视图、选中日期任务面板、新建/编辑/删除、设置;顶部房屋按钮或关闭窗口回到紧凑窗口。
- **系统托盘**:关闭紧凑窗口时最小化到托盘;托盘可显示主窗口、新建日程、退出。
- **设置**:主题(跟随系统/浅色/深色)、ElaMica 云母效果、AI 接口地址/模型/API Key、同步服务地址/开关。
> 云母效果使用 ElaWidgetTools 的 `ElaMica` 跨平台模拟背景(内置模糊基底图),
> 在 Linux 下不是系统级窗口模糊;后续可在 Windows 上扩展系统 Mica。
## AI 对话与日程建议
1. 打开设置,填写 AI 服务:接口地址(OpenAI 兼容,云端或本地)、模型、API Key。
2. 在紧凑窗口输入自然语言,例如:
- 「明天下午写周报 2 小时」
- 「今晚 23:00 整理资料 30 分钟」
- 「这周找时间复习 1 小时」
3. AI 先流式回复,再给出可勾选的日程建议卡片:
- 支持新增、修改(标题/时间/时长)、删除;
- 与已有日程冲突时,可自动移动受影响的、可移动日程(涟漪重排);
- 长任务在 `splittable` 时可拆成多个时间块;
- 「接受选中」只写入勾选项;若只接受部分导致最终时间冲突,服务层会拒绝落库;
- 「全部拒绝」不修改日程;AI 永不直接写库,确认后才由 ScheduleService 事务写入。
4. 可把文件拖入对话面板,支持:
- 文本:txt / md / csv / json / yaml
- PDF:需要系统 `pdftotext`
- Word:docx 需要 `unzip`,doc 需要 `catdoc`
- 图片:以 data URL 发送,需要模型支持视觉输入
排程由本地确定性 `SchedulerEngine` 完成:避开已确认日程、优先用户指定时间、回退到 08:00–22:00、按 15 分钟粒度、遵守 deadline。
> 隐私提示:拖入文件的文本/图片会发送到你配置的 AI 服务。若需完全离线,请配置本地 OpenAI 兼容模型。
### Linux 中文输入法(fcitx5)
自定义 Qt 安装通常不带 fcitx5 的 Qt6 platform input context 插件;系统包
`fcitx5-frontend-qt6` 又是针对发行版 Qt(如 6.4)编译的,其私有 API 与 Qt 6.6.x 不兼容,无法加载。
本项目提供脚本,按当前自定义 Qt 重新编译并安装 fcitx5 插件:
```bash
./scripts/setup-fcitx5-qt6-plugin.sh
```
默认安装到 `/home/misaki/Qt6.3/6.6.3/gcc_64/plugins/platforminputcontexts/`,也可通过
`QT_ROOT` 指定其他 Qt。安装后需重启应用。验证:
```bash
QT_DEBUG_PLUGINS=1 ./build/linux-gcc/bin/Schedule 2>&1 | grep -i fcitx
```
看到 `loaded library ... libfcitx5platforminputcontextplugin.so` 即成功。
Windows/macOS 使用 Qt 原生输入法支持,不需要该插件。
详细诊断记录见 [`docs/validation/linux-ime.md`](docs/validation/linux-ime.md)。
## 多设备同步
仓库内附带自部署 Go 同步服务端,使用 SQLite(WAL)保存变更流,支持设备注册、增量 push/pull、WebSocket 通知与全量导出。
1. 启动服务端(默认 `:8787`):
```bash
cd server
go run ./cmd/server
```
生产环境请设置 `SYNC_TOKEN_PEPPER`,并用 HTTPS 反向代理;详见 [`server/README.md`](server/README.md)。
2. 在设置中填写同步服务地址并启用多设备同步;首次启用会自动注册设备并保存令牌。
3. 紧凑窗口和详细窗口顶部会显示同步状态(本地 / 同步中 / 已同步 / 离线 / 同步错误)。
客户端使用 SQLite outbox 捕获本地变更,按服务端 `seq` 增量拉取;冲突按 `updated_at` 做 LWW,删除墓碑优先于等时间戳的更新。断线后保留 outbox 并自动重试,WebSocket 断开时退化为定时轮询。同步协议与部署说明见 [`server/README.md`](server/README.md),验证记录见 [`docs/validation/phase-3.md`](docs/validation/phase-3.md)。
## 构建
依赖:CMake ≥ 3.24、Ninja、Qt 6.5+(含 Qt WebSockets)、GCC/Clang(C++20);构建同步服务端需要 Go 1.23+,Docker 部署可选。
```bash
git submodule update --init --recursive
cmake --preset linux-gcc
cmake --build --preset linux-gcc
```
若检测到 Go,构建时会同时生成 `build/linux-gcc/bin/schedule-sync-server`;未安装 Go 时客户端仍可单独构建,同步集成测试会自动跳过。
如果 Qt 不在 `/home/misaki/Qt6.3/6.6.3/gcc_64`,修改 `CMakePresets.json` 中
`linux-gcc` 的 `CMAKE_PREFIX_PATH`,或使用 `windows-mingw` / `windows-msvc` / `macos-clang`
preset 并通过环境变量 `QT_ROOT` 指定 Qt。
### Windows + MinGW
1. 安装 Qt 6.5+ 的 **MinGW 64-bit** 套件,并在 Qt Maintenance Tool 中确认包含 **Qt WebSockets**;
同时安装与该 Qt 套件匹配的 MinGW 工具链(官方安装器通常位于 `C:/Qt/Tools/mingw1120_64`)。
不要混用 MSVC Qt、不同版本的 MinGW Qt 或系统里的其他 g++。
2. 在 PowerShell 中设置环境变量(路径按实际安装修改):
```powershell
$env:QT_ROOT = "C:/Qt/6.6.3/mingw_64"
$env:MINGW_ROOT = "C:/Qt/Tools/mingw1120_64"
$env:Path = "$env:QT_ROOT/bin;$env:MINGW_ROOT/bin;$env:Path"
cmake --preset windows-mingw
cmake --build --preset windows-mingw -j 8
ctest --preset windows-mingw --output-on-failure
```
`windows-mingw` preset 使用 Ninja,并显式指定 `gcc.exe` / `g++.exe` / `windres.exe`,
不会退回 MSVC。测试 preset 会把 Qt 和 MinGW 的 `bin` 加入 `PATH`,并使用
`QT_QPA_PLATFORM=offscreen`,不需要桌面会话。
3. 运行:
```powershell
.\build\windows-mingw\bin\Schedule.exe
```
开发时保持 `QT_ROOT/bin` 在 `PATH` 即可;分发前可用
`$env:QT_ROOT/bin/windeployqt.exe build/windows-mingw/bin/Schedule.exe` 收集 Qt DLL。
4. 若 Windows 上安装了 Go,构建会同时生成 `build/windows-mingw/bin/schedule-sync-server.exe`
并运行双客户端同步集成测试;没有 Go 时该测试自动跳过。也可以把同步服务端跑在 Linux
或另一台机器上,客户端只需填写 `http://<server>:8787`。
### Windows 多设备联调
1. 在服务端机器启动 `go run ./cmd/server`(或 Docker),设置随机 `SYNC_TOKEN_PEPPER`。
2. Windows 客户端设置中填写服务地址并启用同步;首次启用自动注册。
3. 局域网联调时确认 Windows 防火墙允许客户端访问服务端端口;公网使用 HTTPS 反向代理。
4. 两台设备分别创建/修改/删除日程,观察双方状态变为「已同步」,并验证断网后恢复。
## 运行
```bash
./build/linux-gcc/bin/Schedule
```
## 测试
```bash
ctest --preset linux-gcc
```
当前自动化测试(11 组):存储/服务、网格与详细窗口、紧凑窗口、TOML 配置、SchedulerEngine、
AI 编排(15 个用例:流式、修复、更新/删除、涟漪、拆分、冲突保护、多轮历史、文件、删除兜底、无 diff 重试)、
OpenAI 兼容 Provider(本地假 SSE 服务)、AI 对话到接受落库的 UI 全链路、Go 服务端单元/接口/并发测试、双客户端同步集成(含离线重连)。
本地模型回归(50 条真实中文指令):
```bash
cmake --build --preset linux-gcc --target ai_regression
./build/linux-gcc/bin/ai_regression --timeout 180
```
结果与明细:[`docs/validation/ai-regression-real.md`](docs/validation/ai-regression-real.md)。
本地 `qwen` 推理模型平均约 32s/条;删除“所有会议”已通过会议标记 + 本地兜底修复。模型存在随机波动,可选拆分请求可能选择单块 + 涟漪。
## 数据与配置
- 数据库:`~/.local/share/Misaki/Schedule/schedule.db`(SQLite WAL)。
- 配置文件:`~/.config/Misaki/Schedule/config.toml`(TOML,权限 0600)。
- 旧版 `~/.config/Misaki/Schedule.conf` 会在首次启动时自动迁移,原文件保留作备份。
配置包含主题、云母开关、吸附粒度、窗口状态、设备 ID、AI 服务与同步服务:
```toml
[ai]
base_url = "https://api.openai.com/v1"
api_key = ""
model = "gpt-4o-mini"
temperature = 0.2
[sync]
enabled = false
server_url = "http://127.0.0.1:8787"
token = ""
```
AI 接口地址、模型、API Key 与同步服务地址/开关可直接在设置对话框中修改。同步令牌由客户端在注册后自动写入,文件权限 0600。
可用 `SCHEDULE_CONFIG_PATH` / `SCHEDULE_DB_PATH` 环境变量覆盖默认路径。
> API Key 与同步令牌以本地明文保存,通过配置文件 0600 权限保护;不会写入日志。AI 对话与排程会读取 AI 配置。
## 快捷键
### 紧凑窗口
| 快捷键 | 功能 |
|---|---|
| `Ctrl+O` | 打开详细日程 |
| `Ctrl+,` | 打开设置 |
### 详细日程窗口
| 快捷键 | 功能 |
|---|---|
| `Ctrl+1 / 2 / 3` | 切换日 / 月 / 年视图 |
| `Ctrl+W` | 返回紧凑视图 |
| `Ctrl+N` | 新建日程 |
| `Alt+←/→` | 上一段 / 下一段(日/月/年自适应) |
| `Ctrl+T` | 回到今天 |
| `Ctrl+,` | 打开设置 |
| `Ctrl` + 滚轮 | 时间轴缩放(日视图) |
| `Delete` | 删除选中日程(日视图) |
| `Enter` | 编辑选中日程(日视图) |
+37
View File
@@ -0,0 +1,37 @@
# 第三方依赖登记
所有第三方库均放置于 `client/3rd/`,不得直接修改源码;确需修改时使用 patch/fork 并在此记录。
| 库 | 版本 | 来源 | 引入原因 | 许可证 |
|---|---|---|---|---|
| ElaWidgetTools | commit `9cec882` (v2.0.x) | https://github.com/Liniyous/ElaWidgetTools | Fluent 风格控件、无边框窗口、深浅色主题;自绘视图以外的基础 UI | MIT |
| toml++ | v3.4.0 (`toml.hpp` amalgamated) | https://github.com/marzer/tomlplusplus | TOML 配置读写(单头文件,C++17) | MIT |
## 维护方式
```bash
git submodule update --init --recursive
```
升级时在 `client/3rd/ElaWidgetTools` 内切换并锁定提交,然后更新本表。
## Linux 运行时可选组件
| 组件 | 版本 | 来源 | 用途 | 许可证 |
|---|---|---|---|---|
| fcitx5-qt | 5.1.4 | https://github.com/fcitx/fcitx5-qt | fcitx5 的 Qt6 输入法插件;由 `scripts/setup-fcitx5-qt6-plugin.sh` 针对自定义 Qt 编译,不参与项目链接 | BSD-3-Clause |
| extra-cmake-modules | v5.115.0 | https://github.com/KDE/extra-cmake-modules | 构建 fcitx5-qt 插件时的 CMake 模块(仅构建期) | BSD-3-Clause |
## 可选系统工具(文件内容提取)
| 工具 | 用途 | 缺失时行为 |
|---|---|---|
| `pdftotext` | 提取 PDF 文本 | 对话中提示该文件读取失败 |
| `unzip` | 读取 docx 内部 XML | 对话中提示该文件读取失败 |
| `catdoc` | 提取旧版 .doc 文本 | 对话中提示该文件读取失败 |
这些是运行时可选的系统命令,不属于编译期第三方库。
## Go 依赖(阶段 3 起)
后续 Go 依赖通过 `go.mod` 管理,并在 `server/` 对应文档中登记选型理由。
+16
View File
@@ -0,0 +1,16 @@
MIT License
Copyright (c) Mark Gillard <mark.gillard@outlook.com.au>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
File diff suppressed because it is too large Load Diff
+48
View File
@@ -0,0 +1,48 @@
cmake_minimum_required(VERSION 3.24)
find_package(Qt6 6.5 REQUIRED COMPONENTS Core Gui Widgets Sql Network Concurrent WebSockets Test)
qt_standard_project_setup()
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
set(CMAKE_AUTOUIC ON)
# 警告选项集中定义,仅作用于本工程目标,避免第三方库告警阻断构建。
add_library(schedule_warnings INTERFACE)
if(MSVC)
target_compile_options(schedule_warnings INTERFACE /W4 /permissive-)
if(SCHEDULE_WARNINGS_AS_ERRORS)
target_compile_options(schedule_warnings INTERFACE /WX)
endif()
else()
target_compile_options(schedule_warnings INTERFACE -Wall -Wextra -Wnon-virtual-dtor)
if(SCHEDULE_WARNINGS_AS_ERRORS)
target_compile_options(schedule_warnings INTERFACE -Werror)
endif()
endif()
add_library(tomlplusplus INTERFACE)
target_include_directories(tomlplusplus SYSTEM INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/3rd/tomlplusplus)
# ElaWidgetTools 以静态库方式引入,避免额外运行时库分发。
set(QT_VERSION_MAJOR 6)
set(ELAWIDGETTOOLS_BUILD_STATIC_LIB ON CACHE BOOL "" FORCE)
set(CMAKE_WARN_DEPRECATED OFF)
add_subdirectory(3rd/ElaWidgetTools/ElaWidgetTools EXCLUDE_FROM_ALL)
unset(CMAKE_WARN_DEPRECATED)
# 第三方库按自身要求的 C++17 编译,避免其 C++20 弃用告警污染构建输出。
set_target_properties(ElaWidgetTools PROPERTIES
CXX_STANDARD 17
CXX_STANDARD_REQUIRED ON
CXX_EXTENSIONS OFF
)
if(NOT MSVC)
# 第三方库内部仍使用少量 Qt 已弃用 API,抑制其告警但不修改其源码。
target_compile_options(ElaWidgetTools PRIVATE -Wno-deprecated-declarations)
endif()
add_subdirectory(src)
add_subdirectory(tests)
add_subdirectory(tools)
+6
View File
@@ -0,0 +1,6 @@
<RCC>
<qresource prefix="/">
<file alias="prompts/chat_system.txt">prompts/chat_system.txt</file>
<file alias="prompts/repair_system.txt">prompts/repair_system.txt</file>
</qresource>
</RCC>
+34
View File
@@ -0,0 +1,34 @@
你是「AI 日程」的日程规划助手。请始终使用简体中文回答。
当前本地时间:{CURRENT_TIME}
今天星期:{WEEKDAY}
用户默认可用时间:{WORK_START}–{WORK_END}
用户现有日程(每行开头的 [bN] 是引用编号,只能用于 update/delete):
{EXISTING_SCHEDULE}
工作规则:
1. 先用 1–3 句简洁回复,说明你理解的需求和准备怎么安排。
2. 如果需要修改日程,在回复后另起一行输出标记:@@DIFF@@
3. 在 @@DIFF@@ 之后只输出一个 JSON 对象,不要使用 markdown 代码块,不要输出其他内容:
{"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"}
]}
4. 时间使用用户本地时间,不带时区;不确定的字段填 null。
5. duration_min 必须在 15–480 之间;无法确定时用 60。
6. 用户明确要求移动/改时长/改标题/删除已有日程时,使用 update/delete,并使用摘要中的 [bN] 引用;只改标题时可以省略时间字段。
7. 用户只是询问、闲聊、查看日程,或不需要修改日程时,不要输出 @@DIFF@@,只给回复。
8. 不要编造用户没有提到的任务;不要擅自移动或删除用户没有要求改动的日程。
9. JSON 对象结束后不要再输出任何文字。
10. 用户明确给出任务标题和时长时,必须输出 @@DIFF@@ 与 operations,不要只回复“请提供更多信息”或“无法安排”。
11. 如果指定时间已有日程,仍然输出带 preferred_start/preferred_end 的操作;本地排程器会生成涟漪建议,不要因为冲突而拒绝输出 diff。
12. 删除类请求:从现有日程摘要中找出所有匹配项,逐个使用 delete;不要忽略。
13. 可拆分请求:在 create 中设置 splittable=true,让本地排程器拆分;不要因为时间不够而只回复说明。
14. 用户给出过去时间时,改到下一个可用时间,并在回复中说明。
15. 现有日程摘要中带“(会议)”标记的条目属于会议类;用户要求删除“所有会议”时,逐个 delete 所有带该标记的条目。
16. 示例:现有 [b2] 团队同步(会议)、[b4] 项目会议(会议)。用户说“删除明天所有会议”时,输出 {"operations":[{"type":"delete","target_ref":"b2"},{"type":"delete","target_ref":"b4"}]}。
17. 示例:用户说“明天之前找时间做两小时长任务,可以拆开”,输出 create 并设置 "splittable":true;不要拆成两个独立任务。
补充信息:
{EXTRA_CONTEXT}
@@ -0,0 +1,17 @@
你上一轮输出没有成功解析为日程操作 JSON。请严格只输出一个 JSON 对象,不要输出解释、标记或 markdown 代码块。
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"}
]}
规则:
- 只使用现有日程摘要中出现过的 target_ref。
- 时间使用用户本地时间,不带时区;不确定的字段填 null。
- duration_min 在 15–480 之间。
- 如果只是闲聊或没有日程变更,operations 输出空数组。
- 用户明确要求新增/修改/删除时,必须给出 operations;冲突、时长不足或过去时间交给本地排程器处理。
- 可拆分请求优先设置 splittable=true。
- 现有日程摘要中的(会议)标记用于识别会议类;删除“所有会议”时删除全部带标记项。
+116
View File
@@ -0,0 +1,116 @@
add_library(schedule_core STATIC
core/DateTimeUtils.cpp
core/DateTimeUtils.h
core/ProposedDiff.h
core/SchedulerEngine.cpp
core/SchedulerEngine.h
core/ScheduleItem.h
core/Task.h
core/TimeBlock.h
storage/Migrations.cpp
storage/Migrations.h
storage/SqliteStore.cpp
storage/SqliteStore.h
)
target_include_directories(schedule_core PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(schedule_core
PUBLIC Qt6::Core Qt6::Sql
PRIVATE schedule_warnings
)
add_library(schedule_services STATIC
services/NotificationService.cpp
services/NotificationService.h
services/ScheduleService.cpp
services/ScheduleService.h
utils/AppPaths.cpp
utils/AppPaths.h
utils/AppSettings.cpp
utils/AppSettings.h
)
target_include_directories(schedule_services PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(schedule_services
PUBLIC schedule_core Qt6::Core
PRIVATE schedule_warnings tomlplusplus
)
add_library(schedule_ai STATIC
ai/AIService.cpp
ai/AIService.h
ai/FileExtractor.cpp
ai/FileExtractor.h
ai/IAIProvider.h
ai/OpenAiProvider.cpp
ai/OpenAiProvider.h
ai/PromptLoader.cpp
ai/PromptLoader.h
ai/ScheduleProposal.h
${CMAKE_SOURCE_DIR}/client/resources/prompts.qrc
)
target_include_directories(schedule_ai PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(schedule_ai
PUBLIC schedule_services Qt6::Core Qt6::Network Qt6::Concurrent
PRIVATE schedule_warnings
)
add_library(schedule_sync STATIC
sync/SyncService.cpp
sync/SyncService.h
core/SyncTypes.h
)
target_include_directories(schedule_sync PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(schedule_sync
PUBLIC schedule_services Qt6::Core Qt6::Network Qt6::WebSockets
PRIVATE schedule_warnings
)
add_library(schedule_ui STATIC
platform/SystemTray.cpp
platform/SystemTray.h
ui/AppIcon.cpp
ui/AppIcon.h
ui/CompactWindow.cpp
ui/CompactWindow.h
ui/MainWindow.cpp
ui/MainWindow.h
ui/dialogs/BlockEditDialog.cpp
ui/dialogs/BlockEditDialog.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/TodayItemCard.cpp
ui/panels/TodayItemCard.h
ui/panels/TodayPanel.cpp
ui/panels/TodayPanel.h
ui/theme/ThemeManager.cpp
ui/theme/ThemeManager.h
ui/theme/ThemeTokens.h
ui/theme/WindowEffects.cpp
ui/theme/WindowEffects.h
ui/views/MonthView.cpp
ui/views/MonthView.h
ui/views/ScheduleGridView.cpp
ui/views/ScheduleGridView.h
ui/views/YearView.cpp
ui/views/YearView.h
)
target_include_directories(schedule_ui PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(schedule_ui
PUBLIC schedule_ai schedule_sync Qt6::Widgets ElaWidgetTools
PRIVATE schedule_warnings
)
qt_add_executable(Schedule
main.cpp
)
set_target_properties(Schedule PROPERTIES
WIN32_EXECUTABLE ON
MACOSX_BUNDLE ON
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
)
target_link_libraries(Schedule PRIVATE schedule_ui schedule_sync)
File diff suppressed because it is too large Load Diff
+126
View File
@@ -0,0 +1,126 @@
#pragma once
#include <QDate>
#include <QDateTime>
#include <QFutureWatcher>
#include <QJsonArray>
#include <QHash>
#include <QJsonValue>
#include <QObject>
#include <QString>
#include <QStringList>
#include <memory>
#include "ai/FileExtractor.h"
#include "ai/IAIProvider.h"
#include "ai/ScheduleProposal.h"
#include "core/ProposedDiff.h"
#include "core/ScheduleItem.h"
class AppSettings;
class ScheduleService;
class SqliteStore;
/*
* 类名: AIService
* 功能: AI 编排服务;流式解析回复、生成确定性排程、持久化 ProposedDiff、处理接受/拒绝
* 线程安全: 否;主线程使用,网络/文件提取异步
*/
class AIService : public QObject
{
Q_OBJECT
public:
AIService(ScheduleService& scheduleService,
SqliteStore& store,
AppSettings& settings,
std::unique_ptr<ai::IAIProvider> provider = {},
QObject* parent = nullptr);
~AIService() override;
bool isBusy() const;
QString lastError() const;
void request(const QString& text, const QStringList& filePaths = {});
void applyDiff(const QString& diffId, const QStringList& acceptedTempIds);
void rejectDiff(const QString& diffId);
signals:
void streamDelta(const QString& delta);
void requestFinished();
void requestFailed(const QString& message);
void proposalReady(const ScheduleProposal& proposal);
void notice(const QString& message);
void diffApplied(const QString& diffId, int count);
void diffRejected(const QString& diffId);
void diffApplyFailed(const QString& diffId, const QString& message);
private:
enum class Phase
{
Idle,
Extracting,
Streaming,
Repairing,
};
void onFilesExtracted();
void startCompletion();
void startRepair();
void beginRepairCompletion();
void handleStreamDelta(const QString& delta);
void handleStreamFinished();
void handleProviderError(const QString& message);
void emitVisibleText(bool final);
void appendHistory(const QString& assistantReply);
void finishRequest();
void fail(const QString& message);
QString buildSystemPrompt();
QString scheduleSummary();
QJsonValue buildUserContent() const;
void buildProposalFromOperations(const QJsonArray& operations, const QString& visibleReply);
bool tryLocalDeleteAllMeetings();
bool looksLikeActionableScheduleRequest() const;
void resetStreamState();
static bool extractJsonObject(const QString& text, QJsonObject* object, QString* error);
static QDateTime parseLocalDateTime(const QString& text);
static QString weekdayLabel(const QDate& date);
ScheduleService& m_scheduleService;
SqliteStore& m_store;
AppSettings& m_settings;
std::unique_ptr<ai::IAIProvider> m_provider;
QFutureWatcher<QVector<ExtractedFile>> m_fileWatcher;
QVector<ExtractedFile> m_extractedFiles;
QString m_userText;
QStringList m_filePaths;
QString m_raw;
QString m_repairRaw;
QString m_visibleText;
qsizetype m_emitted = 0;
bool m_markerFound = false;
qsizetype m_markerPos = -1;
bool m_retryUsed = false;
bool m_busy = false;
Phase m_phase = Phase::Idle;
QString m_lastError;
quint64 m_generation = 0;
QHash<QString, ProposedDiff> m_pendingDiffs;
QJsonArray m_history;
struct ContextItem
{
QString ref;
ScheduleItem item;
};
QVector<ContextItem> m_contextItems;
QHash<QString, int> m_contextIndexByRef;
QHash<QString, int> m_contextIndexByBlockId;
QString m_contextSummary;
};
+258
View File
@@ -0,0 +1,258 @@
#include "FileExtractor.h"
#include <QFile>
#include <QFileInfo>
#include <QMimeDatabase>
#include <QProcess>
#include <QStandardPaths>
#include <QXmlStreamReader>
namespace
{
constexpr int kMaxTextCharacters = 20000;
constexpr qint64 kMaxTextFileBytes = 2 * 1024 * 1024;
constexpr qint64 kMaxImageBytes = 8 * 1024 * 1024;
void truncateText(QString& text)
{
if (text.size() <= kMaxTextCharacters)
{
return;
}
text.truncate(kMaxTextCharacters);
text += QStringLiteral("\n\n[内容过长,已截断]");
}
bool runTool(const QString& program,
const QStringList& arguments,
QByteArray& output,
QString& error,
int timeoutMs = 20000)
{
const QString executable = QStandardPaths::findExecutable(program);
if (executable.isEmpty())
{
error = QStringLiteral("未找到 %1,请先安装该工具").arg(program);
return false;
}
QProcess process;
process.setProgram(executable);
process.setArguments(arguments);
process.start();
if (!process.waitForStarted(5000))
{
error = QStringLiteral("%1 启动失败: %2").arg(program, process.errorString());
return false;
}
if (!process.waitForFinished(timeoutMs))
{
process.kill();
process.waitForFinished(2000);
error = QStringLiteral("%1 处理超时").arg(program);
return false;
}
if (process.exitStatus() != QProcess::NormalExit || process.exitCode() != 0)
{
const QString stderrText = QString::fromUtf8(process.readAllStandardError()).trimmed();
error = QStringLiteral("%1 处理失败: %2").arg(program, stderrText.left(300));
return false;
}
output = process.readAllStandardOutput();
return true;
}
ExtractedFile extractText(const QFileInfo& info, ExtractedFile result)
{
QFile file(info.absoluteFilePath());
if (!file.open(QIODevice::ReadOnly))
{
result.error = QStringLiteral("无法读取文件: %1").arg(file.errorString());
return result;
}
QByteArray data = file.read(kMaxTextFileBytes);
result.text = QString::fromUtf8(data);
if (result.text.isEmpty() && data.size() > 0)
{
result.text = QString::fromLocal8Bit(data);
}
truncateText(result.text);
if (result.text.trimmed().isEmpty())
{
result.error = QStringLiteral("文件内容为空");
}
return result;
}
ExtractedFile extractPdf(const QFileInfo& info, ExtractedFile result)
{
QByteArray output;
QString error;
if (!runTool(QStringLiteral("pdftotext"),
{QStringLiteral("-layout"), info.absoluteFilePath(), QStringLiteral("-")},
output,
error))
{
result.error = error;
return result;
}
result.text = QString::fromUtf8(output);
truncateText(result.text);
if (result.text.trimmed().isEmpty())
{
result.error = QStringLiteral("PDF 中没有可提取的文本");
}
return result;
}
ExtractedFile extractDocx(const QFileInfo& info, ExtractedFile result)
{
QByteArray xmlData;
QString error;
if (!runTool(QStringLiteral("unzip"),
{QStringLiteral("-p"), info.absoluteFilePath(), QStringLiteral("word/document.xml")},
xmlData,
error))
{
result.error = error;
return result;
}
QXmlStreamReader reader(xmlData);
QString text;
bool inText = false;
while (!reader.atEnd())
{
reader.readNext();
if (reader.isStartElement())
{
if (reader.qualifiedName() == QStringLiteral("w:t"))
{
inText = true;
}
}
else if (reader.isEndElement())
{
if (reader.qualifiedName() == QStringLiteral("w:t"))
{
inText = false;
}
else if (reader.qualifiedName() == QStringLiteral("w:p"))
{
text += QLatin1Char('\n');
}
}
else if (reader.isCharacters() && inText)
{
text += reader.text();
}
}
if (reader.hasError())
{
result.error = QStringLiteral("Word 文档解析失败: %1").arg(reader.errorString());
return result;
}
result.text = text.trimmed();
truncateText(result.text);
if (result.text.isEmpty())
{
result.error = QStringLiteral("Word 文档中没有可提取的文本");
}
return result;
}
ExtractedFile extractDoc(const QFileInfo& info, ExtractedFile result)
{
QByteArray output;
QString error;
if (!runTool(QStringLiteral("catdoc"), {info.absoluteFilePath()}, output, error))
{
result.error = error;
return result;
}
result.text = QString::fromUtf8(output);
truncateText(result.text);
if (result.text.trimmed().isEmpty())
{
result.error = QStringLiteral("Word 文档中没有可提取的文本");
}
return result;
}
ExtractedFile extractImage(const QFileInfo& info, ExtractedFile result, const QString& mimeType)
{
if (info.size() > kMaxImageBytes)
{
result.error = QStringLiteral("图片超过 8MB 限制");
return result;
}
QFile file(info.absoluteFilePath());
if (!file.open(QIODevice::ReadOnly))
{
result.error = QStringLiteral("无法读取图片: %1").arg(file.errorString());
return result;
}
result.imageData = file.readAll();
result.mimeType = mimeType;
return result;
}
} // namespace
QVector<ExtractedFile> FileExtractor::extractAll(const QStringList& paths)
{
QVector<ExtractedFile> results;
results.reserve(paths.size());
for (const QString& path : paths)
{
const QFileInfo info(path);
ExtractedFile result;
result.fileName = info.fileName();
result.path = info.absoluteFilePath();
if (!info.exists() || !info.isFile())
{
result.error = QStringLiteral("文件不存在");
results.append(result);
continue;
}
QMimeDatabase mimeDatabase;
const QString mimeType = mimeDatabase.mimeTypeForFile(info).name();
result.mimeType = mimeType;
const QString suffix = info.suffix().toLower();
if (suffix == QStringLiteral("txt") || suffix == QStringLiteral("md") ||
suffix == QStringLiteral("csv") || suffix == QStringLiteral("json") ||
suffix == QStringLiteral("log") || suffix == QStringLiteral("yaml") ||
suffix == QStringLiteral("yml"))
{
result = extractText(info, result);
}
else if (suffix == QStringLiteral("pdf"))
{
result = extractPdf(info, result);
}
else if (suffix == QStringLiteral("docx"))
{
result = extractDocx(info, result);
}
else if (suffix == QStringLiteral("doc"))
{
result = extractDoc(info, result);
}
else if (suffix == QStringLiteral("png") || suffix == QStringLiteral("jpg") ||
suffix == QStringLiteral("jpeg") || suffix == QStringLiteral("webp") ||
suffix == QStringLiteral("gif") || suffix == QStringLiteral("bmp"))
{
result = extractImage(info, result, mimeType);
}
else
{
result.error = QStringLiteral("暂不支持的文件格式: .%1").arg(suffix);
}
results.append(result);
}
return results;
}
+40
View File
@@ -0,0 +1,40 @@
#pragma once
#include <QByteArray>
#include <QString>
#include <QStringList>
#include <QVector>
/*
* 类名: ExtractedFile
* 功能: 文件内容提取结果;文本类放入 text,图片类放入 imageData
* 线程安全: 是(值类型)
*/
struct ExtractedFile
{
QString fileName;
QString path;
QString mimeType;
QString text;
QByteArray imageData;
QString error;
bool ok() const
{
return error.isEmpty();
}
bool isImage() const
{
return !imageData.isEmpty();
}
};
/*
* 命名空间: FileExtractor
* 功能: 在后台线程中把常见文件转换为可供 AI 使用的文本/图片数据
* 线程安全: 是(无共享可变状态)
*/
namespace FileExtractor
{
QVector<ExtractedFile> extractAll(const QStringList& paths);
}
+35
View File
@@ -0,0 +1,35 @@
#pragma once
#include <QJsonArray>
#include <QString>
#include <functional>
#include "utils/AppSettings.h"
namespace ai
{
struct CompletionCallbacks
{
std::function<void(const QString&)> onDelta;
std::function<void(const QString&)> onError;
std::function<void()> onFinished;
};
/*
* 接口: IAIProvider
* 功能: AI 提供方抽象;实现必须异步工作,不得阻塞 UI 线程
* 线程安全: 否;主线程调用/回调
*/
class IAIProvider
{
public:
virtual ~IAIProvider() = default;
virtual QString name() const = 0;
virtual void streamCompletion(const AiConfig& config,
const QJsonArray& messages,
CompletionCallbacks callbacks) = 0;
virtual void cancel() = 0;
};
} // namespace ai
+390
View File
@@ -0,0 +1,390 @@
#include "OpenAiProvider.h"
#include <QJsonDocument>
#include <QJsonObject>
#include <QNetworkRequest>
#include <QUrl>
namespace
{
QString textFromContent(const QJsonValue& value)
{
if (value.isString())
{
return value.toString();
}
if (value.isArray())
{
QString text;
for (const QJsonValue& part : value.toArray())
{
if (part.isObject())
{
const QJsonObject object = part.toObject();
if (object.value(QStringLiteral("type")).toString() == QStringLiteral("text"))
{
text += object.value(QStringLiteral("text")).toString();
}
}
}
return text;
}
return {};
}
QString errorMessageFromBody(const QByteArray& body)
{
const QJsonDocument document = QJsonDocument::fromJson(body);
if (document.isObject())
{
const QJsonObject object = document.object();
const QJsonValue error = object.value(QStringLiteral("error"));
if (error.isObject())
{
const QString message = error.toObject().value(QStringLiteral("message")).toString();
if (!message.isEmpty())
{
return message;
}
}
if (error.isString())
{
return error.toString();
}
const QString message = object.value(QStringLiteral("message")).toString();
if (!message.isEmpty())
{
return message;
}
}
const QString text = QString::fromUtf8(body).trimmed();
return text.left(500);
}
} // namespace
OpenAiProvider::OpenAiProvider(QObject* parent)
: QObject(parent)
{
}
OpenAiProvider::~OpenAiProvider()
{
cancel();
}
QString OpenAiProvider::name() const
{
return QStringLiteral("OpenAI 兼容");
}
void OpenAiProvider::cancel()
{
m_completed = true;
m_callbacks = {};
cleanupReply();
m_buffer.clear();
m_rawBody.clear();
}
void OpenAiProvider::streamCompletion(const AiConfig& config,
const QJsonArray& messages,
ai::CompletionCallbacks callbacks)
{
cancel();
m_completed = false;
m_parsedContent = false;
m_sawDone = false;
m_networkError.clear();
m_buffer.clear();
m_rawBody.clear();
m_callbacks = std::move(callbacks);
const QString baseUrl = config.baseUrl.trimmed();
if (baseUrl.isEmpty())
{
finishWithError(QStringLiteral("AI 接口地址为空,请在设置中配置"));
return;
}
QUrl url(baseUrl);
if (!url.isValid() || (url.scheme() != QStringLiteral("http") && url.scheme() != QStringLiteral("https")))
{
finishWithError(QStringLiteral("AI 接口地址无效: %1").arg(baseUrl));
return;
}
QString path = url.path();
while (path.endsWith(QLatin1Char('/')))
{
path.chop(1);
}
if (!path.endsWith(QStringLiteral("/chat/completions")))
{
path += QStringLiteral("/chat/completions");
url.setPath(path);
}
if (config.model.trimmed().isEmpty())
{
finishWithError(QStringLiteral("AI 模型为空,请在设置中配置"));
return;
}
if (config.apiKey.trimmed().isEmpty() && baseUrl.contains(QStringLiteral("api.openai.com")))
{
finishWithError(QStringLiteral("请先在设置中填写 OpenAI API Key"));
return;
}
QJsonObject body;
body.insert(QStringLiteral("model"), config.model);
body.insert(QStringLiteral("messages"), messages);
body.insert(QStringLiteral("temperature"), config.temperature);
// 为推理模型预留 reasoning tokens,避免只用推理耗尽额度而没有最终 content。
body.insert(QStringLiteral("max_tokens"), 4096);
body.insert(QStringLiteral("stream"), true);
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader, QStringLiteral("application/json"));
request.setRawHeader("Accept", "text/event-stream");
if (!config.apiKey.trimmed().isEmpty())
{
request.setRawHeader("Authorization",
QByteArray("Bearer ") + config.apiKey.trimmed().toUtf8());
}
request.setTransferTimeout(120000);
request.setAttribute(QNetworkRequest::RedirectPolicyAttribute,
QNetworkRequest::NoLessSafeRedirectPolicy);
m_reply = m_manager.post(request, QJsonDocument(body).toJson(QJsonDocument::Compact));
connect(m_reply, &QNetworkReply::readyRead, this, &OpenAiProvider::onReadyRead);
connect(m_reply, &QNetworkReply::finished, this, &OpenAiProvider::onFinished);
connect(m_reply, &QNetworkReply::errorOccurred, this, &OpenAiProvider::onNetworkError);
}
void OpenAiProvider::onNetworkError(QNetworkReply::NetworkError code)
{
Q_UNUSED(code)
if (m_completed || !m_reply)
{
return;
}
m_networkError = m_reply->errorString();
}
void OpenAiProvider::onReadyRead()
{
if (m_completed || !m_reply)
{
return;
}
const QByteArray chunk = m_reply->readAll();
m_rawBody += chunk;
m_buffer += chunk;
while (!m_completed)
{
const int newline = m_buffer.indexOf('\n');
if (newline < 0)
{
break;
}
QByteArray line = m_buffer.left(newline);
m_buffer.remove(0, newline + 1);
if (line.endsWith('\r'))
{
line.chop(1);
}
handleLine(line);
}
if (m_completed)
{
if (m_reply)
{
m_reply->abort();
}
}
}
void OpenAiProvider::handleLine(const QByteArray& line)
{
const QByteArray trimmed = line.trimmed();
if (trimmed.isEmpty() || trimmed.startsWith(':'))
{
return;
}
if (trimmed.startsWith("data:"))
{
handleSsePayload(trimmed.mid(5).trimmed());
}
else if (trimmed.startsWith('{'))
{
// 兼容部分本地服务不发送 data: 前缀的情况。
handleSsePayload(trimmed);
}
}
void OpenAiProvider::handleSsePayload(const QByteArray& payload)
{
if (payload == "[DONE]")
{
m_sawDone = true;
finishOk();
return;
}
const QJsonDocument document = QJsonDocument::fromJson(payload);
if (!document.isObject())
{
return;
}
const QJsonObject object = document.object();
const QJsonValue error = object.value(QStringLiteral("error"));
if (!error.isUndefined() && !error.isNull())
{
finishWithError(errorMessageFromBody(payload));
return;
}
const QJsonArray choices = object.value(QStringLiteral("choices")).toArray();
if (choices.isEmpty())
{
return;
}
const QJsonObject choice = choices.first().toObject();
QString content = textFromContent(choice.value(QStringLiteral("delta")).toObject().value(QStringLiteral("content")));
if (content.isEmpty())
{
content = textFromContent(choice.value(QStringLiteral("message")).toObject().value(QStringLiteral("content")));
}
if (!content.isEmpty())
{
m_parsedContent = true;
if (m_callbacks.onDelta)
{
m_callbacks.onDelta(content);
}
}
}
void OpenAiProvider::onFinished()
{
if (!m_reply)
{
return;
}
const int status = m_reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
const QByteArray remaining = m_reply->readAll();
m_rawBody += remaining;
m_buffer += remaining;
const bool httpError = m_reply->error() != QNetworkReply::NoError || (status != 0 && status >= 400);
if (!m_completed && !httpError)
{
if (!m_buffer.trimmed().isEmpty())
{
handleLine(m_buffer);
m_buffer.clear();
}
}
if (m_completed)
{
cleanupReply();
return;
}
if (httpError)
{
QString detail = errorMessageFromBody(m_rawBody);
if (detail.isEmpty())
{
detail = m_networkError.isEmpty() ? m_reply->errorString() : m_networkError;
}
if (status > 0)
{
detail = QStringLiteral("HTTP %1: %2").arg(status).arg(detail);
}
finishWithError(detail.isEmpty() ? QStringLiteral("AI 服务请求失败") : detail);
return;
}
if (!m_parsedContent)
{
const QJsonDocument document = QJsonDocument::fromJson(m_rawBody);
if (document.isObject())
{
const QJsonObject object = document.object();
const QJsonArray choices = object.value(QStringLiteral("choices")).toArray();
if (!choices.isEmpty())
{
const QJsonObject choice = choices.first().toObject();
QString content = textFromContent(choice.value(QStringLiteral("message")).toObject().value(QStringLiteral("content")));
if (content.isEmpty())
{
content = textFromContent(choice.value(QStringLiteral("delta")).toObject().value(QStringLiteral("content")));
}
if (!content.isEmpty())
{
m_parsedContent = true;
if (m_callbacks.onDelta)
{
m_callbacks.onDelta(content);
}
}
}
}
}
if (!m_parsedContent && !m_sawDone)
{
const QString bodyText = QString::fromUtf8(m_rawBody).trimmed();
finishWithError(bodyText.isEmpty() ? QStringLiteral("AI 服务返回了空响应")
: QStringLiteral("无法解析 AI 服务响应: %1").arg(bodyText.left(300)));
return;
}
finishOk();
}
void OpenAiProvider::finishOk()
{
if (m_completed)
{
return;
}
m_completed = true;
ai::CompletionCallbacks callbacks = std::move(m_callbacks);
m_callbacks = {};
cleanupReply();
if (callbacks.onFinished)
{
callbacks.onFinished();
}
}
void OpenAiProvider::finishWithError(const QString& message)
{
if (m_completed)
{
return;
}
m_completed = true;
ai::CompletionCallbacks callbacks = std::move(m_callbacks);
m_callbacks = {};
cleanupReply();
if (callbacks.onError)
{
callbacks.onError(message);
}
}
void OpenAiProvider::cleanupReply()
{
if (!m_reply)
{
return;
}
QNetworkReply* reply = m_reply;
m_reply = nullptr;
reply->disconnect(this);
if (reply->isRunning())
{
reply->abort();
}
reply->deleteLater();
}
+50
View File
@@ -0,0 +1,50 @@
#pragma once
#include <QByteArray>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QObject>
#include "ai/IAIProvider.h"
/*
* 类名: OpenAiProvider
* 功能: OpenAI 兼容 Chat Completions 流式实现(SSE)
* 线程安全: 否;主线程使用
*/
class OpenAiProvider : public QObject, public ai::IAIProvider
{
Q_OBJECT
public:
explicit OpenAiProvider(QObject* parent = nullptr);
~OpenAiProvider() override;
QString name() const override;
void streamCompletion(const AiConfig& config,
const QJsonArray& messages,
ai::CompletionCallbacks callbacks) override;
void cancel() override;
private slots:
void onReadyRead();
void onFinished();
void onNetworkError(QNetworkReply::NetworkError code);
private:
void handleLine(const QByteArray& line);
void handleSsePayload(const QByteArray& payload);
void finishOk();
void finishWithError(const QString& message);
void cleanupReply();
QNetworkAccessManager m_manager;
QNetworkReply* m_reply = nullptr;
QByteArray m_buffer;
QByteArray m_rawBody;
ai::CompletionCallbacks m_callbacks;
bool m_completed = false;
bool m_parsedContent = false;
bool m_sawDone = false;
QString m_networkError;
};
+39
View File
@@ -0,0 +1,39 @@
#include "PromptLoader.h"
#include <QFile>
#include <QProcessEnvironment>
static void ensurePromptResources()
{
static const bool initialized = []() {
Q_INIT_RESOURCE(prompts);
return true;
}();
Q_UNUSED(initialized)
}
namespace PromptLoader
{
QString load(const QString& fileName)
{
ensurePromptResources();
const QString directory =
QProcessEnvironment::systemEnvironment().value(QStringLiteral("SCHEDULE_PROMPTS_DIR"));
if (!directory.trimmed().isEmpty())
{
QFile file(directory + QLatin1Char('/') + fileName);
if (file.open(QIODevice::ReadOnly | QIODevice::Text))
{
return QString::fromUtf8(file.readAll());
}
}
QFile resource(QStringLiteral(":/prompts/") + fileName);
if (resource.open(QIODevice::ReadOnly | QIODevice::Text))
{
return QString::fromUtf8(resource.readAll());
}
return {};
}
} // namespace PromptLoader
+13
View File
@@ -0,0 +1,13 @@
#pragma once
#include <QString>
/*
* 命名空间: PromptLoader
* 功能: 加载 AI 提示词;优先使用 SCHEDULE_PROMPTS_DIR 覆盖,其次使用内置资源
* 线程安全: 是(只读)
*/
namespace PromptLoader
{
QString load(const QString& fileName);
}
+58
View File
@@ -0,0 +1,58 @@
#pragma once
#include <QDateTime>
#include <QMetaType>
#include <QString>
#include <QVector>
/*
* 枚举: ProposedOperation
* 功能: Diff 预览中的操作类型
*/
enum class ProposedOperation
{
Create,
Update,
Delete,
};
struct ProposedTimeSegment
{
QDateTime startAt;
QDateTime endAt;
};
/*
* 类名: ProposedScheduleEntry
* 功能: Diff 预览中的单条操作视图模型(本地时间)
* 线程安全: 否(值类型)
*/
struct ProposedScheduleEntry
{
QString tempId;
ProposedOperation operation = ProposedOperation::Create;
QString blockId;
QString title;
QString oldTitle;
QDateTime startAt;
QDateTime endAt;
QDateTime oldStartAt;
QDateTime oldEndAt;
QVector<ProposedTimeSegment> segments;
int priority = 1;
int energyRequired = -1;
};
/*
* 类名: ScheduleProposal
* 功能: AI 生成并已落库的待确认日程建议,供 UI 展示与选择性接受
* 线程安全: 否(值类型)
*/
struct ScheduleProposal
{
QString diffId;
QString explanation;
QVector<ProposedScheduleEntry> entries;
};
Q_DECLARE_METATYPE(ScheduleProposal)
+95
View File
@@ -0,0 +1,95 @@
#include "DateTimeUtils.h"
#include <QTime>
namespace DateTimeUtils
{
QString toDb(const QDateTime& value)
{
if (!value.isValid())
{
return {};
}
return value.toUTC().toString(Qt::ISODateWithMs);
}
QDateTime fromDb(const QString& value)
{
if (value.isEmpty())
{
return {};
}
QDateTime utc = QDateTime::fromString(value, Qt::ISODate);
if (!utc.isValid())
{
return {};
}
utc.setTimeSpec(Qt::UTC);
return utc.toLocalTime();
}
QDateTime localDayStartUtc(const QDate& date)
{
return QDateTime(date, QTime(0, 0), Qt::LocalTime).toUTC();
}
QDateTime localDayEndUtc(const QDate& date)
{
return QDateTime(date.addDays(1), QTime(0, 0), Qt::LocalTime).toUTC();
}
QDateTime snapTo(const QDateTime& value, int minutes)
{
if (!value.isValid() || minutes <= 0)
{
return value;
}
const qint64 dayStart = QDateTime(value.date(), QTime(0, 0), Qt::LocalTime).toMSecsSinceEpoch();
const qint64 msecs = value.toMSecsSinceEpoch() - dayStart;
const qint64 step = static_cast<qint64>(minutes) * 60 * 1000;
const qint64 snapped = qRound64(static_cast<double>(msecs) / static_cast<double>(step)) * step;
return QDateTime::fromMSecsSinceEpoch(dayStart + snapped, Qt::LocalTime);
}
int minutesBetween(const QDateTime& from, const QDateTime& to)
{
if (!from.isValid() || !to.isValid())
{
return 0;
}
return static_cast<int>(from.secsTo(to) / 60);
}
int minutesOfDay(const QDateTime& value, const QDate& day)
{
const QDateTime dayStart(day, QTime(0, 0), Qt::LocalTime);
return minutesBetween(dayStart, value);
}
QString formatTimeRange(const QDateTime& start, const QDateTime& end)
{
return QStringLiteral("%1–%2").arg(start.toString(QStringLiteral("HH:mm")),
end.toString(QStringLiteral("HH:mm")));
}
QString formatDuration(int minutes)
{
if (minutes <= 0)
{
return {};
}
const int hours = minutes / 60;
const int mins = minutes % 60;
if (hours > 0 && mins > 0)
{
return QStringLiteral("%1小时%2分").arg(hours).arg(mins);
}
if (hours > 0)
{
return QStringLiteral("%1小时").arg(hours);
}
return QStringLiteral("%1分钟").arg(mins);
}
} // namespace DateTimeUtils
+25
View File
@@ -0,0 +1,25 @@
#pragma once
#include <QDate>
#include <QDateTime>
#include <QString>
namespace DateTimeUtils
{
// 数据库统一存 UTC ISO8601,保证字符串排序与跨时区一致。
QString toDb(const QDateTime& value);
QDateTime fromDb(const QString& value);
// 本地自然日 [00:00, 次日 00:00) 转 UTC,用于查询。
QDateTime localDayStartUtc(const QDate& date);
QDateTime localDayEndUtc(const QDate& date);
QDateTime snapTo(const QDateTime& value, int minutes);
int minutesBetween(const QDateTime& from, const QDateTime& to);
int minutesOfDay(const QDateTime& value, const QDate& day);
QString formatTimeRange(const QDateTime& start, const QDateTime& end);
QString formatDuration(int minutes);
} // namespace DateTimeUtils
+19
View File
@@ -0,0 +1,19 @@
#pragma once
#include <QJsonObject>
#include <QString>
/*
* 类名: ProposedDiff
* 功能: AI 提议的不可变变更集合;阶段 2 起使用,AI 永不直接写库
* 线程安全: 否(值类型)
*/
struct ProposedDiff
{
QString id;
QString createdAt;
QJsonObject payload;
QString explanation;
QString state = QStringLiteral("pending");
QString resolvedAt;
};
+19
View File
@@ -0,0 +1,19 @@
#pragma once
#include <QMetaType>
#include "Task.h"
#include "TimeBlock.h"
/*
* 类名: ScheduleItem
* 功能: Task 与 TimeBlock 的只读聚合,供 UI/服务层展示
* 线程安全: 否(值类型)
*/
struct ScheduleItem
{
Task task;
TimeBlock block;
};
Q_DECLARE_METATYPE(ScheduleItem)
+241
View File
@@ -0,0 +1,241 @@
#include "SchedulerEngine.h"
#include <algorithm>
#include <cstdint>
namespace scheduler
{
namespace
{
SysTime ceilToGranularity(SysTime value, int granularityMinutes)
{
const int step = std::max(1, granularityMinutes) * 60;
const std::int64_t seconds = value.time_since_epoch().count();
const std::int64_t remainder = seconds % step;
if (remainder == 0)
{
return value;
}
return SysTime{std::chrono::seconds{seconds + (step - remainder)}};
}
void mergeBusy(std::vector<TimeRange>& busy)
{
std::sort(busy.begin(), busy.end(), [](const TimeRange& a, const TimeRange& b) {
return a.start < b.start;
});
std::vector<TimeRange> merged;
for (const TimeRange& range : busy)
{
if (range.end <= range.start)
{
continue;
}
if (!merged.empty() && range.start <= merged.back().end)
{
merged.back().end = std::max(merged.back().end, range.end);
}
else
{
merged.push_back(range);
}
}
busy = std::move(merged);
}
std::vector<TimeRange> intersect(const std::vector<TimeRange>& windows,
SysTime lower,
SysTime upper)
{
std::vector<TimeRange> result;
for (const TimeRange& window : windows)
{
const SysTime start = std::max(window.start, lower);
const SysTime end = std::min(window.end, upper);
if (start < end)
{
result.push_back({start, end});
}
}
return result;
}
std::optional<TimeRange> findSlot(const std::vector<TimeRange>& windows,
const std::vector<TimeRange>& busy,
SysTime rangeStart,
std::optional<SysTime> deadline,
std::chrono::seconds duration,
int granularityMinutes)
{
for (const TimeRange& window : windows)
{
SysTime cursor = ceilToGranularity(std::max(window.start, rangeStart), granularityMinutes);
if (cursor >= window.end)
{
continue;
}
for (const TimeRange& occupied : busy)
{
if (occupied.end <= cursor)
{
continue;
}
if (occupied.start >= cursor + duration)
{
if (deadline && cursor + duration > *deadline)
{
return std::nullopt;
}
return TimeRange{cursor, cursor + duration};
}
if (occupied.end > cursor)
{
cursor = ceilToGranularity(occupied.end, granularityMinutes);
if (cursor >= window.end)
{
break;
}
}
}
if (cursor + duration <= window.end)
{
if (deadline && cursor + duration > *deadline)
{
continue;
}
return TimeRange{cursor, cursor + duration};
}
}
return std::nullopt;
}
void addBusy(std::vector<TimeRange>& busy, const TimeRange& range)
{
busy.push_back(range);
mergeBusy(busy);
}
} // namespace
Result schedule(const std::vector<TaskInput>& tasks,
const std::vector<TimeRange>& busyInput,
const std::vector<TimeRange>& allowedWindows,
SysTime rangeStart,
SysTime rangeEnd,
const Options& options)
{
Result result;
if (rangeStart >= rangeEnd || tasks.empty())
{
for (const TaskInput& task : tasks)
{
result.failures.push_back({task.id, "没有可用的排程范围"});
}
return result;
}
std::vector<TimeRange> windows;
windows.reserve(allowedWindows.size());
for (const TimeRange& window : allowedWindows)
{
const SysTime start = std::max(window.start, rangeStart);
const SysTime end = std::min(window.end, rangeEnd);
if (start < end)
{
windows.push_back({start, end});
}
}
std::sort(windows.begin(), windows.end(), [](const TimeRange& a, const TimeRange& b) {
return a.start < b.start;
});
std::vector<TimeRange> busy;
busy.reserve(busyInput.size());
for (const TimeRange& interval : busyInput)
{
if (interval.end <= rangeStart || interval.start >= rangeEnd)
{
continue;
}
busy.push_back({std::max(interval.start, rangeStart), std::min(interval.end, rangeEnd)});
}
mergeBusy(busy);
std::vector<TaskInput> ordered = tasks;
std::sort(ordered.begin(), ordered.end(), [](const TaskInput& a, const TaskInput& b) {
if (a.priority != b.priority)
{
return a.priority > b.priority;
}
if (a.deadline.has_value() != b.deadline.has_value())
{
return a.deadline.has_value();
}
if (a.deadline.has_value() && b.deadline.has_value() && *a.deadline != *b.deadline)
{
return *a.deadline < *b.deadline;
}
if (a.durationMinutes != b.durationMinutes)
{
return a.durationMinutes > b.durationMinutes;
}
return a.id < b.id;
});
for (const TaskInput& task : ordered)
{
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;
if (deadline && *deadline <= rangeStart)
{
result.failures.push_back({task.id, "截止时间已经过去"});
continue;
}
std::optional<TimeRange> slot;
if (task.preferredStart.has_value() && task.preferredEnd.has_value() &&
*task.preferredStart < *task.preferredEnd)
{
// 显式偏好时间优先于默认工作时段(例如用户明确要求 23:00)。
const SysTime lower = std::max(*task.preferredStart, rangeStart);
const SysTime upper =
deadline ? std::min(*task.preferredEnd, *deadline) : *task.preferredEnd;
if (lower < upper)
{
const std::vector<TimeRange> preferredWindows = {{lower, upper}};
slot = findSlot(preferredWindows,
busy,
rangeStart,
deadline,
duration,
options.granularityMinutes);
}
}
if (!slot.has_value())
{
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);
}
if (!slot.has_value())
{
result.failures.push_back(
{task.id,
deadline.has_value() ? "截止时间前没有可用时间" : "可用时间范围内没有空档"});
continue;
}
result.placements.push_back({task.id, slot->start, slot->end});
addBusy(busy, *slot);
}
return result;
}
} // namespace scheduler
+72
View File
@@ -0,0 +1,72 @@
#pragma once
#include <chrono>
#include <optional>
#include <string>
#include <vector>
/*
* 命名空间: scheduler
* 功能: 确定性排程引擎(无 Qt 依赖):在给定可用时间窗和忙碌区间内安排任务
* 线程安全: 是(纯函数,不共享状态)
*/
namespace scheduler
{
using SysTime = std::chrono::sys_seconds;
struct TimeRange
{
SysTime start;
SysTime end;
};
struct TaskInput
{
std::string id;
std::string title;
int durationMinutes = 60;
int priority = 1;
int energyRequired = -1;
bool splittable = false;
std::optional<SysTime> deadline;
std::optional<SysTime> preferredStart;
std::optional<SysTime> preferredEnd;
};
struct ScheduledSlot
{
std::string taskId;
SysTime start;
SysTime end;
};
struct Failure
{
std::string taskId;
std::string reason;
};
struct Options
{
int granularityMinutes = 15;
};
struct Result
{
std::vector<ScheduledSlot> placements;
std::vector<Failure> failures;
};
/*
* 在 allowedWindows 内为任务寻找不冲突的时间片。
* preferredStart/End 会优先尝试;失败后回退到其他允许时间窗(仍受 deadline 约束)。
*/
Result schedule(const std::vector<TaskInput>& tasks,
const std::vector<TimeRange>& busy,
const std::vector<TimeRange>& allowedWindows,
SysTime rangeStart,
SysTime rangeEnd,
const Options& options = {});
} // namespace scheduler
+35
View File
@@ -0,0 +1,35 @@
#pragma once
#include <QJsonObject>
#include <QString>
/*
* 类名: SyncOutboxItem
* 功能: 本地待推送变更(由 SQLite trigger 写入 sync_outbox)
* 线程安全: 否(值类型)
*/
struct SyncOutboxItem
{
qint64 id = 0;
QString entityType;
QString entityId;
QString op;
QJsonObject payload;
};
/*
* 类名: RemoteChange
* 功能: 从同步服务端拉取的变更记录
* 线程安全: 否(值类型)
*/
struct RemoteChange
{
qint64 seq = 0;
QString deviceId;
QString entityType;
QString entityId;
QString op;
qint64 version = 0;
QString updatedAt;
QJsonObject payload;
};
+29
View File
@@ -0,0 +1,29 @@
#pragma once
#include <QDateTime>
#include <QString>
#include <optional>
/*
* 类名: Task
* 功能: 用户意图层的任务实体,对应数据库 task 表
* 线程安全: 否(值类型,跨线程传递前需拷贝)
*/
struct Task
{
QString id;
QString title;
QString description;
QString source = QStringLiteral("manual");
QString sourceRef;
std::optional<int> estimatedMin;
std::optional<int> energyReq;
std::optional<QDateTime> 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 <QDateTime>
#include <QString>
#include <optional>
/*
* 类名: TimeBlock
* 功能: 执行层的具体时间片,对应数据库 timeblock 表
* 线程安全: 否(值类型)
*/
struct TimeBlock
{
QString id;
QString taskId;
QDateTime startAt;
QDateTime endAt;
int granularity = 15;
bool splittable = true;
bool breakable = true;
QString status = QStringLiteral("scheduled");
std::optional<QDateTime> doneAt;
QDateTime createdAt;
QDateTime updatedAt;
int version = 0;
QString deviceId;
};
+99
View File
@@ -0,0 +1,99 @@
#include <QApplication>
#include <QFont>
#include <QFontDatabase>
#include <QMessageBox>
#include <QTimer>
#include <cstdio>
#include "ElaApplication.h"
#include "services/NotificationService.h"
#include "ai/AIService.h"
#include "services/ScheduleService.h"
#include "sync/SyncService.h"
#include "storage/SqliteStore.h"
#include "ui/AppIcon.h"
#include "ui/CompactWindow.h"
#include "ui/theme/WindowEffects.h"
#include "ui/theme/ThemeManager.h"
#include "utils/AppSettings.h"
namespace
{
void applyCjkFont()
{
const QStringList preferred = {
QStringLiteral("Noto Sans CJK SC"),
QStringLiteral("Noto Sans SC"),
QStringLiteral("Source Han Sans SC"),
QStringLiteral("WenQuanYi Micro Hei"),
QStringLiteral("Microsoft YaHei"),
};
const QStringList families = QFontDatabase::families();
for (const QString& candidate : preferred)
{
if (families.contains(candidate))
{
QFont font(candidate);
font.setPixelSize(13);
font.setHintingPreference(QFont::PreferNoHinting);
QApplication::setFont(font);
return;
}
}
}
} // namespace
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
app.setOrganizationName(QStringLiteral("Misaki"));
app.setOrganizationDomain(QStringLiteral("misaki.local"));
app.setApplicationName(QStringLiteral("Schedule"));
app.setApplicationDisplayName(QStringLiteral("AI 日程"));
app.setApplicationVersion(QStringLiteral("0.1.0"));
QApplication::setWindowIcon(AppIcon::create());
QApplication::setStyle(QStringLiteral("Fusion"));
eApp->init();
applyCjkFont();
AppSettings settings;
SqliteStore store(settings.databasePath());
QString databaseError;
if (!store.open(&databaseError))
{
std::fprintf(stderr, "Failed to open database: %s\n", qPrintable(databaseError));
QMessageBox::critical(nullptr,
QStringLiteral("数据库错误"),
QStringLiteral("无法打开本地数据库:\n%1").arg(databaseError));
return 1;
}
ThemeManager themeManager(settings);
themeManager.initialize();
const bool micaEnabled = settings.micaEnabled();
ScheduleService scheduleService(store, settings.deviceId());
NotificationService notificationService(scheduleService);
AIService aiService(scheduleService, store, settings);
SyncService syncService(scheduleService, store, settings);
CompactWindow window(scheduleService,
notificationService,
aiService,
themeManager,
settings,
&syncService);
window.show();
notificationService.start(20000);
syncService.start();
// 等窗口先以普通背景完成首帧,再初始化云母,避免 ElaMica 基底图未就绪时出现空图告警。
if (micaEnabled)
{
QTimer::singleShot(0, qApp, []() { WindowEffects::applyMica(true); });
}
return app.exec();
}
+118
View File
@@ -0,0 +1,118 @@
#include "SystemTray.h"
#include <QAction>
#include <QSystemTrayIcon>
#include "ElaMenu.h"
#include "ui/AppIcon.h"
SystemTray::SystemTray(QObject* parent)
: QObject(parent)
{
if (!QSystemTrayIcon::isSystemTrayAvailable())
{
return;
}
m_trayIcon = new QSystemTrayIcon(AppIcon::create(), this);
m_trayIcon->setToolTip(QStringLiteral("AI 日程"));
m_menu = new ElaMenu();
rebuildMenu();
m_trayIcon->setContextMenu(m_menu);
connect(m_trayIcon, &QSystemTrayIcon::activated, this, [this](QSystemTrayIcon::ActivationReason reason) {
switch (reason)
{
case QSystemTrayIcon::Trigger:
case QSystemTrayIcon::DoubleClick:
case QSystemTrayIcon::MiddleClick:
Q_EMIT showRequested();
break;
default:
break;
}
});
connect(m_trayIcon, &QSystemTrayIcon::messageClicked, this, &SystemTray::showRequested);
}
SystemTray::~SystemTray()
{
if (m_trayIcon)
{
m_trayIcon->hide();
}
delete m_menu;
}
bool SystemTray::isAvailable()
{
return QSystemTrayIcon::isSystemTrayAvailable();
}
bool SystemTray::isVisible() const
{
return m_trayIcon && m_trayIcon->isVisible();
}
void SystemTray::show()
{
if (m_trayIcon)
{
m_trayIcon->show();
}
}
void SystemTray::hide()
{
if (m_trayIcon)
{
m_trayIcon->hide();
}
}
void SystemTray::showNotification(const QString& title, const QString& message, int timeoutMs)
{
if (!m_trayIcon || !m_trayIcon->isVisible())
{
return;
}
m_trayIcon->showMessage(title, message, QSystemTrayIcon::Information, timeoutMs);
}
void SystemTray::setOverdueCount(int count)
{
m_overdueCount = count;
if (!m_trayIcon)
{
return;
}
m_trayIcon->setToolTip(count > 0 ? QStringLiteral("AI 日程 · %1 项已超时").arg(count)
: QStringLiteral("AI 日程"));
rebuildMenu();
}
void SystemTray::rebuildMenu()
{
if (!m_menu)
{
return;
}
m_menu->clear();
m_statusAction = m_menu->addAction(m_overdueCount > 0
? QStringLiteral("待处理超时日程:%1 项").arg(m_overdueCount)
: QStringLiteral("暂无超时日程"));
m_statusAction->setEnabled(false);
m_menu->addSeparator();
QAction* showAction = m_menu->addAction(QStringLiteral("显示主窗口"));
connect(showAction, &QAction::triggered, this, &SystemTray::showRequested);
QAction* newAction = m_menu->addAction(QStringLiteral("新建日程"));
connect(newAction, &QAction::triggered, this, &SystemTray::newBlockRequested);
m_menu->addSeparator();
QAction* quitAction = m_menu->addAction(QStringLiteral("退出"));
connect(quitAction, &QAction::triggered, this, &SystemTray::quitRequested);
}
+44
View File
@@ -0,0 +1,44 @@
#pragma once
#include <QObject>
#include <QString>
class QSystemTrayIcon;
class ElaMenu;
class QAction;
/*
* 类名: SystemTray
* 功能: 托盘常驻、菜单与系统通知的跨平台封装;不可用时由上层降级
* 线程安全: 否;主线程使用
*/
class SystemTray : public QObject
{
Q_OBJECT
public:
explicit SystemTray(QObject* parent = nullptr);
~SystemTray() override;
static bool isAvailable();
bool isVisible() const;
void show();
void hide();
void showNotification(const QString& title, const QString& message, int timeoutMs = 6000);
void setOverdueCount(int count);
signals:
void showRequested();
void newBlockRequested();
void quitRequested();
private:
void rebuildMenu();
QSystemTrayIcon* m_trayIcon = nullptr;
ElaMenu* m_menu = nullptr;
QAction* m_statusAction = nullptr;
int m_overdueCount = 0;
};
@@ -0,0 +1,92 @@
#include "NotificationService.h"
#include <QDateTime>
#include <algorithm>
#include "ScheduleService.h"
NotificationService::NotificationService(ScheduleService& scheduleService, QObject* parent)
: QObject(parent)
, m_scheduleService(scheduleService)
{
qRegisterMetaType<ScheduleItem>("ScheduleItem");
qRegisterMetaType<QVector<ScheduleItem>>("QVector<ScheduleItem>");
m_timer.setSingleShot(false);
connect(&m_timer, &QTimer::timeout, this, &NotificationService::checkNow);
connect(&m_scheduleService, &ScheduleService::dataChanged, this, &NotificationService::checkNow);
}
void NotificationService::start(int intervalMs)
{
m_timer.setInterval(std::max(1000, intervalMs));
m_timer.start();
checkNow();
}
void NotificationService::stop()
{
m_timer.stop();
}
void NotificationService::checkNow()
{
const QVector<ScheduleItem> current = m_scheduleService.overdueItems(QDateTime::currentDateTime());
QSet<QString> currentIds;
currentIds.reserve(current.size());
for (const ScheduleItem& item : current)
{
currentIds.insert(item.block.id);
}
// 已不再超时的块从记忆集合移除,后续再次超时可重新提醒。
QSet<QString> retained;
retained.reserve(m_notifiedIds.size());
for (const QString& id : m_notifiedIds)
{
if (currentIds.contains(id))
{
retained.insert(id);
}
}
m_notifiedIds = retained;
for (const ScheduleItem& item : current)
{
if (!m_notifiedIds.contains(item.block.id))
{
m_notifiedIds.insert(item.block.id);
Q_EMIT overdueDetected(item);
}
}
const bool changed = [&]() {
if (m_overdueItems.size() != current.size())
{
return true;
}
for (int i = 0; i < current.size(); ++i)
{
if (m_overdueItems.at(i).block.id != current.at(i).block.id ||
m_overdueItems.at(i).block.status != current.at(i).block.status ||
m_overdueItems.at(i).block.endAt != current.at(i).block.endAt)
{
return true;
}
}
return false;
}();
m_overdueItems = current;
if (changed)
{
Q_EMIT overdueListChanged(m_overdueItems);
}
}
QVector<ScheduleItem> NotificationService::overdueItems() const
{
return m_overdueItems;
}
+38
View File
@@ -0,0 +1,38 @@
#pragma once
#include <QObject>
#include <QSet>
#include <QTimer>
#include <QVector>
#include "core/ScheduleItem.h"
class ScheduleService;
/*
* 类名: NotificationService
* 功能: 周期性检测超时未完成日程并发出通知信号;不直接依赖任何 UI/平台 API
* 线程安全: 否;主线程使用
*/
class NotificationService : public QObject
{
Q_OBJECT
public:
explicit NotificationService(ScheduleService& scheduleService, QObject* parent = nullptr);
void start(int intervalMs = 20000);
void stop();
void checkNow();
QVector<ScheduleItem> overdueItems() const;
signals:
void overdueDetected(const ScheduleItem& item);
void overdueListChanged(const QVector<ScheduleItem>& items);
private:
ScheduleService& m_scheduleService;
QTimer m_timer;
QSet<QString> m_notifiedIds;
QVector<ScheduleItem> m_overdueItems;
};
+952
View File
@@ -0,0 +1,952 @@
#include "ScheduleService.h"
#include <QDateTime>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QSet>
#include <QUuid>
#include <algorithm>
#include "core/DateTimeUtils.h"
#include "storage/SqliteStore.h"
namespace
{
constexpr int kMinBlockMinutes = 5;
constexpr int kMaxBlockMinutes = 24 * 60;
QDateTime truncateToMinute(const QDateTime& value)
{
return QDateTime(value.date(), QTime(value.time().hour(), value.time().minute()), value.timeSpec());
}
} // namespace
ScheduleService::ScheduleService(SqliteStore& store, QString deviceId, QObject* parent)
: QObject(parent)
, m_store(store)
, m_deviceId(std::move(deviceId))
{
}
bool ScheduleService::validateRange(const QDateTime& start, const QDateTime& end, QString* error)
{
if (!start.isValid() || !end.isValid())
{
const QString message = QStringLiteral("开始或结束时间无效");
m_lastError = message;
if (error)
{
*error = message;
}
return false;
}
const int duration = DateTimeUtils::minutesBetween(start, end);
if (duration < kMinBlockMinutes)
{
const QString message = QStringLiteral("日程时长至少需要 %1 分钟").arg(kMinBlockMinutes);
m_lastError = message;
if (error)
{
*error = message;
}
return false;
}
if (duration > kMaxBlockMinutes)
{
const QString message = QStringLiteral("单次日程不能超过 24 小时");
m_lastError = message;
if (error)
{
*error = message;
}
return false;
}
return true;
}
QString ScheduleService::newId() const
{
return QUuid::createUuid().toString(QUuid::WithoutBraces);
}
bool ScheduleService::touchTask(Task& task) const
{
task.updatedAt = QDateTime::currentDateTime();
task.version += 1;
task.deviceId = m_deviceId;
return true;
}
bool ScheduleService::touchBlock(TimeBlock& block) const
{
block.updatedAt = QDateTime::currentDateTime();
block.version += 1;
block.deviceId = m_deviceId;
return true;
}
bool ScheduleService::createBlock(const QString& title,
const QDateTime& start,
const QDateTime& end,
QString* error)
{
const QDateTime normalizedStart = truncateToMinute(start);
const QDateTime normalizedEnd = truncateToMinute(end);
if (!validateRange(normalizedStart, normalizedEnd, error))
{
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.createdAt = now;
task.updatedAt = now;
task.version = 0;
task.deviceId = m_deviceId;
TimeBlock block;
block.id = newId();
block.taskId = task.id;
block.startAt = normalizedStart;
block.endAt = normalizedEnd;
block.createdAt = now;
block.updatedAt = now;
block.version = 0;
block.deviceId = m_deviceId;
if (!m_store.beginTransaction())
{
m_lastError = m_store.lastError();
if (error)
{
*error = m_lastError;
}
return false;
}
if (!m_store.insertTask(task) || !m_store.insertTimeBlock(block))
{
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;
}
m_lastError.clear();
Q_EMIT dataChanged();
return true;
}
bool ScheduleService::updateBlock(const QString& blockId,
const QString& title,
const QDateTime& start,
const QDateTime& end,
QString* error)
{
const QDateTime normalizedStart = truncateToMinute(start);
const QDateTime normalizedEnd = truncateToMinute(end);
if (!validateRange(normalizedStart, normalizedEnd, error))
{
return false;
}
const auto block = m_store.timeBlockById(blockId);
if (!block.has_value())
{
m_lastError = QStringLiteral("日程不存在: %1").arg(blockId);
if (error)
{
*error = m_lastError;
}
return false;
}
auto task = m_store.taskById(block->taskId);
if (!task.has_value())
{
m_lastError = QStringLiteral("日程对应的任务不存在: %1").arg(block->taskId);
if (error)
{
*error = m_lastError;
}
return false;
}
TimeBlock updatedBlock = *block;
updatedBlock.startAt = normalizedStart;
updatedBlock.endAt = normalizedEnd;
touchBlock(updatedBlock);
Task updatedTask = *task;
const QString trimmedTitle = title.trimmed();
updatedTask.title = trimmedTitle.isEmpty() ? QStringLiteral("未命名日程") : trimmedTitle;
touchTask(updatedTask);
if (!m_store.beginTransaction())
{
m_lastError = m_store.lastError();
if (error)
{
*error = m_lastError;
}
return false;
}
if (!m_store.updateTask(updatedTask) || !m_store.updateTimeBlock(updatedBlock))
{
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;
}
m_lastError.clear();
Q_EMIT dataChanged();
return true;
}
bool ScheduleService::moveBlock(const QString& blockId,
const QDateTime& start,
const QDateTime& end,
QString* error)
{
const QDateTime normalizedStart = truncateToMinute(start);
const QDateTime normalizedEnd = truncateToMinute(end);
if (!validateRange(normalizedStart, normalizedEnd, error))
{
return false;
}
auto block = m_store.timeBlockById(blockId);
if (!block.has_value())
{
m_lastError = QStringLiteral("日程不存在: %1").arg(blockId);
if (error)
{
*error = m_lastError;
}
return false;
}
block->startAt = normalizedStart;
block->endAt = normalizedEnd;
touchBlock(*block);
if (!m_store.updateTimeBlock(*block))
{
m_lastError = m_store.lastError();
if (error)
{
*error = m_lastError;
}
return false;
}
m_lastError.clear();
Q_EMIT dataChanged();
return true;
}
bool ScheduleService::setBlockStatus(const QString& blockId, const QString& status, QString* error)
{
static const QStringList allowed = {
QStringLiteral("scheduled"),
QStringLiteral("in_progress"),
QStringLiteral("done"),
QStringLiteral("missed"),
QStringLiteral("dropped"),
};
if (!allowed.contains(status))
{
m_lastError = QStringLiteral("非法日程状态: %1").arg(status);
if (error)
{
*error = m_lastError;
}
return false;
}
auto block = m_store.timeBlockById(blockId);
if (!block.has_value())
{
m_lastError = QStringLiteral("日程不存在: %1").arg(blockId);
if (error)
{
*error = m_lastError;
}
return false;
}
block->status = status;
block->doneAt = status == QStringLiteral("done") ? std::optional<QDateTime>(QDateTime::currentDateTime())
: std::nullopt;
touchBlock(*block);
if (!m_store.updateTimeBlock(*block))
{
m_lastError = m_store.lastError();
if (error)
{
*error = m_lastError;
}
return false;
}
m_lastError.clear();
Q_EMIT dataChanged();
return true;
}
bool ScheduleService::postponeBlock(const QString& blockId, int minutes, QString* error)
{
auto block = m_store.timeBlockById(blockId);
if (!block.has_value())
{
m_lastError = QStringLiteral("日程不存在: %1").arg(blockId);
if (error)
{
*error = m_lastError;
}
return false;
}
block->startAt = block->startAt.addSecs(minutes * 60);
block->endAt = block->endAt.addSecs(minutes * 60);
block->status = QStringLiteral("scheduled");
block->doneAt = std::nullopt;
touchBlock(*block);
if (!m_store.updateTimeBlock(*block))
{
m_lastError = m_store.lastError();
if (error)
{
*error = m_lastError;
}
return false;
}
m_lastError.clear();
Q_EMIT dataChanged();
return true;
}
bool ScheduleService::deleteBlock(const QString& blockId, QString* error)
{
const auto block = m_store.timeBlockById(blockId);
if (!block.has_value())
{
m_lastError = QStringLiteral("日程不存在: %1").arg(blockId);
if (error)
{
*error = m_lastError;
}
return false;
}
if (!m_store.beginTransaction())
{
m_lastError = m_store.lastError();
if (error)
{
*error = m_lastError;
}
return false;
}
if (!m_store.deleteTimeBlock(blockId))
{
m_store.rollback();
m_lastError = m_store.lastError();
if (error)
{
*error = m_lastError;
}
return false;
}
if (!m_store.hasBlocksForTask(block->taskId) && !m_store.deleteTask(block->taskId))
{
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;
}
m_lastError.clear();
Q_EMIT dataChanged();
return true;
}
bool ScheduleService::applyProposedDiff(const ProposedDiff& diff,
const QStringList& acceptedTempIds,
QString* error)
{
QSet<QString> accepted;
for (const QString& id : acceptedTempIds)
{
accepted.insert(id);
}
if (accepted.isEmpty())
{
m_lastError = QStringLiteral("没有选择任何日程");
if (error)
{
*error = m_lastError;
}
return false;
}
struct PendingCreate
{
Task task;
QVector<TimeBlock> blocks;
};
struct PendingUpdate
{
Task task;
TimeBlock block;
bool timeChanged = false;
};
struct PendingDelete
{
QString blockId;
QString taskId;
};
QVector<PendingCreate> creates;
QVector<PendingUpdate> updates;
QVector<PendingDelete> deletes;
QSet<QString> updatedBlockIds;
QSet<QString> deletedBlockIds;
const QDateTime now = QDateTime::currentDateTime();
const QJsonArray createArray = diff.payload.value(QStringLiteral("creates")).toArray();
for (const QJsonValue& value : createArray)
{
const QJsonObject create = value.toObject();
const QString tempId = create.value(QStringLiteral("temp_id")).toString();
if (!accepted.contains(tempId))
{
continue;
}
const QJsonObject taskObject = create.value(QStringLiteral("task")).toObject();
const QString title = taskObject.value(QStringLiteral("title")).toString().trimmed();
if (title.isEmpty())
{
m_lastError = QStringLiteral("AI 提议中的新增日程数据无效: %1").arg(tempId);
if (error)
{
*error = m_lastError;
}
return false;
}
QJsonArray blockArray = create.value(QStringLiteral("blocks")).toArray();
if (blockArray.isEmpty() && create.value(QStringLiteral("block")).isObject())
{
blockArray.append(create.value(QStringLiteral("block")));
}
if (blockArray.isEmpty())
{
m_lastError = QStringLiteral("AI 提议中的新增日程缺少时间块: %1").arg(tempId);
if (error)
{
*error = m_lastError;
}
return false;
}
PendingCreate entry;
entry.task.id = newId();
entry.task.title = title;
entry.task.description = taskObject.value(QStringLiteral("description")).toString();
entry.task.source = QStringLiteral("ai_chat");
entry.task.sourceRef = taskObject.value(QStringLiteral("source_ref")).toString();
if (taskObject.contains(QStringLiteral("energy_req")) &&
taskObject.value(QStringLiteral("energy_req")).isDouble())
{
entry.task.energyReq = taskObject.value(QStringLiteral("energy_req")).toInt();
}
const QString deadlineText = taskObject.value(QStringLiteral("deadline")).toString();
if (!deadlineText.isEmpty())
{
const QDateTime deadline = DateTimeUtils::fromDb(deadlineText);
if (deadline.isValid())
{
entry.task.deadline = deadline;
}
}
entry.task.priority = qBound(1, taskObject.value(QStringLiteral("priority")).toInt(1), 5);
entry.task.createdAt = now;
entry.task.updatedAt = now;
entry.task.version = 0;
entry.task.deviceId = m_deviceId;
int totalMinutes = 0;
for (const QJsonValue& blockValue : blockArray)
{
const QJsonObject blockObject = blockValue.toObject();
const QDateTime start =
DateTimeUtils::fromDb(blockObject.value(QStringLiteral("start_at")).toString());
const QDateTime end =
DateTimeUtils::fromDb(blockObject.value(QStringLiteral("end_at")).toString());
if (!start.isValid() || !end.isValid() || end <= start)
{
m_lastError = QStringLiteral("AI 提议中的新增日程时间块无效: %1").arg(tempId);
if (error)
{
*error = m_lastError;
}
return false;
}
TimeBlock block;
block.id = newId();
block.taskId = entry.task.id;
block.startAt = start;
block.endAt = end;
block.granularity = blockObject.value(QStringLiteral("granularity")).toInt(15);
block.splittable = blockObject.value(QStringLiteral("splittable")).toBool(true);
block.breakable = blockObject.value(QStringLiteral("breakable")).toBool(true);
block.status = QStringLiteral("scheduled");
block.createdAt = now;
block.updatedAt = now;
block.version = 0;
block.deviceId = m_deviceId;
entry.blocks.append(block);
totalMinutes += DateTimeUtils::minutesBetween(start, end);
}
entry.task.estimatedMin =
taskObject.value(QStringLiteral("estimated_min")).toInt(totalMinutes);
creates.append(entry);
}
const QJsonArray updateArray = diff.payload.value(QStringLiteral("updates")).toArray();
for (const QJsonValue& value : updateArray)
{
const QJsonObject update = value.toObject();
const QString tempId = update.value(QStringLiteral("temp_id")).toString();
if (!accepted.contains(tempId))
{
continue;
}
const QString blockId = update.value(QStringLiteral("block_id")).toString();
if (blockId.isEmpty() || deletedBlockIds.contains(blockId) || updatedBlockIds.contains(blockId))
{
m_lastError = QStringLiteral("AI 提议中的修改目标无效: %1").arg(tempId);
if (error)
{
*error = m_lastError;
}
return false;
}
const auto currentBlock = m_store.timeBlockById(blockId);
if (!currentBlock.has_value())
{
m_lastError = QStringLiteral("要修改的日程已经不存在: %1").arg(blockId);
if (error)
{
*error = m_lastError;
}
return false;
}
auto currentTask = m_store.taskById(currentBlock->taskId);
if (!currentTask.has_value())
{
m_lastError = QStringLiteral("要修改的日程对应任务不存在: %1").arg(currentBlock->taskId);
if (error)
{
*error = m_lastError;
}
return false;
}
const QJsonObject taskObject = update.value(QStringLiteral("task")).toObject();
const QJsonObject blockObject = update.value(QStringLiteral("block")).toObject();
const QString title = taskObject.value(QStringLiteral("title")).toString().trimmed();
const QDateTime start = DateTimeUtils::fromDb(blockObject.value(QStringLiteral("start_at")).toString());
const QDateTime end = DateTimeUtils::fromDb(blockObject.value(QStringLiteral("end_at")).toString());
if (title.isEmpty() || !start.isValid() || !end.isValid() || end <= start)
{
m_lastError = QStringLiteral("AI 提议中的修改数据无效: %1").arg(tempId);
if (error)
{
*error = m_lastError;
}
return false;
}
PendingUpdate entry;
entry.task = *currentTask;
entry.task.title = title;
if (taskObject.contains(QStringLiteral("description")))
{
entry.task.description = taskObject.value(QStringLiteral("description")).toString();
}
entry.task.estimatedMin = DateTimeUtils::minutesBetween(start, end);
if (taskObject.contains(QStringLiteral("energy_req")))
{
if (taskObject.value(QStringLiteral("energy_req")).isDouble())
{
entry.task.energyReq = taskObject.value(QStringLiteral("energy_req")).toInt();
}
else
{
entry.task.energyReq.reset();
}
}
const QString deadlineText = taskObject.value(QStringLiteral("deadline")).toString();
if (!deadlineText.isEmpty())
{
const QDateTime deadline = DateTimeUtils::fromDb(deadlineText);
entry.task.deadline = deadline.isValid() ? std::optional<QDateTime>(deadline) : std::nullopt;
}
entry.task.priority = qBound(1, taskObject.value(QStringLiteral("priority")).toInt(entry.task.priority), 5);
entry.block = *currentBlock;
entry.timeChanged = (currentBlock->startAt != start || currentBlock->endAt != end);
entry.block.startAt = start;
entry.block.endAt = end;
if (blockObject.contains(QStringLiteral("granularity")))
{
entry.block.granularity = blockObject.value(QStringLiteral("granularity")).toInt(15);
}
if (blockObject.contains(QStringLiteral("splittable")))
{
entry.block.splittable = blockObject.value(QStringLiteral("splittable")).toBool(true);
}
if (blockObject.contains(QStringLiteral("breakable")))
{
entry.block.breakable = blockObject.value(QStringLiteral("breakable")).toBool(true);
}
touchTask(entry.task);
touchBlock(entry.block);
updates.append(entry);
updatedBlockIds.insert(blockId);
}
const QJsonArray deleteArray = diff.payload.value(QStringLiteral("deletes")).toArray();
for (const QJsonValue& value : deleteArray)
{
const QJsonObject object = value.toObject();
const QString tempId = object.value(QStringLiteral("temp_id")).toString();
if (!accepted.contains(tempId))
{
continue;
}
const QString blockId = object.value(QStringLiteral("block_id")).toString();
if (blockId.isEmpty() || updatedBlockIds.contains(blockId) || deletedBlockIds.contains(blockId))
{
m_lastError = QStringLiteral("AI 提议中的删除目标无效: %1").arg(tempId);
if (error)
{
*error = m_lastError;
}
return false;
}
const auto block = m_store.timeBlockById(blockId);
if (!block.has_value())
{
m_lastError = QStringLiteral("要删除的日程已经不存在: %1").arg(blockId);
if (error)
{
*error = m_lastError;
}
return false;
}
deletes.append({blockId, block->taskId});
deletedBlockIds.insert(blockId);
}
if (creates.isEmpty() && updates.isEmpty() && deletes.isEmpty())
{
m_lastError = QStringLiteral("AI 提议中没有选中的有效操作");
if (error)
{
*error = m_lastError;
}
return false;
}
// 冲突检查:只检查新增/改时间的块,避免用户只接受部分涟漪调整时产生重叠。
if (!creates.isEmpty() || std::any_of(updates.cbegin(), updates.cend(), [](const PendingUpdate& u) {
return u.timeChanged;
}))
{
QVector<QPair<QString, QPair<QDateTime, QDateTime>>> candidates;
for (const PendingCreate& entry : creates)
{
for (const TimeBlock& block : entry.blocks)
{
candidates.append({block.id, {block.startAt, block.endAt}});
}
}
for (const PendingUpdate& entry : updates)
{
if (entry.timeChanged)
{
candidates.append({entry.block.id, {entry.block.startAt, entry.block.endAt}});
}
}
QDate minDate = QDate::currentDate();
QDate maxDate = QDate::currentDate();
bool first = true;
for (const auto& candidate : candidates)
{
const QDate startDate = candidate.second.first.date();
const QDate endDate = candidate.second.second.date();
if (first)
{
minDate = startDate;
maxDate = endDate;
first = false;
}
else
{
minDate = std::min(minDate, startDate);
maxDate = std::max(maxDate, endDate);
}
}
QSet<QString> ignoredBlockIds = deletedBlockIds;
for (const PendingUpdate& entry : updates)
{
if (entry.timeChanged)
{
ignoredBlockIds.insert(entry.block.id);
}
}
const QVector<ScheduleItem> existing =
m_store.blocksInRange(DateTimeUtils::localDayStartUtc(minDate.addDays(-1)),
DateTimeUtils::localDayEndUtc(maxDate.addDays(1)));
QVector<QPair<QDateTime, QDateTime>> occupied;
for (const ScheduleItem& item : existing)
{
if (ignoredBlockIds.contains(item.block.id))
{
continue;
}
if (item.block.status != QStringLiteral("scheduled") &&
item.block.status != QStringLiteral("in_progress"))
{
continue;
}
occupied.append({item.block.startAt, item.block.endAt});
}
for (const auto& candidate : candidates)
{
const QDateTime start = candidate.second.first;
const QDateTime end = candidate.second.second;
for (const auto& interval : occupied)
{
if (start < interval.second && end > interval.first)
{
m_lastError = QStringLiteral("应用后会产生时间冲突,请同时接受相关涟漪调整");
if (error)
{
*error = m_lastError;
}
return false;
}
}
for (const auto& other : candidates)
{
if (candidate.first == other.first)
{
continue;
}
if (start < other.second.second && end > other.second.first)
{
m_lastError = QStringLiteral("AI 提议中的多个日程彼此重叠");
if (error)
{
*error = m_lastError;
}
return false;
}
}
}
}
if (!m_store.beginTransaction())
{
m_lastError = m_store.lastError();
if (error)
{
*error = m_lastError;
}
return false;
}
for (const PendingDelete& entry : deletes)
{
if (!m_store.deleteTimeBlock(entry.blockId))
{
m_store.rollback();
m_lastError = m_store.lastError();
if (error)
{
*error = m_lastError;
}
return false;
}
if (!m_store.hasBlocksForTask(entry.taskId) && !m_store.deleteTask(entry.taskId))
{
m_store.rollback();
m_lastError = m_store.lastError();
if (error)
{
*error = m_lastError;
}
return false;
}
}
for (const PendingUpdate& entry : updates)
{
if (!m_store.updateTask(entry.task) || !m_store.updateTimeBlock(entry.block))
{
m_store.rollback();
m_lastError = m_store.lastError();
if (error)
{
*error = m_lastError;
}
return false;
}
}
for (const PendingCreate& entry : creates)
{
if (!m_store.insertTask(entry.task))
{
m_store.rollback();
m_lastError = m_store.lastError();
if (error)
{
*error = m_lastError;
}
return false;
}
for (const TimeBlock& block : entry.blocks)
{
if (!m_store.insertTimeBlock(block))
{
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;
}
m_lastError.clear();
Q_EMIT dataChanged();
return true;
}
bool ScheduleService::applyProposedCreates(const ProposedDiff& diff,
const QStringList& acceptedTempIds,
QString* error)
{
return applyProposedDiff(diff, acceptedTempIds, error);
}
QVector<ScheduleItem> ScheduleService::itemsForDay(const QDate& date) const
{
auto items = m_store.blocksInRange(DateTimeUtils::localDayStartUtc(date),
DateTimeUtils::localDayEndUtc(date));
std::sort(items.begin(), items.end(), [](const ScheduleItem& a, const ScheduleItem& b) {
if (a.block.startAt != b.block.startAt)
{
return a.block.startAt < b.block.startAt;
}
return a.block.id < b.block.id;
});
return items;
}
QVector<ScheduleItem> ScheduleService::itemsForRange(const QDate& from, const QDate& to) const
{
if (!from.isValid() || !to.isValid() || from > to)
{
return {};
}
auto items = m_store.blocksInRange(DateTimeUtils::localDayStartUtc(from),
DateTimeUtils::localDayEndUtc(to));
std::sort(items.begin(), items.end(), [](const ScheduleItem& a, const ScheduleItem& b) {
if (a.block.startAt != b.block.startAt)
{
return a.block.startAt < b.block.startAt;
}
return a.block.id < b.block.id;
});
return items;
}
QVector<ScheduleItem> ScheduleService::overdueItems(const QDateTime& now) const
{
auto items = m_store.overdueBefore(now.toUTC());
std::sort(items.begin(), items.end(), [](const ScheduleItem& a, const ScheduleItem& b) {
return a.block.endAt < b.block.endAt;
});
return items;
}
QString ScheduleService::lastError() const
{
return m_lastError;
}
void ScheduleService::notifyDataChanged()
{
Q_EMIT dataChanged();
}
+70
View File
@@ -0,0 +1,70 @@
#pragma once
#include <QDate>
#include <QObject>
#include <QString>
#include <QVector>
#include "core/ProposedDiff.h"
#include "core/ScheduleItem.h"
class SqliteStore;
/*
* 类名: ScheduleService
* 功能: 日程 CRUD 与查询的应用服务;所有 UI 变更都经此进入存储层
* 线程安全: 否;主线程使用
*/
class ScheduleService : public QObject
{
Q_OBJECT
public:
ScheduleService(SqliteStore& store, QString deviceId, QObject* parent = nullptr);
bool createBlock(const QString& title,
const QDateTime& start,
const QDateTime& end,
QString* error = nullptr);
bool updateBlock(const QString& blockId,
const QString& title,
const QDateTime& start,
const QDateTime& end,
QString* error = nullptr);
bool moveBlock(const QString& blockId,
const QDateTime& start,
const QDateTime& end,
QString* error = nullptr);
bool setBlockStatus(const QString& blockId, const QString& status, QString* error = nullptr);
bool postponeBlock(const QString& blockId, int minutes, QString* error = nullptr);
bool deleteBlock(const QString& blockId, QString* error = nullptr);
// 将 ProposedDiff 中用户勾选的 creates/updates/deletes 事务性写入数据库。
bool applyProposedDiff(const ProposedDiff& diff,
const QStringList& acceptedTempIds,
QString* error = nullptr);
// 兼容仅包含 creates 的旧调用。
bool applyProposedCreates(const ProposedDiff& diff,
const QStringList& acceptedTempIds,
QString* error = nullptr);
QVector<ScheduleItem> itemsForDay(const QDate& date) const;
// 返回 [from, to] 闭区间内的所有日程,按开始时间升序。
QVector<ScheduleItem> itemsForRange(const QDate& from, const QDate& to) const;
QVector<ScheduleItem> overdueItems(const QDateTime& now = QDateTime::currentDateTime()) const;
QString lastError() const;
// 供同步层在外部写入后通知 UI 刷新。
void notifyDataChanged();
signals:
void dataChanged();
private:
bool validateRange(const QDateTime& start, const QDateTime& end, QString* error);
bool touchTask(Task& task) const;
bool touchBlock(TimeBlock& block) const;
QString newId() const;
SqliteStore& m_store;
QString m_deviceId;
QString m_lastError;
};
+194
View File
@@ -0,0 +1,194 @@
#include "Migrations.h"
namespace Migrations
{
QVector<Migration> all()
{
QVector<Migration> migrations;
Migration v1;
v1.version = 1;
v1.name = QStringLiteral("initial_schema");
v1.statements = {
QStringLiteral(
"CREATE TABLE IF NOT EXISTS 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"
")"),
QStringLiteral(
"CREATE TABLE IF NOT EXISTS 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"
")"),
QStringLiteral(
"CREATE TABLE IF NOT EXISTS recurrence ("
" id TEXT PRIMARY KEY,"
" task_id TEXT NOT NULL REFERENCES task(id) ON DELETE CASCADE,"
" rrule TEXT NOT NULL,"
" until TEXT"
")"),
QStringLiteral(
"CREATE TABLE IF NOT EXISTS energy_profile ("
" id TEXT PRIMARY KEY,"
" weekday INTEGER NOT NULL,"
" hour_slot INTEGER NOT NULL,"
" level INTEGER NOT NULL"
")"),
QStringLiteral(
"CREATE TABLE IF NOT EXISTS proposed_diff ("
" id TEXT PRIMARY KEY,"
" created_at TEXT NOT NULL,"
" payload TEXT NOT NULL,"
" explanation TEXT,"
" state TEXT DEFAULT 'pending',"
" resolved_at TEXT"
")"),
QStringLiteral(
"CREATE TABLE IF NOT EXISTS sync_state ("
" device_id TEXT PRIMARY KEY,"
" last_seq INTEGER DEFAULT 0"
")"),
QStringLiteral("CREATE INDEX IF NOT EXISTS idx_timeblock_start ON timeblock(start_at)"),
QStringLiteral("CREATE INDEX IF NOT EXISTS idx_timeblock_task ON timeblock(task_id)"),
QStringLiteral("CREATE INDEX IF NOT EXISTS idx_timeblock_status_end ON timeblock(status, end_at)"),
QStringLiteral("CREATE INDEX IF NOT EXISTS idx_task_status ON task(status)"),
QStringLiteral("CREATE INDEX IF NOT EXISTS idx_proposed_diff_state ON proposed_diff(state)"),
};
migrations.append(v1);
Migration v2;
v2.version = 2;
v2.name = QStringLiteral("sync_outbox");
const QString taskJson = QStringLiteral(
"json_object('id',%1.id,'title',%1.title,'description',%1.description,'source',%1.source,"
"'source_ref',%1.source_ref,'estimated_min',%1.estimated_min,'energy_req',%1.energy_req,"
"'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 blockJson = QStringLiteral(
"json_object('id',%1.id,'task_id',%1.task_id,'start_at',%1.start_at,'end_at',%1.end_at,"
"'granularity',%1.granularity,'splittable',%1.splittable,'breakable',%1.breakable,"
"'status',%1.status,'done_at',%1.done_at,'created_at',%1.created_at,"
"'updated_at',%1.updated_at,'version',%1.version,'device_id',%1.device_id)");
v2.statements = {
QStringLiteral(
"CREATE TABLE IF NOT EXISTS sync_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"
")"),
QStringLiteral(
"CREATE INDEX IF NOT EXISTS idx_sync_outbox_entity ON sync_outbox(entity_type, entity_id)"),
QStringLiteral(
"CREATE TABLE IF NOT EXISTS sync_remote_apply ("
" id INTEGER PRIMARY KEY CHECK (id = 1)"
")"),
// 升级前已有的数据先作为初始 upsert 入队,避免首次启用同步时漏推。
QStringLiteral("INSERT INTO sync_outbox(entity_type, entity_id, op, payload, created_at) "
"SELECT 'task', id, 'upsert', %1, updated_at FROM task")
.arg(taskJson.arg("task")),
QStringLiteral("INSERT INTO sync_outbox(entity_type, entity_id, op, payload, created_at) "
"SELECT 'timeblock', id, 'upsert', %1, updated_at FROM timeblock")
.arg(blockJson.arg("timeblock")),
QStringLiteral(
"CREATE TRIGGER IF NOT EXISTS trg_task_outbox_insert AFTER INSERT ON task "
"WHEN NOT EXISTS (SELECT 1 FROM sync_remote_apply) BEGIN "
" INSERT INTO sync_outbox(entity_type, entity_id, op, payload, created_at) "
" VALUES('task', NEW.id, 'upsert', %1, NEW.updated_at); END")
.arg(taskJson.arg("NEW")),
QStringLiteral(
"CREATE TRIGGER IF NOT EXISTS trg_task_outbox_update AFTER UPDATE ON task "
"WHEN NOT EXISTS (SELECT 1 FROM sync_remote_apply) BEGIN "
" INSERT INTO sync_outbox(entity_type, entity_id, op, payload, created_at) "
" VALUES('task', NEW.id, 'upsert', %1, NEW.updated_at); END")
.arg(taskJson.arg("NEW")),
QStringLiteral(
"CREATE TRIGGER IF NOT EXISTS trg_task_outbox_delete AFTER DELETE ON task "
"WHEN NOT EXISTS (SELECT 1 FROM sync_remote_apply) BEGIN "
" INSERT INTO sync_outbox(entity_type, entity_id, op, payload, created_at) "
" VALUES('task', OLD.id, 'delete', %1, OLD.updated_at); END")
.arg(taskJson.arg("OLD")),
QStringLiteral(
"CREATE TRIGGER IF NOT EXISTS trg_timeblock_outbox_insert AFTER INSERT ON timeblock "
"WHEN NOT EXISTS (SELECT 1 FROM sync_remote_apply) BEGIN "
" INSERT INTO sync_outbox(entity_type, entity_id, op, payload, created_at) "
" VALUES('timeblock', NEW.id, 'upsert', %1, NEW.updated_at); END")
.arg(blockJson.arg("NEW")),
QStringLiteral(
"CREATE TRIGGER IF NOT EXISTS trg_timeblock_outbox_update AFTER UPDATE ON timeblock "
"WHEN NOT EXISTS (SELECT 1 FROM sync_remote_apply) BEGIN "
" INSERT INTO sync_outbox(entity_type, entity_id, op, payload, created_at) "
" VALUES('timeblock', NEW.id, 'upsert', %1, NEW.updated_at); END")
.arg(blockJson.arg("NEW")),
QStringLiteral(
"CREATE TRIGGER IF NOT EXISTS trg_timeblock_outbox_delete AFTER DELETE ON timeblock "
"WHEN NOT EXISTS (SELECT 1 FROM sync_remote_apply) BEGIN "
" INSERT INTO sync_outbox(entity_type, entity_id, op, payload, created_at) "
" VALUES('timeblock', OLD.id, 'delete', %1, OLD.updated_at); END")
.arg(blockJson.arg("OLD")),
};
migrations.append(v2);
Migration v3;
v3.version = 3;
v3.name = QStringLiteral("sync_delete_timestamp");
const QString nowExpression = QStringLiteral("strftime('%Y-%m-%dT%H:%M:%fZ','now')");
const QString taskDeletePayload = QStringLiteral("json_set(%1, '$.updated_at', %2)")
.arg(taskJson.arg("OLD"), nowExpression);
const QString blockDeletePayload = QStringLiteral("json_set(%1, '$.updated_at', %2)")
.arg(blockJson.arg("OLD"), nowExpression);
v3.statements = {
QStringLiteral("DROP TRIGGER IF EXISTS trg_task_outbox_delete"),
QStringLiteral("DROP TRIGGER IF EXISTS trg_timeblock_outbox_delete"),
QStringLiteral(
"CREATE TRIGGER trg_task_outbox_delete AFTER DELETE ON task "
"WHEN NOT EXISTS (SELECT 1 FROM sync_remote_apply) BEGIN "
" INSERT INTO sync_outbox(entity_type, entity_id, op, payload, created_at) "
" VALUES('task', OLD.id, 'delete', %1, %2); END")
.arg(taskDeletePayload, nowExpression),
QStringLiteral(
"CREATE TRIGGER trg_timeblock_outbox_delete AFTER DELETE ON timeblock "
"WHEN NOT EXISTS (SELECT 1 FROM sync_remote_apply) BEGIN "
" INSERT INTO sync_outbox(entity_type, entity_id, op, payload, created_at) "
" VALUES('timeblock', OLD.id, 'delete', %1, %2); END")
.arg(blockDeletePayload, nowExpression),
};
migrations.append(v3);
return migrations;
}
int latestVersion()
{
const auto migrations = all();
return migrations.isEmpty() ? 0 : migrations.last().version;
}
} // namespace Migrations
+19
View File
@@ -0,0 +1,19 @@
#pragma once
#include <QStringList>
#include <QVector>
namespace Migrations
{
struct Migration
{
int version = 0;
QString name;
QStringList statements;
};
QVector<Migration> all();
int latestVersion();
} // namespace Migrations
File diff suppressed because it is too large Load Diff
+82
View File
@@ -0,0 +1,82 @@
#pragma once
#include <QSqlDatabase>
#include <QString>
#include <QVector>
#include <atomic>
#include <optional>
#include "core/ProposedDiff.h"
#include "core/SyncTypes.h"
#include "core/ScheduleItem.h"
/*
* 类名: SqliteStore
* 功能: SQLite 持久化与迁移;只暴露领域对象,不向上层泄漏 SQL 细节
* 线程安全: 否;一个实例只允许在其创建线程使用(后续如需跨线程将按线程复用连接)
*/
class SqliteStore
{
public:
explicit SqliteStore(QString databasePath);
~SqliteStore();
SqliteStore(const SqliteStore&) = delete;
SqliteStore& operator=(const SqliteStore&) = delete;
bool open(QString* error = nullptr);
void close();
bool isOpen() const;
QString databasePath() const;
QString lastError() const;
int schemaVersion() const;
bool beginTransaction();
bool commit();
void rollback();
bool insertTask(const Task& task);
bool updateTask(const Task& task);
std::optional<Task> taskById(const QString& id);
bool deleteTask(const QString& id);
bool hasBlocksForTask(const QString& taskId);
bool insertTimeBlock(const TimeBlock& block);
bool updateTimeBlock(const TimeBlock& block);
std::optional<TimeBlock> timeBlockById(const QString& id);
bool deleteTimeBlock(const QString& id);
bool insertProposedDiff(const ProposedDiff& diff);
std::optional<ProposedDiff> proposedDiffById(const QString& id);
bool updateProposedDiffState(const QString& id, const QString& state, const QString& resolvedAt);
// 返回与 [fromUtc, toUtc) 相交的所有块,按开始时间升序。
QVector<ScheduleItem> blocksInRange(const QDateTime& fromUtc, const QDateTime& toUtc) const;
// 已结束但仍未完成、且结束时间在最近 windowDays 内的块。
QVector<ScheduleItem> overdueBefore(const QDateTime& nowUtc, int windowDays = 30) const;
QVector<SyncOutboxItem> outboxBatch(int limit, QString* error = nullptr) const;
int outboxCount(QString* error = nullptr) const;
bool clearOutboxThrough(qint64 id, QString* error = nullptr);
bool setRemoteApplySuppressed(bool enabled, QString* error = nullptr);
bool applyRemoteChange(const RemoteChange& change, QString* error = nullptr);
qint64 syncCursor(const QString& deviceId, QString* error = nullptr) const;
bool setSyncCursor(const QString& deviceId, qint64 seq, QString* error = nullptr);
private:
bool openDatabase(QString* error);
bool configureConnection(QString* error);
bool migrate(QString* error);
bool execScriptStatement(const QString& sql);
bool setError(const QString& message) const;
bool isOpenInternal() const;
static QString makeConnectionName();
QString m_databasePath;
QString m_connectionName;
QSqlDatabase m_database;
int m_schemaVersion = 0;
mutable QString m_lastError;
};
+651
View File
@@ -0,0 +1,651 @@
#include "SyncService.h"
#include <QDateTime>
#include <QHostInfo>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QTimer>
#include <QUrlQuery>
#include <QWebSocket>
#include <algorithm>
#include "core/DateTimeUtils.h"
#include "core/SyncTypes.h"
#include "services/ScheduleService.h"
#include "storage/SqliteStore.h"
#include "utils/AppSettings.h"
namespace
{
constexpr int kCycleIntervalMs = 15000;
constexpr int kBatchSize = 100;
constexpr int kInitialRetryMs = 5000;
constexpr int kMaxRetryMs = 60000;
QString safeString(const QJsonObject& object, const char* key)
{
const QJsonValue value = object.value(QLatin1String(key));
return value.isString() ? value.toString() : QString();
}
qint64 safeInt(const QJsonObject& object, const char* key)
{
const QJsonValue value = object.value(QLatin1String(key));
return value.isDouble() ? static_cast<qint64>(value.toDouble()) : 0;
}
} // namespace
SyncService::SyncService(ScheduleService& scheduleService,
SqliteStore& store,
AppSettings& settings,
QObject* parent)
: QObject(parent)
, m_scheduleService(scheduleService)
, m_store(store)
, m_settings(settings)
{
m_network = new QNetworkAccessManager(this);
m_cycleTimer = new QTimer(this);
m_cycleTimer->setInterval(kCycleIntervalMs);
connect(m_cycleTimer, &QTimer::timeout, this, &SyncService::beginCycle);
m_retryTimer = new QTimer(this);
m_retryTimer->setSingleShot(true);
connect(m_retryTimer, &QTimer::timeout, this, &SyncService::beginCycle);
m_debounceTimer = new QTimer(this);
m_debounceTimer->setSingleShot(true);
connect(m_debounceTimer, &QTimer::timeout, this, &SyncService::beginCycle);
m_wsReconnectTimer = new QTimer(this);
m_wsReconnectTimer->setSingleShot(true);
m_wsReconnectTimer->setInterval(5000);
connect(m_wsReconnectTimer, &QTimer::timeout, this, &SyncService::connectWebSocket);
connect(&m_scheduleService, &ScheduleService::dataChanged, this, [this]() {
if (m_running && !m_applyingRemote)
{
m_debounceTimer->start(500);
}
});
}
SyncService::~SyncService()
{
stopInternal();
}
QString SyncService::statusText() const
{
return m_status;
}
bool SyncService::isEnabled() const
{
return m_config.enabled;
}
void SyncService::start()
{
stopInternal();
++m_generation;
m_config = m_settings.syncConfig();
m_deviceId = m_settings.deviceId();
QString error;
if (!m_config.enabled)
{
setStatus(QStringLiteral("同步未启用"));
return;
}
if (!validateConfiguration(&error))
{
setStatus(error);
return;
}
m_running = true;
m_retryDelayMs = kInitialRetryMs;
m_retryTimer->stop();
if (m_config.token.isEmpty())
{
registerDevice();
}
else
{
beginRunningSession();
}
}
void SyncService::stop()
{
stopInternal();
setStatus(QStringLiteral("同步已停止"));
}
void SyncService::reloadConfig()
{
stopInternal();
start();
}
void SyncService::stopInternal()
{
++m_generation;
m_running = false;
m_busy = false;
m_registering = false;
m_wsConnected = false;
if (m_cycleTimer)
{
m_cycleTimer->stop();
}
if (m_retryTimer)
{
m_retryTimer->stop();
}
if (m_debounceTimer)
{
m_debounceTimer->stop();
}
if (m_wsReconnectTimer)
{
m_wsReconnectTimer->stop();
}
if (m_webSocket)
{
m_webSocket->close();
}
}
void SyncService::setStatus(const QString& status)
{
if (m_status == status)
{
return;
}
m_status = status;
Q_EMIT statusChanged(m_status);
}
bool SyncService::validateConfiguration(QString* error) const
{
if (m_config.serverUrl.trimmed().isEmpty())
{
if (error)
{
*error = QStringLiteral("未配置同步服务地址");
}
return false;
}
const QUrl url(m_config.serverUrl);
if (!url.isValid() || (url.scheme() != QStringLiteral("http") && url.scheme() != QStringLiteral("https")))
{
if (error)
{
*error = QStringLiteral("同步服务地址无效");
}
return false;
}
return true;
}
QUrl SyncService::apiUrl(const QString& endpoint) const
{
QUrl base(m_config.serverUrl);
QString path = base.path();
while (path.endsWith(QLatin1Char('/')))
{
path.chop(1);
}
QString suffix = endpoint;
if (!suffix.startsWith(QLatin1Char('/')))
{
suffix.prepend(QLatin1Char('/'));
}
base.setPath(path + suffix);
return base;
}
QUrl SyncService::streamUrl() const
{
QUrl url = apiUrl(QStringLiteral("/v1/stream"));
url.setScheme(url.scheme() == QStringLiteral("https") ? QStringLiteral("wss") : QStringLiteral("ws"));
QUrlQuery query;
query.addQueryItem(QStringLiteral("token"), m_config.token);
url.setQuery(query);
return url;
}
QNetworkRequest SyncService::makeRequest(const QUrl& url, bool withAuth) const
{
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader, QStringLiteral("application/json"));
request.setRawHeader("Accept", "application/json");
request.setTransferTimeout(30000);
request.setAttribute(QNetworkRequest::RedirectPolicyAttribute,
QNetworkRequest::NoLessSafeRedirectPolicy);
if (withAuth && !m_config.token.isEmpty())
{
request.setRawHeader("Authorization", QByteArray("Bearer ") + m_config.token.toUtf8());
}
return request;
}
void SyncService::beginCycle()
{
if (!m_running || m_busy || m_registering)
{
return;
}
if (m_config.token.isEmpty())
{
registerDevice();
return;
}
if (m_retryTimer->isActive())
{
return;
}
m_busy = true;
QString error;
const int count = m_store.outboxCount(&error);
if (!error.isEmpty())
{
failOperation(error);
return;
}
if (count > 0)
{
pushChanges();
}
else
{
pullChanges();
}
}
void SyncService::registerDevice()
{
if (!m_running || m_registering)
{
return;
}
m_registering = true;
m_busy = true;
setStatus(QStringLiteral("正在注册同步设备…"));
QJsonObject body;
body.insert(QStringLiteral("device_id"), m_deviceId);
QString name = QHostInfo::localHostName();
if (name.isEmpty())
{
name = QStringLiteral("Schedule PC");
}
body.insert(QStringLiteral("name"), name);
const quint64 generation = m_generation;
QNetworkReply* reply = m_network->post(makeRequest(apiUrl(QStringLiteral("/v1/devices/register")), false),
QJsonDocument(body).toJson(QJsonDocument::Compact));
connect(reply, &QNetworkReply::finished, this, [this, reply, generation]() {
m_registering = false;
m_busy = false;
const QByteArray data = reply->readAll();
const int status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
const QNetworkReply::NetworkError networkError = reply->error();
const QString networkMessage = reply->errorString();
reply->deleteLater();
if (generation != m_generation || !m_running)
{
return;
}
if (networkError != QNetworkReply::NoError || status >= 400)
{
failOperation(QStringLiteral("设备注册失败:%1").arg(networkMessage));
return;
}
const QJsonObject object = QJsonDocument::fromJson(data).object();
const QString token = object.value(QStringLiteral("token")).toString();
if (token.isEmpty())
{
failOperation(QStringLiteral("设备注册响应缺少 token"));
return;
}
m_config = m_settings.syncConfig();
m_config.token = token;
m_settings.setSyncConfig(m_config);
beginRunningSession();
});
}
void SyncService::beginRunningSession()
{
if (!m_running)
{
return;
}
QString error;
m_cursor = m_store.syncCursor(m_deviceId, &error);
if (!error.isEmpty())
{
failOperation(error);
return;
}
m_retryDelayMs = kInitialRetryMs;
m_retryTimer->stop();
m_cycleTimer->start();
setStatus(QStringLiteral("同步中…"));
connectWebSocket();
scheduleCycleSoon(0);
}
void SyncService::pushChanges()
{
QString error;
const QVector<SyncOutboxItem> items = m_store.outboxBatch(kBatchSize, &error);
if (!error.isEmpty())
{
failOperation(error);
return;
}
if (items.isEmpty())
{
pullChanges();
return;
}
QJsonArray changes;
qint64 maxOutboxId = 0;
const QDateTime now = QDateTime::currentDateTime();
for (const SyncOutboxItem& item : items)
{
maxOutboxId = std::max(maxOutboxId, item.id);
QString updatedAt = item.payload.value(QStringLiteral("updated_at")).toString();
if (updatedAt.isEmpty())
{
updatedAt = DateTimeUtils::toDb(now);
}
QJsonObject change;
change.insert(QStringLiteral("entity_type"), item.entityType);
change.insert(QStringLiteral("entity_id"), item.entityId);
change.insert(QStringLiteral("op"), item.op);
change.insert(QStringLiteral("version"),
item.payload.value(QStringLiteral("version")).toVariant().toLongLong());
change.insert(QStringLiteral("updated_at"), updatedAt);
if (!item.payload.isEmpty())
{
change.insert(QStringLiteral("payload"), item.payload);
}
changes.append(change);
}
QJsonObject body;
body.insert(QStringLiteral("changes"), changes);
const quint64 generation = m_generation;
QNetworkReply* reply = m_network->post(makeRequest(apiUrl(QStringLiteral("/v1/changes/push")), true),
QJsonDocument(body).toJson(QJsonDocument::Compact));
connect(reply, &QNetworkReply::finished, this, [this, reply, generation, maxOutboxId, itemCount = items.size()]() {
const QByteArray data = reply->readAll();
const int status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
const QNetworkReply::NetworkError networkError = reply->error();
const QString networkMessage = reply->errorString();
reply->deleteLater();
if (generation != m_generation || !m_running)
{
m_busy = false;
return;
}
if (status == 401)
{
handleUnauthorized();
return;
}
if (networkError != QNetworkReply::NoError || status >= 400)
{
failOperation(QStringLiteral("推送失败:%1").arg(networkMessage));
return;
}
const QJsonObject object = QJsonDocument::fromJson(data).object();
const int accepted = object.value(QStringLiteral("accepted")).toInt();
if (accepted < itemCount)
{
failOperation(QStringLiteral("同步服务未接受全部变更"));
return;
}
QString error;
if (!m_store.clearOutboxThrough(maxOutboxId, &error))
{
failOperation(error);
return;
}
m_retryDelayMs = kInitialRetryMs;
m_retryTimer->stop();
m_busy = false;
beginCycle();
});
}
void SyncService::pullChanges()
{
QUrl url = apiUrl(QStringLiteral("/v1/changes/pull"));
QUrlQuery query;
query.addQueryItem(QStringLiteral("since_seq"), QString::number(m_cursor));
query.addQueryItem(QStringLiteral("limit"), QString::number(kBatchSize));
url.setQuery(query);
const quint64 generation = m_generation;
QNetworkReply* reply = m_network->get(makeRequest(url, true));
connect(reply, &QNetworkReply::finished, this, [this, reply, generation]() {
const QByteArray data = reply->readAll();
const int status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
const QNetworkReply::NetworkError networkError = reply->error();
const QString networkMessage = reply->errorString();
reply->deleteLater();
if (generation != m_generation || !m_running)
{
m_busy = false;
return;
}
if (status == 401)
{
handleUnauthorized();
return;
}
if (networkError != QNetworkReply::NoError || status >= 400)
{
failOperation(QStringLiteral("拉取失败:%1").arg(networkMessage));
return;
}
const QJsonObject object = QJsonDocument::fromJson(data).object();
const QJsonArray changes = object.value(QStringLiteral("changes")).toArray();
const bool hasMore = object.value(QStringLiteral("has_more")).toBool();
const qint64 latestSeq = object.value(QStringLiteral("latest_seq")).toVariant().toLongLong();
if (changes.isEmpty())
{
m_busy = false;
if (latestSeq > m_cursor)
{
scheduleCycleSoon(0);
}
else
{
m_retryDelayMs = kInitialRetryMs;
m_retryTimer->stop();
setStatus(QStringLiteral("已同步"));
}
return;
}
if (!m_store.beginTransaction())
{
failOperation(m_store.lastError());
return;
}
if (!m_store.setRemoteApplySuppressed(true))
{
m_store.rollback();
failOperation(m_store.lastError());
return;
}
qint64 lastSeq = m_cursor;
bool appliedRemote = false;
for (const QJsonValue& value : changes)
{
const QJsonObject object = value.toObject();
const qint64 seq = object.value(QStringLiteral("seq")).toVariant().toLongLong();
lastSeq = std::max(lastSeq, seq);
const QString deviceId = safeString(object, "device_id");
if (deviceId == m_deviceId)
{
continue;
}
RemoteChange change;
change.seq = seq;
change.deviceId = deviceId;
change.entityType = safeString(object, "entity_type");
change.entityId = safeString(object, "entity_id");
change.op = safeString(object, "op");
change.version = safeInt(object, "version");
change.updatedAt = safeString(object, "updated_at");
change.payload = object.value(QStringLiteral("payload")).toObject();
if (!m_store.applyRemoteChange(change, nullptr))
{
m_store.rollback();
failOperation(m_store.lastError());
return;
}
appliedRemote = true;
}
if (!m_store.setRemoteApplySuppressed(false))
{
m_store.rollback();
failOperation(m_store.lastError());
return;
}
if (!m_store.setSyncCursor(m_deviceId, lastSeq, nullptr))
{
m_store.rollback();
failOperation(m_store.lastError());
return;
}
if (!m_store.commit())
{
m_store.rollback();
failOperation(m_store.lastError());
return;
}
m_cursor = lastSeq;
m_busy = false;
m_retryDelayMs = kInitialRetryMs;
m_retryTimer->stop();
if (appliedRemote)
{
m_applyingRemote = true;
m_scheduleService.notifyDataChanged();
m_applyingRemote = false;
}
if (hasMore || latestSeq > lastSeq)
{
scheduleCycleSoon(0);
}
else
{
setStatus(QStringLiteral("已同步"));
}
});
}
void SyncService::connectWebSocket()
{
if (!m_running || m_config.token.isEmpty())
{
return;
}
if (!m_webSocket)
{
m_webSocket = new QWebSocket(QString(), QWebSocketProtocol::VersionLatest, this);
connect(m_webSocket, &QWebSocket::connected, this, [this]() {
m_wsConnected = true;
m_wsReconnectTimer->stop();
setStatus(QStringLiteral("已连接"));
scheduleCycleSoon(0);
});
connect(m_webSocket, &QWebSocket::textMessageReceived, this, [this](const QString& message) {
const QJsonObject object = QJsonDocument::fromJson(message.toUtf8()).object();
const QString type = object.value(QStringLiteral("type")).toString();
if (type == QStringLiteral("ready") || type == QStringLiteral("changes"))
{
scheduleCycleSoon(100);
}
});
connect(m_webSocket, &QWebSocket::disconnected, this, [this]() {
m_wsConnected = false;
if (m_running)
{
setStatus(QStringLiteral("轮询同步(WebSocket 断开)"));
m_wsReconnectTimer->start();
}
});
connect(m_webSocket, &QWebSocket::errorOccurred, this, [this](QAbstractSocket::SocketError) {
if (m_running)
{
m_wsConnected = false;
m_wsReconnectTimer->start();
}
});
}
m_webSocket->open(streamUrl());
}
void SyncService::scheduleRetry()
{
if (!m_running)
{
return;
}
setStatus(QStringLiteral("离线,等待重试"));
m_retryTimer->start(m_retryDelayMs);
m_retryDelayMs = std::min(kMaxRetryMs, m_retryDelayMs * 2);
}
void SyncService::scheduleCycleSoon(int delayMs)
{
if (!m_running)
{
return;
}
m_debounceTimer->start(delayMs);
}
void SyncService::failOperation(const QString& message)
{
m_busy = false;
m_registering = false;
setStatus(QStringLiteral("同步失败:%1").arg(message));
Q_EMIT syncError(message);
scheduleRetry();
}
void SyncService::handleUnauthorized()
{
m_busy = false;
m_wsConnected = false;
if (m_webSocket)
{
m_webSocket->close();
}
m_config = m_settings.syncConfig();
m_config.token.clear();
m_settings.setSyncConfig(m_config);
setStatus(QStringLiteral("同步认证失效,正在重新注册…"));
registerDevice();
}
+85
View File
@@ -0,0 +1,85 @@
#pragma once
#include <QObject>
#include <QString>
#include <QUrl>
#include "utils/AppSettings.h"
class AppSettings;
class QNetworkAccessManager;
class QNetworkReply;
class QNetworkRequest;
class QTimer;
class QWebSocket;
class ScheduleService;
class SqliteStore;
/*
* 类名: SyncService
* 功能: 自部署同步客户端:设备注册、发件箱推送、增量拉取、LWW 应用、WebSocket 通知
* 线程安全: 否;主线程使用,网络回调异步
*/
class SyncService : public QObject
{
Q_OBJECT
public:
SyncService(ScheduleService& scheduleService,
SqliteStore& store,
AppSettings& settings,
QObject* parent = nullptr);
~SyncService() override;
void start();
void stop();
void reloadConfig();
QString statusText() const;
bool isEnabled() const;
signals:
void statusChanged(const QString& status);
void syncError(const QString& message);
private:
void beginCycle();
void pushChanges();
void pullChanges();
void registerDevice();
void beginRunningSession();
void stopInternal();
void connectWebSocket();
void scheduleRetry();
void scheduleCycleSoon(int delayMs);
void setStatus(const QString& status);
void failOperation(const QString& message);
void handleUnauthorized();
QUrl apiUrl(const QString& endpoint) const;
QUrl streamUrl() const;
bool validateConfiguration(QString* error) const;
QNetworkRequest makeRequest(const QUrl& url, bool withAuth) const;
ScheduleService& m_scheduleService;
SqliteStore& m_store;
AppSettings& m_settings;
SyncConfig m_config;
QString m_deviceId;
QString m_status;
QNetworkAccessManager* m_network = nullptr;
QWebSocket* m_webSocket = nullptr;
QTimer* m_cycleTimer = nullptr;
QTimer* m_retryTimer = nullptr;
QTimer* m_debounceTimer = nullptr;
QTimer* m_wsReconnectTimer = nullptr;
qint64 m_cursor = 0;
int m_retryDelayMs = 5000;
bool m_running = false;
bool m_busy = false;
bool m_registering = false;
bool m_wsConnected = false;
bool m_applyingRemote = false;
quint64 m_generation = 0;
};
+61
View File
@@ -0,0 +1,61 @@
#include "AppIcon.h"
#include <QLinearGradient>
#include <QPainter>
#include <QPainterPath>
#include <QPixmap>
namespace
{
QPixmap drawIcon(int size)
{
QPixmap pixmap(size, size);
pixmap.fill(Qt::transparent);
QPainter painter(&pixmap);
painter.setRenderHint(QPainter::Antialiasing);
const qreal s = size;
QPainterPath background;
background.addRoundedRect(QRectF(s * 0.04, s * 0.04, s * 0.92, s * 0.92), s * 0.22, s * 0.22);
QLinearGradient gradient(0, 0, s, s);
gradient.setColorAt(0.0, QColor(0x4C, 0x8D, 0xFF));
gradient.setColorAt(1.0, QColor(0x22, 0x58, 0xC4));
painter.fillPath(background, gradient);
QPen pen(QColor(255, 255, 255, 235));
pen.setWidthF(s * 0.055);
pen.setCapStyle(Qt::RoundCap);
pen.setJoinStyle(Qt::RoundJoin);
painter.setPen(pen);
painter.setBrush(Qt::NoBrush);
const QRectF calendar(s * 0.22, s * 0.28, s * 0.56, s * 0.48);
painter.drawRoundedRect(calendar, s * 0.08, s * 0.08);
painter.drawLine(QPointF(calendar.left(), s * 0.42), QPointF(calendar.right(), s * 0.42));
painter.drawLine(QPointF(s * 0.35, s * 0.21), QPointF(s * 0.35, s * 0.32));
painter.drawLine(QPointF(s * 0.65, s * 0.21), QPointF(s * 0.65, s * 0.32));
QPainterPath check;
check.moveTo(s * 0.37, s * 0.57);
check.lineTo(s * 0.46, s * 0.66);
check.lineTo(s * 0.64, s * 0.47);
pen.setColor(QColor(255, 255, 255, 255));
pen.setWidthF(s * 0.07);
painter.setPen(pen);
painter.drawPath(check);
painter.end();
return pixmap;
}
} // namespace
QIcon AppIcon::create()
{
QIcon icon;
for (const int size : {16, 24, 32, 48, 64, 128, 256})
{
icon.addPixmap(drawIcon(size));
}
return icon;
}
+8
View File
@@ -0,0 +1,8 @@
#pragma once
#include <QIcon>
namespace AppIcon
{
QIcon create();
}
+491
View File
@@ -0,0 +1,491 @@
#include "CompactWindow.h"
#include <QApplication>
#include <QCloseEvent>
#include <QCoreApplication>
#include <QDateTime>
#include <QDialog>
#include <QKeySequence>
#include <QHBoxLayout>
#include <QLabel>
#include <QPainter>
#include <QShortcut>
#include <QSplitter>
#include <QTimer>
#include <QVBoxLayout>
#include <algorithm>
#include "ElaMessageBar.h"
#include "ElaPushButton.h"
#include "ElaText.h"
#include "ElaToolButton.h"
#include "platform/SystemTray.h"
#include "core/DateTimeUtils.h"
#include "ai/AIService.h"
#include "services/NotificationService.h"
#include "services/ScheduleService.h"
#include "sync/SyncService.h"
#include "ui/MainWindow.h"
#include "ui/dialogs/BlockEditDialog.h"
#include "ui/dialogs/SettingsDialog.h"
#include "ui/panels/ChatPanel.h"
#include "ui/panels/TodayPanel.h"
#include "ui/theme/ThemeManager.h"
#include "ui/theme/WindowEffects.h"
#include "utils/AppSettings.h"
namespace
{
QString weekdayLabel(const QDate& date)
{
static const char* labels[] = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
return QString::fromUtf8(labels[date.dayOfWeek() % 7]);
}
} // namespace
CompactWindow::CompactWindow(ScheduleService& scheduleService,
NotificationService& notificationService,
AIService& aiService,
ThemeManager& themeManager,
AppSettings& settings,
SyncService* syncService,
QWidget* parent)
: ElaWindow(parent)
, m_scheduleService(scheduleService)
, m_notificationService(notificationService)
, m_aiService(aiService)
, m_themeManager(themeManager)
, m_settings(settings)
, m_syncService(syncService)
, m_today(QDate::currentDate())
{
setWindowTitle(QStringLiteral("AI 日程"));
setAppBarHeight(44);
setIsNavigationBarEnable(false);
setWindowButtonFlag(ElaAppBarType::RouteBackButtonHint, false);
setWindowButtonFlag(ElaAppBarType::RouteForwardButtonHint, false);
setWindowButtonFlag(ElaAppBarType::ThemeChangeButtonHint, false);
setWindowButtonFlag(ElaAppBarType::NavigationButtonHint, false);
setWindowButtonFlag(ElaAppBarType::MaximizeButtonHint, false);
setMinimumSize(400, 580);
resize(460, 720);
buildUi();
applyTheme(m_themeManager.tokens());
connectSignals();
restoreWindowState();
reloadToday();
setupTray();
m_refreshTimer = new QTimer(this);
m_refreshTimer->setInterval(60000);
connect(m_refreshTimer, &QTimer::timeout, this, &CompactWindow::reloadToday);
m_refreshTimer->start();
connect(qApp, &QCoreApplication::aboutToQuit, this, &CompactWindow::saveWindowState);
if (SystemTray::isAvailable())
{
QApplication::setQuitOnLastWindowClosed(false);
}
}
CompactWindow::~CompactWindow()
{
if (m_scheduleWindow)
{
m_scheduleWindow->disconnect(this);
delete m_scheduleWindow;
m_scheduleWindow = nullptr;
}
}
void CompactWindow::buildUi()
{
auto* root = new QWidget(this);
auto* rootLayout = new QVBoxLayout(root);
rootLayout->setContentsMargins(12, 6, 12, 12);
rootLayout->setSpacing(8);
auto* header = new QHBoxLayout();
header->setContentsMargins(2, 0, 2, 0);
header->setSpacing(8);
m_dateLabel = new ElaText(QStringLiteral("今天"), 15, root);
QFont dateFont = m_dateLabel->font();
dateFont.setWeight(QFont::DemiBold);
m_dateLabel->setFont(dateFont);
m_syncLabel = new QLabel(QStringLiteral("● 本地"), root);
m_syncLabel->setStyleSheet(QStringLiteral("background:transparent;color:%1;font-size:11px;")
.arg(m_tokens.textMuted.name()));
m_syncLabel->setToolTip(QStringLiteral("本地模式"));
m_openScheduleButton = new ElaPushButton(QStringLiteral("详细日程"), root);
m_openScheduleButton->setFixedSize(96, 32);
m_openScheduleButton->setToolTip(QStringLiteral("打开详细日程 (Ctrl+O)"));
m_settingsButton = new ElaToolButton(root);
m_settingsButton->setIsTransparent(true);
m_settingsButton->setElaIcon(ElaIconType::Gear);
m_settingsButton->setFixedSize(30, 30);
m_settingsButton->setToolTip(QStringLiteral("设置"));
header->addWidget(m_dateLabel);
header->addStretch(1);
if (m_syncService)
{
header->addWidget(m_syncLabel, 0, Qt::AlignVCenter);
}
header->addWidget(m_openScheduleButton);
header->addWidget(m_settingsButton);
rootLayout->addLayout(header);
m_splitter = new QSplitter(Qt::Vertical, root);
m_splitter->setChildrenCollapsible(false);
m_splitter->setHandleWidth(6);
m_chatPanel = new ChatPanel(m_aiService, m_splitter);
m_todayPanel = new TodayPanel(m_splitter);
m_splitter->addWidget(m_chatPanel);
m_splitter->addWidget(m_todayPanel);
m_splitter->setStretchFactor(0, 3);
m_splitter->setStretchFactor(1, 2);
m_splitter->setSizes({400, 260});
rootLayout->addWidget(m_splitter, 1);
addCentralWidget(root);
setStackSwitchMode(ElaWindowType::StackSwitchMode::None);
setCurrentStackIndex(1);
connect(m_openScheduleButton, &ElaPushButton::clicked, this, &CompactWindow::openSchedule);
connect(m_settingsButton, &ElaToolButton::clicked, this, &CompactWindow::openSettings);
if (m_syncService)
{
m_syncLabel->show();
connect(m_syncService, &SyncService::statusChanged, this, &CompactWindow::updateSyncStatus);
updateSyncStatus(m_syncService->statusText());
}
else
{
m_syncLabel->hide();
}
auto* openShortcut = new QShortcut(QKeySequence(QStringLiteral("Ctrl+O")), this);
connect(openShortcut, &QShortcut::activated, this, &CompactWindow::openSchedule);
auto* settingsShortcut = new QShortcut(QKeySequence(QStringLiteral("Ctrl+,")), this);
connect(settingsShortcut, &QShortcut::activated, this, &CompactWindow::openSettings);
}
void CompactWindow::setupTray()
{
m_tray = new SystemTray(this);
if (!SystemTray::isAvailable())
{
return;
}
m_tray->show();
m_tray->setOverdueCount(m_notificationService.overdueItems().size());
connect(m_tray, &SystemTray::showRequested, this, [this]() {
if (m_scheduleWindow && m_scheduleWindow->isVisible())
{
m_scheduleWindow->showAndRaise();
}
else
{
showAndRaise();
}
});
connect(m_tray, &SystemTray::newBlockRequested, this, [this]() {
openSchedule();
if (m_scheduleWindow)
{
m_scheduleWindow->openNewBlock();
}
});
connect(m_tray, &SystemTray::quitRequested, this, [this]() {
m_quitting = true;
QApplication::quit();
});
}
void CompactWindow::connectSignals()
{
connect(&m_scheduleService, &ScheduleService::dataChanged, this, &CompactWindow::reloadToday);
connect(m_todayPanel, &TodayPanel::editRequested, this, &CompactWindow::openEditDialog);
connect(m_todayPanel, &TodayPanel::statusChangeRequested, this, [this](const QString& id,
const QString& status) {
QString error;
if (!m_scheduleService.setBlockStatus(id, status, &error))
{
showError(QStringLiteral("更新状态失败"), error);
}
});
connect(m_todayPanel, &TodayPanel::postponeRequested, this, [this](const QString& id, int minutes) {
QString error;
if (!m_scheduleService.postponeBlock(id, minutes, &error))
{
showError(QStringLiteral("延后日程失败"), error);
}
});
connect(m_todayPanel, &TodayPanel::deleteRequested, this, [this](const QString& id) {
QString error;
if (!m_scheduleService.deleteBlock(id, &error))
{
showError(QStringLiteral("删除日程失败"), error);
}
});
connect(m_todayPanel, &TodayPanel::focusRequested, this, [this](const QString& id) {
openSchedule();
if (m_scheduleWindow)
{
m_scheduleWindow->focusBlock(QDate::currentDate(), id);
}
});
connect(&m_notificationService,
&NotificationService::overdueListChanged,
this,
[this](const QVector<ScheduleItem>& items) {
if (m_tray)
{
m_tray->setOverdueCount(items.size());
}
reloadToday();
});
connect(&m_notificationService, &NotificationService::overdueDetected, 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);
}
if (isVisible())
{
QApplication::alert(this, 0);
}
else if (m_scheduleWindow && m_scheduleWindow->isVisible())
{
QApplication::alert(m_scheduleWindow, 0);
}
});
connect(&m_themeManager, &ThemeManager::themeChanged, this, &CompactWindow::applyTheme);
connect(&m_themeManager, &ThemeManager::preferenceChanged, this, [this](ThemeManager::Preference) {
applyTheme(m_themeManager.tokens());
});
}
void CompactWindow::applyTheme(const ThemeTokens& tokens)
{
m_tokens = tokens;
if (m_chatPanel)
{
m_chatPanel->setTokens(tokens);
}
if (m_todayPanel)
{
m_todayPanel->setTokens(tokens);
}
if (m_syncLabel)
{
m_syncLabel->setStyleSheet(
QStringLiteral("background:transparent;color:%1;font-size:11px;").arg(tokens.textMuted.name()));
}
}
void CompactWindow::restoreWindowState()
{
const QByteArray geometry = m_settings.compactGeometry();
if (!geometry.isEmpty())
{
restoreGeometry(geometry);
}
else
{
moveToCenter();
}
}
void CompactWindow::saveWindowState()
{
m_settings.setCompactGeometry(saveGeometry());
}
void CompactWindow::reloadToday()
{
if (!m_todayPanel || !m_dateLabel)
{
return;
}
const QDate today = QDate::currentDate();
if (m_today != today)
{
m_today = today;
}
m_dateLabel->setText(QStringLiteral("今天 · %1月%2日 %3")
.arg(today.month())
.arg(today.day())
.arg(weekdayLabel(today)));
m_todayItems = m_scheduleService.itemsForDay(today);
m_todayPanel->setDate(today);
m_todayPanel->setItems(m_todayItems, QDateTime::currentDateTime());
}
void CompactWindow::openSchedule()
{
if (!m_scheduleWindow)
{
m_scheduleWindow = new MainWindow(m_scheduleService,
m_notificationService,
m_themeManager,
m_settings,
m_syncService);
connect(m_scheduleWindow, &MainWindow::closeRequested, this, &CompactWindow::showAndRaise);
}
hide();
m_scheduleWindow->showAndRaise();
}
void CompactWindow::openSettings()
{
SettingsDialog dialog(m_themeManager, m_settings, this);
if (m_syncService)
{
connect(&dialog, &SettingsDialog::syncSettingsChanged, m_syncService, &SyncService::reloadConfig);
}
dialog.moveToCenter();
dialog.exec();
}
void CompactWindow::updateSyncStatus(const QString& status)
{
if (!m_syncLabel)
{
return;
}
QString shortStatus = status;
if (status.contains(QStringLiteral("失败")) || status.contains(QStringLiteral("错误")) ||
status.contains(QStringLiteral("未配置")) || status.contains(QStringLiteral("无效")))
{
shortStatus = QStringLiteral("同步错误");
}
else if (status.contains(QStringLiteral("离线")) || status.contains(QStringLiteral("等待")))
{
shortStatus = QStringLiteral("离线");
}
else if (status.contains(QStringLiteral("注册")) || status.contains(QStringLiteral("同步中")) ||
status.contains(QStringLiteral("WebSocket")))
{
shortStatus = QStringLiteral("同步中");
}
else if (status.contains(QStringLiteral("已同步")) || status.contains(QStringLiteral("已连接")))
{
shortStatus = QStringLiteral("已同步");
}
else
{
shortStatus = QStringLiteral("本地");
}
m_syncLabel->setText(QStringLiteral("● ") + shortStatus);
m_syncLabel->setToolTip(status);
m_syncLabel->setStyleSheet(QStringLiteral("background:transparent;color:%1;font-size:11px;")
.arg(m_tokens.textMuted.name()));
}
void CompactWindow::openEditDialog(const QString& blockId)
{
const auto it = std::find_if(m_todayItems.cbegin(), m_todayItems.cend(), [&blockId](const ScheduleItem& item) {
return item.block.id == blockId;
});
if (it == m_todayItems.cend())
{
showError(QStringLiteral("编辑日程失败"), QStringLiteral("找不到该日程,请刷新后重试"));
return;
}
BlockEditDialog dialog(m_tokens, this);
dialog.setCreateMode(false);
dialog.setValues(it->task.title, it->block.startAt, it->block.endAt);
dialog.moveToCenter();
if (dialog.exec() != QDialog::Accepted)
{
return;
}
QString error;
if (!m_scheduleService.updateBlock(blockId,
dialog.titleValue(),
dialog.startValue(),
dialog.endValue(),
&error))
{
showError(QStringLiteral("保存日程失败"), error);
}
}
void CompactWindow::showError(const QString& title, const QString& message)
{
ElaMessageBar::error(ElaMessageBarType::TopRight,
title,
message.isEmpty() ? QStringLiteral("未知错误") : message,
4500,
this);
}
void CompactWindow::showAndRaise()
{
if (isMinimized())
{
showNormal();
}
else
{
show();
}
raise();
activateWindow();
reloadToday();
}
void CompactWindow::paintEvent(QPaintEvent* event)
{
ElaWindow::paintEvent(event);
if (!WindowEffects::isMicaActive())
{
return;
}
QPainter painter(this);
QColor tint = m_tokens.windowBackground;
tint.setAlpha(m_tokens.dark ? 92 : 84);
painter.fillRect(rect(), tint);
QColor bar = m_tokens.toolbarBackground;
bar.setAlpha(m_tokens.dark ? 178 : 168);
painter.fillRect(QRect(0, 0, width(), 44), bar);
}
void CompactWindow::closeEvent(QCloseEvent* event)
{
if (m_tray && m_tray->isVisible() && !m_quitting)
{
saveWindowState();
hide();
const bool hintShown = m_settings.trayHintShown();
if (!hintShown)
{
m_tray->showNotification(QStringLiteral("AI 日程"),
QStringLiteral("已最小化到系统托盘,可从托盘菜单退出。"));
m_settings.setTrayHintShown(true);
}
event->ignore();
return;
}
saveWindowState();
QMainWindow::closeEvent(event);
}
+92
View File
@@ -0,0 +1,92 @@
#pragma once
#include <QDate>
#include <QVector>
#include "ElaWindow.h"
#include "core/ScheduleItem.h"
#include "ui/theme/ThemeTokens.h"
class AIService;
class AppSettings;
class ChatPanel;
class ElaPushButton;
class ElaText;
class ElaToolButton;
class MainWindow;
class NotificationService;
class ScheduleService;
class SyncService;
class SystemTray;
class ThemeManager;
class TodayPanel;
class QCloseEvent;
class QLabel;
class QPaintEvent;
class QSplitter;
class QTimer;
/*
* 类名: CompactWindow
* 功能: 默认启动的紧凑无边框窗口;展示 AI 助手与今日任务,并可打开详细日程
* 线程安全: 否;UI 线程
*/
class CompactWindow : public ElaWindow
{
Q_OBJECT
public:
CompactWindow(ScheduleService& scheduleService,
NotificationService& notificationService,
AIService& aiService,
ThemeManager& themeManager,
AppSettings& settings,
SyncService* syncService = nullptr,
QWidget* parent = nullptr);
~CompactWindow() override;
void showAndRaise();
protected:
void closeEvent(QCloseEvent* event) override;
void paintEvent(QPaintEvent* event) override;
private:
void buildUi();
void setupTray();
void connectSignals();
void restoreWindowState();
void saveWindowState();
void applyTheme(const ThemeTokens& tokens);
void reloadToday();
void openSchedule();
void openSettings();
void openEditDialog(const QString& blockId);
void showError(const QString& title, const QString& message);
void updateSyncStatus(const QString& status);
ScheduleService& m_scheduleService;
NotificationService& m_notificationService;
AIService& m_aiService;
ThemeManager& m_themeManager;
AppSettings& m_settings;
SyncService* m_syncService = nullptr;
ThemeTokens m_tokens;
SystemTray* m_tray = nullptr;
MainWindow* m_scheduleWindow = nullptr;
QVector<ScheduleItem> m_todayItems;
QDate m_today;
ElaText* m_dateLabel = nullptr;
ElaPushButton* m_openScheduleButton = nullptr;
ElaToolButton* m_settingsButton = nullptr;
QLabel* m_syncLabel = nullptr;
QSplitter* m_splitter = nullptr;
ChatPanel* m_chatPanel = nullptr;
TodayPanel* m_todayPanel = nullptr;
QTimer* m_refreshTimer = nullptr;
bool m_quitting = false;
};
+946
View File
@@ -0,0 +1,946 @@
#include "MainWindow.h"
#include <QApplication>
#include <QCloseEvent>
#include <QComboBox>
#include <QCoreApplication>
#include <QDateTime>
#include <QDialog>
#include <QFrame>
#include <QHBoxLayout>
#include <QPainter>
#include <QKeySequence>
#include <QLabel>
#include <QShortcut>
#include <QShowEvent>
#include <QSignalBlocker>
#include <QSplitter>
#include <QStackedWidget>
#include <QTime>
#include <QTimer>
#include <QVBoxLayout>
#include <algorithm>
#include "ElaComboBox.h"
#include "ElaLineEdit.h"
#include "ElaMessageBar.h"
#include "ElaPivot.h"
#include "ElaPushButton.h"
#include "ElaText.h"
#include "ElaToolButton.h"
#include "core/DateTimeUtils.h"
#include "services/NotificationService.h"
#include "services/ScheduleService.h"
#include "sync/SyncService.h"
#include "ui/dialogs/BlockEditDialog.h"
#include "ui/dialogs/SettingsDialog.h"
#include "ui/panels/TodayPanel.h"
#include "ui/theme/ThemeManager.h"
#include "ui/theme/WindowEffects.h"
#include "ui/views/MonthView.h"
#include "ui/views/ScheduleGridView.h"
#include "ui/views/YearView.h"
#include "utils/AppSettings.h"
namespace
{
QString weekdayLabel(const QDate& date)
{
static const char* labels[] = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
return QString::fromUtf8(labels[date.dayOfWeek() % 7]);
}
} // namespace
MainWindow::MainWindow(ScheduleService& scheduleService,
NotificationService& notificationService,
ThemeManager& themeManager,
AppSettings& settings,
SyncService* syncService,
QWidget* parent)
: ElaWindow(parent)
, m_scheduleService(scheduleService)
, m_notificationService(notificationService)
, m_themeManager(themeManager)
, m_settings(settings)
, m_syncService(syncService)
, m_currentDate(QDate::currentDate())
{
setWindowTitle(QStringLiteral("详细日程"));
setAppBarHeight(44);
setIsNavigationBarEnable(false);
setWindowButtonFlag(ElaAppBarType::RouteBackButtonHint, false);
setWindowButtonFlag(ElaAppBarType::RouteForwardButtonHint, false);
setWindowButtonFlag(ElaAppBarType::ThemeChangeButtonHint, false);
setWindowButtonFlag(ElaAppBarType::NavigationButtonHint, false);
setMinimumSize(1080, 680);
resize(1280, 820);
buildUi();
applyTheme(m_themeManager.tokens());
connectSignals();
restoreWindowState();
setView(View::Day);
updateOverdueBanner(m_notificationService.overdueItems());
connect(qApp, &QCoreApplication::aboutToQuit, this, &MainWindow::saveWindowState);
}
MainWindow::~MainWindow() = default;
void MainWindow::buildUi()
{
auto* root = new QWidget(this);
auto* rootLayout = new QVBoxLayout(root);
rootLayout->setContentsMargins(10, 6, 10, 10);
rootLayout->setSpacing(8);
m_toolbar = new QFrame(root);
m_toolbar->setObjectName(QStringLiteral("Toolbar"));
auto* toolbarLayout = new QHBoxLayout(m_toolbar);
toolbarLayout->setContentsMargins(10, 6, 10, 6);
toolbarLayout->setSpacing(6);
m_compactButton = new ElaToolButton(m_toolbar);
m_compactButton->setIsTransparent(true);
m_compactButton->setElaIcon(ElaIconType::House);
m_compactButton->setFixedSize(30, 30);
m_compactButton->setToolTip(QStringLiteral("返回紧凑视图 (Ctrl+W)"));
m_todayButton = new ElaPushButton(QStringLiteral("今天"), m_toolbar);
m_todayButton->setFixedSize(58, 30);
m_todayButton->setToolTip(QStringLiteral("回到今天 (Ctrl+T)"));
m_prevButton = new ElaToolButton(m_toolbar);
m_prevButton->setIsTransparent(true);
m_prevButton->setElaIcon(ElaIconType::ArrowLeft);
m_prevButton->setFixedSize(30, 30);
m_prevButton->setToolTip(QStringLiteral("上一段 (Alt+←)"));
m_nextButton = new ElaToolButton(m_toolbar);
m_nextButton->setIsTransparent(true);
m_nextButton->setElaIcon(ElaIconType::ArrowRight);
m_nextButton->setFixedSize(30, 30);
m_nextButton->setToolTip(QStringLiteral("下一段 (Alt+→)"));
m_dateLabel = new ElaText(m_toolbar);
m_dateLabel->setTextPixelSize(15);
QFont dateFont = m_dateLabel->font();
dateFont.setWeight(QFont::DemiBold);
m_dateLabel->setFont(dateFont);
m_viewPivot = new ElaPivot(m_toolbar);
m_viewPivot->setTextPixelSize(14);
m_viewPivot->setPivotSpacing(18);
m_viewPivot->setFixedSize(174, 30);
m_viewPivot->appendPivot(QStringLiteral("日"));
m_viewPivot->appendPivot(QStringLiteral("月"));
m_viewPivot->appendPivot(QStringLiteral("年"));
m_viewPivot->setCurrentIndex(0);
m_viewPivot->setToolTip(QStringLiteral("切换日 / 月 / 年视图 (Ctrl+1/2/3)"));
m_newButton = new ElaPushButton(QStringLiteral("新建日程"), m_toolbar);
m_newButton->setFixedSize(96, 32);
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_snapCombo = new ElaComboBox(m_toolbar);
m_snapCombo->addItems({QStringLiteral("吸附 15 分"),
QStringLiteral("吸附 30 分"),
QStringLiteral("吸附 60 分")});
m_snapCombo->setFixedSize(100, 30);
m_snapCombo->setToolTip(QStringLiteral("时间网格吸附粒度"));
m_themeButton = new ElaToolButton(m_toolbar);
m_themeButton->setIsTransparent(true);
m_themeButton->setElaIcon(ElaIconType::CircleHalfStroke);
m_themeButton->setFixedSize(30, 30);
m_settingsButton = new ElaToolButton(m_toolbar);
m_settingsButton->setIsTransparent(true);
m_settingsButton->setElaIcon(ElaIconType::Gear);
m_settingsButton->setFixedSize(30, 30);
m_settingsButton->setToolTip(QStringLiteral("设置 (Ctrl+,)"));
m_syncLabel = new QLabel(QStringLiteral("● 本地"), m_toolbar);
m_syncLabel->setFixedHeight(24);
m_syncLabel->setToolTip(QStringLiteral("本地模式"));
toolbarLayout->addWidget(m_compactButton);
toolbarLayout->addWidget(m_todayButton);
toolbarLayout->addWidget(m_prevButton);
toolbarLayout->addWidget(m_nextButton);
toolbarLayout->addWidget(m_viewPivot);
toolbarLayout->addWidget(m_dateLabel);
toolbarLayout->addSpacing(6);
toolbarLayout->addWidget(m_newButton);
toolbarLayout->addStretch(1);
toolbarLayout->addWidget(m_searchEdit);
toolbarLayout->addWidget(m_snapCombo);
toolbarLayout->addWidget(m_themeButton);
toolbarLayout->addWidget(m_settingsButton);
toolbarLayout->addWidget(m_syncLabel);
rootLayout->addWidget(m_toolbar);
m_mainSplitter = new QSplitter(Qt::Horizontal, root);
m_mainSplitter->setChildrenCollapsible(false);
m_mainSplitter->setHandleWidth(6);
auto* calendarContainer = new QWidget(m_mainSplitter);
auto* calendarLayout = new QVBoxLayout(calendarContainer);
calendarLayout->setContentsMargins(0, 0, 0, 0);
calendarLayout->setSpacing(6);
m_overdueBanner = new QFrame(calendarContainer);
m_overdueBanner->setObjectName(QStringLiteral("OverdueBanner"));
auto* bannerLayout = new QHBoxLayout(m_overdueBanner);
bannerLayout->setContentsMargins(12, 6, 8, 6);
bannerLayout->setSpacing(10);
m_overdueLabel = new QLabel(m_overdueBanner);
auto* handleButton = new ElaPushButton(QStringLiteral("处理"), m_overdueBanner);
handleButton->setFixedSize(64, 26);
bannerLayout->addWidget(m_overdueLabel, 1);
bannerLayout->addWidget(handleButton, 0, Qt::AlignVCenter);
m_overdueBanner->setVisible(false);
m_viewStack = new QStackedWidget(calendarContainer);
m_grid = new ScheduleGridView(m_viewStack);
m_monthView = new MonthView(m_viewStack);
m_yearView = new YearView(m_viewStack);
m_viewStack->addWidget(m_grid);
m_viewStack->addWidget(m_monthView);
m_viewStack->addWidget(m_yearView);
m_hintLabel = new ElaText(QString(), 11, calendarContainer);
m_hintLabel->setTextStyle(ElaTextType::Caption);
m_hintLabel->setContentsMargins(4, 0, 0, 0);
calendarLayout->addWidget(m_overdueBanner);
calendarLayout->addWidget(m_viewStack, 1);
calendarLayout->addWidget(m_hintLabel);
m_rightDock = new QFrame(m_mainSplitter);
m_rightDock->setObjectName(QStringLiteral("RightDock"));
auto* rightLayout = new QVBoxLayout(m_rightDock);
rightLayout->setContentsMargins(6, 6, 6, 6);
rightLayout->setSpacing(0);
m_todayPanel = new TodayPanel(m_rightDock);
rightLayout->addWidget(m_todayPanel);
m_mainSplitter->addWidget(calendarContainer);
m_mainSplitter->addWidget(m_rightDock);
m_mainSplitter->setStretchFactor(0, 1);
m_mainSplitter->setStretchFactor(1, 0);
m_mainSplitter->setSizes({900, 320});
rootLayout->addWidget(m_mainSplitter, 1);
addCentralWidget(root);
setStackSwitchMode(ElaWindowType::StackSwitchMode::None);
setCurrentStackIndex(1);
connect(m_compactButton, &ElaToolButton::clicked, this, &MainWindow::close);
connect(m_todayButton, &ElaPushButton::clicked, this, [this]() { navigateToDate(QDate::currentDate()); });
connect(m_prevButton, &ElaToolButton::clicked, this, [this]() { stepDate(-1); });
connect(m_nextButton, &ElaToolButton::clicked, this, [this]() { stepDate(1); });
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);
if (m_syncService)
{
connect(m_syncService, &SyncService::statusChanged, this, &MainWindow::updateSyncStatus);
updateSyncStatus(m_syncService->statusText());
}
else
{
updateSyncStatus(QStringLiteral("本地"));
}
connect(m_snapCombo, &ElaComboBox::currentIndexChanged, this, [this](int index) {
static const int values[] = {15, 30, 60};
if (index >= 0 && index < 3 && m_grid)
{
m_grid->setSnapMinutes(values[index]);
m_settings.setSnapMinutes(values[index]);
}
});
connect(m_viewPivot, &ElaPivot::pivotClicked, this, [this](int index) {
if (index >= 0 && index <= 2)
{
setView(static_cast<View>(index));
}
});
connect(handleButton, &ElaPushButton::clicked, this, [this]() {
const QVector<ScheduleItem> items = m_notificationService.overdueItems();
if (items.isEmpty())
{
return;
}
const ScheduleItem& first = items.first();
m_currentDate = first.block.startAt.date();
setView(View::Day);
m_grid->scrollToBlock(first.block.id);
m_grid->setFocus(Qt::OtherFocusReason);
});
auto* newShortcut = new QShortcut(QKeySequence::New, this);
connect(newShortcut, &QShortcut::activated, this, &MainWindow::openCreateDialogForNew);
auto* prevShortcut = new QShortcut(QKeySequence(QStringLiteral("Alt+Left")), this);
connect(prevShortcut, &QShortcut::activated, this, [this]() { stepDate(-1); });
auto* nextShortcut = new QShortcut(QKeySequence(QStringLiteral("Alt+Right")), this);
connect(nextShortcut, &QShortcut::activated, this, [this]() { stepDate(1); });
auto* todayShortcut = new QShortcut(QKeySequence(QStringLiteral("Ctrl+T")), this);
connect(todayShortcut, &QShortcut::activated, this, [this]() { navigateToDate(QDate::currentDate()); });
auto* dayShortcut = new QShortcut(QKeySequence(QStringLiteral("Ctrl+1")), this);
connect(dayShortcut, &QShortcut::activated, this, [this]() { setView(View::Day); });
auto* monthShortcut = new QShortcut(QKeySequence(QStringLiteral("Ctrl+2")), this);
connect(monthShortcut, &QShortcut::activated, this, [this]() { setView(View::Month); });
auto* yearShortcut = new QShortcut(QKeySequence(QStringLiteral("Ctrl+3")), this);
connect(yearShortcut, &QShortcut::activated, this, [this]() { setView(View::Year); });
auto* settingsShortcut = new QShortcut(QKeySequence(QStringLiteral("Ctrl+,")), this);
connect(settingsShortcut, &QShortcut::activated, this, &MainWindow::openSettings);
auto* compactShortcut = new QShortcut(QKeySequence(QStringLiteral("Ctrl+W")), this);
connect(compactShortcut, &QShortcut::activated, this, &MainWindow::close);
}
void MainWindow::connectSignals()
{
connect(&m_scheduleService, &ScheduleService::dataChanged, this, &MainWindow::reloadCurrentView);
connect(m_grid, &ScheduleGridView::createRequested, this, &MainWindow::openCreateDialog);
connect(m_grid, &ScheduleGridView::editRequested, this, &MainWindow::openEditDialog);
connect(m_grid, &ScheduleGridView::moveRequested, this, [this](const QString& id,
const QDateTime& start,
const QDateTime& end) {
QString error;
if (!m_scheduleService.moveBlock(id, start, end, &error))
{
showError(QStringLiteral("移动日程失败"), error);
}
});
connect(m_grid, &ScheduleGridView::statusChangeRequested, this, [this](const QString& id,
const QString& status) {
QString error;
if (!m_scheduleService.setBlockStatus(id, status, &error))
{
showError(QStringLiteral("更新状态失败"), error);
}
});
connect(m_grid, &ScheduleGridView::postponeRequested, this, [this](const QString& id, int minutes) {
QString error;
if (!m_scheduleService.postponeBlock(id, minutes, &error))
{
showError(QStringLiteral("延后日程失败"), error);
}
});
connect(m_grid, &ScheduleGridView::deleteRequested, this, [this](const QString& id) {
QString error;
if (!m_scheduleService.deleteBlock(id, &error))
{
showError(QStringLiteral("删除日程失败"), error);
}
});
connect(m_monthView, &MonthView::dateSelected, this, &MainWindow::navigateToDate);
connect(m_monthView, &MonthView::dateActivated, this, [this](const QDate& date) {
m_currentDate = date;
setView(View::Day);
});
connect(m_monthView, &MonthView::createRequested, this, [this](const QDate& date) {
navigateToDate(date);
openCreateDialogForNew();
});
connect(m_monthView, &MonthView::monthStepRequested, this, [this](int direction) { stepDate(direction); });
connect(m_yearView, &YearView::dateSelected, this, &MainWindow::navigateToDate);
connect(m_yearView, &YearView::dateActivated, this, [this](const QDate& date) {
m_currentDate = date;
setView(View::Day);
});
connect(m_yearView, &YearView::monthActivated, this, [this](const QDate& month) {
m_currentDate = month;
setView(View::Month);
});
connect(m_yearView, &YearView::yearStepRequested, this, [this](int direction) { stepDate(direction); });
connect(m_todayPanel, &TodayPanel::editRequested, this, &MainWindow::openEditDialog);
connect(m_todayPanel, &TodayPanel::statusChangeRequested, this, [this](const QString& id,
const QString& status) {
QString error;
if (!m_scheduleService.setBlockStatus(id, status, &error))
{
showError(QStringLiteral("更新状态失败"), error);
}
});
connect(m_todayPanel, &TodayPanel::postponeRequested, this, [this](const QString& id, int minutes) {
QString error;
if (!m_scheduleService.postponeBlock(id, minutes, &error))
{
showError(QStringLiteral("延后日程失败"), error);
}
});
connect(m_todayPanel, &TodayPanel::deleteRequested, this, [this](const QString& id) {
QString error;
if (!m_scheduleService.deleteBlock(id, &error))
{
showError(QStringLiteral("删除日程失败"), error);
}
});
connect(m_todayPanel, &TodayPanel::focusRequested, this, [this](const QString& id) {
if (m_currentView != View::Day)
{
setView(View::Day);
}
m_grid->scrollToBlock(id);
m_grid->setFocus(Qt::OtherFocusReason);
});
connect(&m_notificationService,
&NotificationService::overdueListChanged,
this,
[this](const QVector<ScheduleItem>& items) {
updateOverdueBanner(items);
reloadCurrentView();
});
connect(&m_themeManager, &ThemeManager::themeChanged, this, &MainWindow::applyTheme);
connect(&m_themeManager, &ThemeManager::preferenceChanged, this, [this](ThemeManager::Preference) {
applyTheme(m_themeManager.tokens());
});
}
void MainWindow::applyTheme(const ThemeTokens& tokens)
{
m_tokens = tokens;
if (m_grid)
{
m_grid->setTokens(tokens);
}
if (m_monthView)
{
m_monthView->setTokens(tokens);
}
if (m_yearView)
{
m_yearView->setTokens(tokens);
}
if (m_todayPanel)
{
m_todayPanel->setTokens(tokens);
}
if (m_toolbar)
{
m_toolbar->setStyleSheet(QStringLiteral(
"QFrame#Toolbar{background:%1;border:1px solid %2;border-radius:10px;}")
.arg(tokens.toolbarBackground.name(), tokens.cardBorder.name()));
}
if (m_rightDock)
{
m_rightDock->setStyleSheet(QStringLiteral(
"QFrame#RightDock{background:%1;border:1px solid %2;border-radius:10px;}")
.arg(tokens.panelBackground.name(), tokens.cardBorder.name()));
}
if (m_overdueBanner)
{
m_overdueBanner->setStyleSheet(
QStringLiteral("QFrame#OverdueBanner{background:%1;border:1px solid %2;border-radius:8px;}")
.arg(tokens.blockOverdueFill.name(), tokens.blockOverdueBorder.name()));
}
if (m_overdueLabel)
{
m_overdueLabel->setStyleSheet(
QStringLiteral("background:transparent;color:%1;font-size:12px;")
.arg(tokens.blockOverdueBorder.name()));
}
if (m_syncLabel)
{
m_syncLabel->setStyleSheet(
QStringLiteral("background:transparent;color:%1;font-size:11px;").arg(tokens.textMuted.name()));
}
if (m_themeButton)
{
m_themeButton->setToolTip(QStringLiteral("主题:%1(点击切换)")
.arg(ThemeManager::preferenceLabel(m_themeManager.preference())));
}
}
void MainWindow::restoreWindowState()
{
const QByteArray geometry = m_settings.scheduleGeometry();
if (!geometry.isEmpty())
{
restoreGeometry(geometry);
}
else
{
moveToCenter();
}
const QByteArray mainState = m_settings.scheduleSplitter();
if (!mainState.isEmpty() && m_mainSplitter)
{
m_mainSplitter->restoreState(mainState);
}
int snapMinutes = m_settings.snapMinutes();
if (snapMinutes != 15 && snapMinutes != 30 && snapMinutes != 60)
{
snapMinutes = 15;
}
const int snapIndex = snapMinutes == 15 ? 0 : (snapMinutes == 30 ? 1 : 2);
{
const QSignalBlocker blocker(m_snapCombo);
m_snapCombo->setCurrentIndex(snapIndex);
}
m_grid->setSnapMinutes(snapMinutes);
}
void MainWindow::saveWindowState()
{
m_settings.setScheduleGeometry(saveGeometry());
if (m_mainSplitter)
{
m_settings.setScheduleSplitter(m_mainSplitter->saveState());
}
if (m_grid)
{
m_settings.setSnapMinutes(m_grid->snapMinutes());
}
}
void MainWindow::setView(View view)
{
m_currentView = view;
const int index = static_cast<int>(view);
if (m_viewStack)
{
m_viewStack->setCurrentIndex(index);
}
if (m_viewPivot)
{
m_viewPivot->setCurrentIndex(index);
}
updateDateLabel();
updateHint();
reloadCurrentView();
if (view == View::Day && m_grid)
{
m_grid->scrollToCurrentTime();
}
}
MainWindow::View MainWindow::view() const
{
return m_currentView;
}
QDate MainWindow::currentDate() const
{
return m_currentDate;
}
void MainWindow::reloadCurrentView()
{
if (!m_grid || !m_monthView || !m_yearView || !m_todayPanel)
{
return;
}
const QDateTime now = QDateTime::currentDateTime();
QVector<ScheduleItem> agendaItems;
switch (m_currentView)
{
case View::Day:
{
m_grid->setDate(m_currentDate);
agendaItems = m_scheduleService.itemsForDay(m_currentDate);
m_grid->setBlocks(agendaItems);
break;
}
case View::Month:
{
const QDate first(m_currentDate.year(), m_currentDate.month(), 1);
const QDate last = first.addMonths(1).addDays(-1);
m_monthView->setMonth(first);
m_monthView->setItems(m_scheduleService.itemsForRange(first, last));
m_monthView->setSelectedDate(m_currentDate);
agendaItems = m_scheduleService.itemsForDay(m_currentDate);
break;
}
case View::Year:
{
const int year = m_currentDate.year();
m_yearView->setYear(year);
m_yearView->setItems(m_scheduleService.itemsForRange(QDate(year, 1, 1), QDate(year, 12, 31)));
m_yearView->setSelectedDate(m_currentDate);
agendaItems = m_scheduleService.itemsForDay(m_currentDate);
break;
}
}
m_todayPanel->setDate(m_currentDate);
m_todayPanel->setItems(agendaItems, now);
}
void MainWindow::navigateToDate(const QDate& date)
{
if (!date.isValid())
{
return;
}
m_currentDate = date;
updateDateLabel();
reloadCurrentView();
if (m_currentView == View::Day && m_grid)
{
m_grid->scrollToCurrentTime();
}
}
void MainWindow::stepDate(int direction)
{
if (direction == 0)
{
return;
}
switch (m_currentView)
{
case View::Day:
navigateToDate(m_currentDate.addDays(direction));
break;
case View::Month:
navigateToDate(m_currentDate.addMonths(direction));
break;
case View::Year:
{
const int year = m_currentDate.year() + direction;
if (year < 1900 || year > 9999)
{
return;
}
const QDate first(year, m_currentDate.month(), 1);
if (!first.isValid())
{
return;
}
navigateToDate(QDate(year, m_currentDate.month(), qMin(m_currentDate.day(), first.daysInMonth())));
break;
}
}
}
void MainWindow::updateDateLabel()
{
if (!m_dateLabel)
{
return;
}
const QDate today = QDate::currentDate();
QString text;
switch (m_currentView)
{
case View::Day:
{
text = QStringLiteral("%1年%2月%3日 %4")
.arg(m_currentDate.year())
.arg(m_currentDate.month())
.arg(m_currentDate.day())
.arg(weekdayLabel(m_currentDate));
if (m_currentDate == today)
{
text.prepend(QStringLiteral("今天 · "));
}
break;
}
case View::Month:
text = QStringLiteral("%1年%2月").arg(m_currentDate.year()).arg(m_currentDate.month());
if (m_currentDate.year() == today.year() && m_currentDate.month() == today.month())
{
text.prepend(QStringLiteral("本月 · "));
}
break;
case View::Year:
text = QStringLiteral("%1年").arg(m_currentDate.year());
if (m_currentDate.year() == today.year())
{
text.prepend(QStringLiteral("今年 · "));
}
break;
}
m_dateLabel->setText(text);
}
void MainWindow::updateHint()
{
if (!m_hintLabel)
{
return;
}
switch (m_currentView)
{
case View::Day:
m_hintLabel->setText(
QStringLiteral("双击空白新建 · 拖动块移动 · 上下边缘改时长 · Ctrl+滚轮缩放 · Delete 删除"));
break;
case View::Month:
m_hintLabel->setText(
QStringLiteral("单击选择日期 · 双击打开日视图 · 滚轮切换月份 · 右键新建日程"));
break;
case View::Year:
m_hintLabel->setText(
QStringLiteral("单击选择日期 · 双击打开日视图 · 点击月份标题进入月视图 · 滚轮切换年份"));
break;
}
}
void MainWindow::showAndRaise()
{
if (isMinimized())
{
showNormal();
}
else
{
show();
}
raise();
activateWindow();
}
void MainWindow::openNewBlock()
{
openCreateDialogForNew();
}
void MainWindow::focusBlock(const QDate& date, const QString& blockId)
{
if (!date.isValid())
{
return;
}
m_currentDate = date;
setView(View::Day);
showAndRaise();
QTimer::singleShot(0, this, [this, blockId]() {
m_grid->scrollToBlock(blockId);
m_grid->setFocus(Qt::OtherFocusReason);
});
}
void MainWindow::openCreateDialog(const QDateTime& start, const QDateTime& end)
{
BlockEditDialog dialog(m_tokens, this);
dialog.setCreateMode(true);
dialog.setValues(QString(), start, end);
dialog.moveToCenter();
if (dialog.exec() != QDialog::Accepted)
{
return;
}
QString error;
if (!m_scheduleService.createBlock(dialog.titleValue(), dialog.startValue(), dialog.endValue(), &error))
{
showError(QStringLiteral("创建日程失败"), error);
return;
}
if (dialog.startValue().date() != m_currentDate)
{
navigateToDate(dialog.startValue().date());
}
}
void MainWindow::openCreateDialogForNew()
{
const QDateTime start = defaultNewStart();
openCreateDialog(start, start.addSecs(60 * 60));
}
void MainWindow::openEditDialog(const QString& blockId)
{
const QVector<ScheduleItem> items = m_scheduleService.itemsForDay(m_currentDate);
const auto it = std::find_if(items.cbegin(), items.cend(), [&blockId](const ScheduleItem& item) {
return item.block.id == blockId;
});
if (it == items.cend())
{
showError(QStringLiteral("编辑日程失败"), QStringLiteral("当前日期找不到该日程,请刷新后重试"));
return;
}
BlockEditDialog dialog(m_tokens, this);
dialog.setCreateMode(false);
dialog.setValues(it->task.title, it->block.startAt, it->block.endAt);
dialog.moveToCenter();
if (dialog.exec() != QDialog::Accepted)
{
return;
}
QString error;
if (!m_scheduleService.updateBlock(blockId,
dialog.titleValue(),
dialog.startValue(),
dialog.endValue(),
&error))
{
showError(QStringLiteral("保存日程失败"), error);
return;
}
if (dialog.startValue().date() != m_currentDate)
{
navigateToDate(dialog.startValue().date());
}
}
void MainWindow::openSettings()
{
SettingsDialog dialog(m_themeManager, m_settings, this);
if (m_syncService)
{
connect(&dialog, &SettingsDialog::syncSettingsChanged, m_syncService, &SyncService::reloadConfig);
}
dialog.moveToCenter();
dialog.exec();
}
void MainWindow::updateSyncStatus(const QString& status)
{
if (!m_syncLabel)
{
return;
}
QString shortStatus = status;
if (status.contains(QStringLiteral("失败")) || status.contains(QStringLiteral("错误")) ||
status.contains(QStringLiteral("未配置")) || status.contains(QStringLiteral("无效")))
{
shortStatus = QStringLiteral("同步错误");
}
else if (status.contains(QStringLiteral("离线")) || status.contains(QStringLiteral("等待")))
{
shortStatus = QStringLiteral("离线");
}
else if (status.contains(QStringLiteral("注册")) || status.contains(QStringLiteral("同步中")) ||
status.contains(QStringLiteral("WebSocket")))
{
shortStatus = QStringLiteral("同步中");
}
else if (status.contains(QStringLiteral("已同步")) || status.contains(QStringLiteral("已连接")))
{
shortStatus = QStringLiteral("已同步");
}
else
{
shortStatus = QStringLiteral("本地");
}
m_syncLabel->setText(QStringLiteral("● ") + shortStatus);
m_syncLabel->setToolTip(status);
}
void MainWindow::updateOverdueBanner(const QVector<ScheduleItem>& items)
{
if (!m_overdueBanner || !m_overdueLabel)
{
return;
}
if (items.isEmpty())
{
m_overdueBanner->setVisible(false);
return;
}
const ScheduleItem& first = items.first();
m_overdueLabel->setText(QStringLiteral("有 %1 项日程已超时,最早:%2(%3)")
.arg(items.size())
.arg(first.task.title,
DateTimeUtils::formatTimeRange(first.block.startAt, first.block.endAt)));
m_overdueBanner->setVisible(true);
}
void MainWindow::showError(const QString& title, const QString& message)
{
ElaMessageBar::error(ElaMessageBarType::TopRight,
title,
message.isEmpty() ? QStringLiteral("未知错误") : message,
4500,
this);
}
QDateTime MainWindow::defaultNewStart() const
{
const QDateTime now = QDateTime::currentDateTime();
QDateTime start;
if (m_currentDate == now.date())
{
start = DateTimeUtils::snapTo(now.addSecs(15 * 60), 15);
}
else
{
start = QDateTime(m_currentDate, QTime(9, 0), Qt::LocalTime);
}
const QDateTime rangeEnd = QDateTime(m_currentDate.addDays(1), QTime(0, 0), Qt::LocalTime);
if (start.addSecs(60 * 60) > rangeEnd)
{
start = rangeEnd.addSecs(-60 * 60);
}
const QDateTime rangeStart = QDateTime(m_currentDate, QTime(0, 0), Qt::LocalTime);
if (start < rangeStart)
{
start = rangeStart;
}
return start;
}
void MainWindow::closeEvent(QCloseEvent* event)
{
saveWindowState();
hide();
Q_EMIT closeRequested();
event->ignore();
}
void MainWindow::paintEvent(QPaintEvent* event)
{
ElaWindow::paintEvent(event);
if (!WindowEffects::isMicaActive())
{
return;
}
QPainter painter(this);
QColor tint = m_tokens.windowBackground;
tint.setAlpha(m_tokens.dark ? 92 : 84);
painter.fillRect(rect(), tint);
QColor bar = m_tokens.toolbarBackground;
bar.setAlpha(m_tokens.dark ? 178 : 168);
painter.fillRect(QRect(0, 0, width(), 44), bar);
}
void MainWindow::showEvent(QShowEvent* event)
{
ElaWindow::showEvent(event);
if (!m_firstShowHandled)
{
m_firstShowHandled = true;
QTimer::singleShot(0, this, [this]() {
if (m_grid && m_currentView == View::Day)
{
m_grid->scrollToCurrentTime();
}
});
}
}
+132
View File
@@ -0,0 +1,132 @@
#pragma once
#include <QDate>
#include <QDateTime>
#include <QVector>
#include "ElaWindow.h"
#include "core/ScheduleItem.h"
#include "ui/theme/ThemeTokens.h"
class AppSettings;
class ElaComboBox;
class ElaLineEdit;
class ElaPivot;
class ElaPushButton;
class ElaText;
class ElaToolButton;
class MonthView;
class NotificationService;
class ScheduleGridView;
class ScheduleService;
class SyncService;
class ThemeManager;
class TodayPanel;
class YearView;
class QCloseEvent;
class QFrame;
class QPaintEvent;
class QLabel;
class QShowEvent;
class QSplitter;
class QStackedWidget;
/*
* 类名: MainWindow
* 功能: 详细日程窗口;日/月/年视图、当日任务与设置入口
* 线程安全: 否;UI 线程
*/
class MainWindow : public ElaWindow
{
Q_OBJECT
public:
enum class View
{
Day = 0,
Month = 1,
Year = 2,
};
Q_ENUM(View)
MainWindow(ScheduleService& scheduleService,
NotificationService& notificationService,
ThemeManager& themeManager,
AppSettings& settings,
SyncService* syncService = nullptr,
QWidget* parent = nullptr);
~MainWindow() override;
void setView(View view);
View view() const;
QDate currentDate() const;
void showAndRaise();
void openNewBlock();
void focusBlock(const QDate& date, const QString& blockId);
signals:
void closeRequested();
protected:
void closeEvent(QCloseEvent* event) override;
void showEvent(QShowEvent* event) override;
void paintEvent(QPaintEvent* event) override;
private:
void buildUi();
void connectSignals();
void restoreWindowState();
void saveWindowState();
void applyTheme(const ThemeTokens& tokens);
void reloadCurrentView();
void navigateToDate(const QDate& date);
void stepDate(int direction);
void updateDateLabel();
void updateHint();
void openCreateDialog(const QDateTime& start, const QDateTime& end);
void openCreateDialogForNew();
void openEditDialog(const QString& blockId);
void openSettings();
void updateOverdueBanner(const QVector<ScheduleItem>& items);
void showError(const QString& title, const QString& message);
void updateSyncStatus(const QString& status);
QDateTime defaultNewStart() const;
ScheduleService& m_scheduleService;
NotificationService& m_notificationService;
ThemeManager& m_themeManager;
AppSettings& m_settings;
SyncService* m_syncService = nullptr;
ThemeTokens m_tokens;
QDate m_currentDate;
View m_currentView = View::Day;
bool m_firstShowHandled = false;
QFrame* m_toolbar = nullptr;
ElaToolButton* m_compactButton = nullptr;
ElaPushButton* m_todayButton = nullptr;
ElaToolButton* m_prevButton = nullptr;
ElaToolButton* m_nextButton = nullptr;
ElaText* m_dateLabel = nullptr;
ElaPivot* m_viewPivot = nullptr;
ElaPushButton* m_newButton = nullptr;
ElaLineEdit* m_searchEdit = nullptr;
ElaComboBox* m_snapCombo = nullptr;
ElaToolButton* m_themeButton = nullptr;
ElaToolButton* m_settingsButton = nullptr;
QLabel* m_syncLabel = nullptr;
QFrame* m_overdueBanner = nullptr;
QLabel* m_overdueLabel = nullptr;
QSplitter* m_mainSplitter = nullptr;
QFrame* m_rightDock = nullptr;
QStackedWidget* m_viewStack = nullptr;
ScheduleGridView* m_grid = nullptr;
MonthView* m_monthView = nullptr;
YearView* m_yearView = nullptr;
TodayPanel* m_todayPanel = nullptr;
ElaText* m_hintLabel = nullptr;
};
+135
View File
@@ -0,0 +1,135 @@
#include "BlockEditDialog.h"
#include <QDateTimeEdit>
#include <QFormLayout>
#include <QHBoxLayout>
#include <QSignalBlocker>
#include <QVBoxLayout>
#include "ElaLineEdit.h"
#include "ElaPushButton.h"
#include "ElaText.h"
BlockEditDialog::BlockEditDialog(const ThemeTokens& tokens, QWidget* parent)
: ElaDialog(parent)
, m_errorColor(tokens.blockOverdueBorder.name())
{
setWindowTitle(QStringLiteral("新建日程"));
setWindowButtonFlags(ElaAppBarType::CloseButtonHint);
setMinimumWidth(440);
resize(440, 320);
auto* root = new QVBoxLayout(this);
root->setContentsMargins(22, 8, 22, 18);
root->setSpacing(12);
auto* form = new QFormLayout();
form->setLabelAlignment(Qt::AlignLeft | Qt::AlignVCenter);
form->setFormAlignment(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* startLabel = new ElaText(QStringLiteral("开始"), 13, this);
m_startEdit = new QDateTimeEdit(this);
m_startEdit->setCalendarPopup(true);
m_startEdit->setDisplayFormat(QStringLiteral("yyyy-MM-dd HH:mm"));
m_startEdit->setMinimumHeight(34);
auto* endLabel = new ElaText(QStringLiteral("结束"), 13, this);
m_endEdit = new QDateTimeEdit(this);
m_endEdit->setCalendarPopup(true);
m_endEdit->setDisplayFormat(QStringLiteral("yyyy-MM-dd HH:mm"));
m_endEdit->setMinimumHeight(34);
form->addRow(titleLabel, m_titleEdit);
form->addRow(startLabel, m_startEdit);
form->addRow(endLabel, m_endEdit);
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* cancelButton = new ElaPushButton(QStringLiteral("取消"), this);
auto* saveButton = new ElaPushButton(QStringLiteral("保存"), this);
cancelButton->setFixedSize(88, 34);
saveButton->setFixedSize(88, 34);
saveButton->setDefault(true);
buttonRow->addWidget(cancelButton);
buttonRow->addWidget(saveButton);
root->addLayout(buttonRow);
connect(cancelButton, &ElaPushButton::clicked, this, &BlockEditDialog::reject);
connect(saveButton, &ElaPushButton::clicked, this, &BlockEditDialog::accept);
connect(m_startEdit, &QDateTimeEdit::dateTimeChanged, this, [this](const QDateTime& start) {
if (m_endEdit->dateTime() <= start)
{
const QSignalBlocker blocker(m_endEdit);
m_endEdit->setDateTime(start.addSecs(60 * 60));
}
});
}
void BlockEditDialog::setCreateMode(bool create)
{
setWindowTitle(create ? QStringLiteral("新建日程") : QStringLiteral("编辑日程"));
}
void BlockEditDialog::setValues(const QString& title, const QDateTime& start, const QDateTime& end)
{
const QSignalBlocker startBlocker(m_startEdit);
const QSignalBlocker endBlocker(m_endEdit);
m_titleEdit->setText(title);
m_startEdit->setDateTime(start);
m_endEdit->setDateTime(end);
m_titleEdit->setFocus();
m_titleEdit->selectAll();
}
QString BlockEditDialog::titleValue() const
{
return m_titleEdit->text().trimmed();
}
QDateTime BlockEditDialog::startValue() const
{
return m_startEdit->dateTime();
}
QDateTime BlockEditDialog::endValue() const
{
return m_endEdit->dateTime();
}
void BlockEditDialog::updateError(const QString& message)
{
m_errorLabel->setText(message);
}
void BlockEditDialog::accept()
{
if (startValue().isValid() && endValue() <= startValue())
{
updateError(QStringLiteral("结束时间必须晚于开始时间"));
return;
}
if (startValue().secsTo(endValue()) < 5 * 60)
{
updateError(QStringLiteral("日程时长至少为 5 分钟"));
return;
}
updateError(QString());
QDialog::accept();
}
+43
View File
@@ -0,0 +1,43 @@
#pragma once
#include <QDateTime>
#include <QString>
#include "ElaDialog.h"
#include "ui/theme/ThemeTokens.h"
class ElaLineEdit;
class ElaText;
class QDateTimeEdit;
/*
* 类名: BlockEditDialog
* 功能: 新建/编辑日程的模态对话框,负责输入校验
* 线程安全: 否;UI 线程
*/
class BlockEditDialog : public ElaDialog
{
Q_OBJECT
public:
explicit BlockEditDialog(const ThemeTokens& tokens, QWidget* parent = nullptr);
void setCreateMode(bool create);
void setValues(const QString& title, const QDateTime& start, const QDateTime& end);
QString titleValue() const;
QDateTime startValue() const;
QDateTime endValue() const;
public slots:
void accept() override;
private:
void updateError(const QString& message);
ElaLineEdit* m_titleEdit = nullptr;
QDateTimeEdit* m_startEdit = nullptr;
QDateTimeEdit* m_endEdit = nullptr;
ElaText* m_errorLabel = nullptr;
QString m_errorColor;
};
+290
View File
@@ -0,0 +1,290 @@
#include "SettingsDialog.h"
#include <QFormLayout>
#include <QFrame>
#include <QHBoxLayout>
#include <QLineEdit>
#include <QVBoxLayout>
#include "ElaComboBox.h"
#include "ElaLineEdit.h"
#include "ElaPushButton.h"
#include "ElaText.h"
#include "ElaToggleSwitch.h"
#include "ElaToolButton.h"
#include "ui/theme/ThemeManager.h"
#include "ui/theme/WindowEffects.h"
#include "utils/AppSettings.h"
SettingsDialog::SettingsDialog(ThemeManager& themeManager, AppSettings& settings, QWidget* parent)
: ElaDialog(parent)
, m_themeManager(themeManager)
, m_settings(settings)
{
setWindowTitle(QStringLiteral("设置"));
setWindowButtonFlags(ElaAppBarType::CloseButtonHint);
resize(560, 720);
setMinimumWidth(520);
auto* root = new QVBoxLayout(this);
root->setContentsMargins(24, 8, 24, 18);
root->setSpacing(10);
const auto addSectionTitle = [this, root](const QString& text) {
auto* title = new ElaText(text, 14, this);
QFont titleFont = title->font();
titleFont.setWeight(QFont::DemiBold);
title->setFont(titleFont);
root->addWidget(title);
};
const auto addDivider = [this, root]() {
auto* divider = new QFrame(this);
divider->setFrameShape(QFrame::HLine);
divider->setFrameShadow(QFrame::Plain);
root->addWidget(divider);
};
addSectionTitle(QStringLiteral("外观"));
auto* themeRow = new QHBoxLayout();
themeRow->setSpacing(16);
auto* themeLabel = new ElaText(QStringLiteral("主题"), 13, this);
m_themeCombo = new ElaComboBox(this);
m_themeCombo->addItems({QStringLiteral("跟随系统"), QStringLiteral("浅色"), QStringLiteral("深色")});
m_themeCombo->setFixedSize(150, 32);
switch (m_themeManager.preference())
{
case ThemeManager::Preference::Light:
m_themeCombo->setCurrentIndex(1);
break;
case ThemeManager::Preference::Dark:
m_themeCombo->setCurrentIndex(2);
break;
case ThemeManager::Preference::System:
default:
m_themeCombo->setCurrentIndex(0);
break;
}
themeRow->addWidget(themeLabel, 0, Qt::AlignVCenter);
themeRow->addWidget(m_themeCombo, 0, Qt::AlignVCenter);
themeRow->addStretch(1);
root->addLayout(themeRow);
auto* micaRow = new QHBoxLayout();
micaRow->setSpacing(16);
auto* micaTextLayout = new QVBoxLayout();
micaTextLayout->setSpacing(2);
auto* micaTitle = new ElaText(QStringLiteral("窗口云母效果"), 13, this);
auto* micaDescription = new ElaText(
QStringLiteral("使用 ElaWidgetTools 的 ElaMica 背景(跨平台模拟;Windows 可扩展系统 Mica)。"),
11,
this);
micaDescription->setTextStyle(ElaTextType::Caption);
micaDescription->setWordWrap(true);
micaDescription->setMaximumWidth(350);
micaTextLayout->addWidget(micaTitle);
micaTextLayout->addWidget(micaDescription);
m_micaSwitch = new ElaToggleSwitch(this);
m_micaSwitch->setIsToggled(m_settings.micaEnabled());
micaRow->addLayout(micaTextLayout, 1);
micaRow->addWidget(m_micaSwitch, 0, Qt::AlignVCenter);
root->addLayout(micaRow);
addDivider();
addSectionTitle(QStringLiteral("AI 服务"));
auto* aiDescription = new ElaText(
QStringLiteral("配置 OpenAI 兼容接口(云端或本地服务)。AI 排程与对话会使用此处配置。"),
11,
this);
aiDescription->setTextStyle(ElaTextType::Caption);
aiDescription->setWordWrap(true);
root->addWidget(aiDescription);
const AiConfig aiConfig = m_settings.aiConfig();
auto* aiForm = new QFormLayout();
aiForm->setHorizontalSpacing(14);
aiForm->setVerticalSpacing(10);
aiForm->setFieldGrowthPolicy(QFormLayout::ExpandingFieldsGrow);
aiForm->setLabelAlignment(Qt::AlignLeft | Qt::AlignVCenter);
auto* baseUrlLabel = new ElaText(QStringLiteral("接口地址"), 13, this);
m_baseUrlEdit = new ElaLineEdit(this);
m_baseUrlEdit->setPlaceholderText(QStringLiteral("https://api.openai.com/v1"));
m_baseUrlEdit->setText(aiConfig.baseUrl);
m_baseUrlEdit->setClearButtonEnabled(true);
m_baseUrlEdit->setMinimumHeight(34);
auto* modelLabel = new ElaText(QStringLiteral("模型"), 13, this);
m_modelEdit = new ElaLineEdit(this);
m_modelEdit->setPlaceholderText(QStringLiteral("gpt-4o-mini"));
m_modelEdit->setText(aiConfig.model);
m_modelEdit->setClearButtonEnabled(true);
m_modelEdit->setMinimumHeight(34);
auto* apiKeyLabel = new ElaText(QStringLiteral("API Key"), 13, this);
auto* keyRow = new QHBoxLayout();
keyRow->setSpacing(6);
m_apiKeyEdit = new ElaLineEdit(this);
m_apiKeyEdit->setPlaceholderText(QStringLiteral("sk-..."));
m_apiKeyEdit->setText(aiConfig.apiKey);
m_apiKeyEdit->setEchoMode(QLineEdit::Password);
m_apiKeyEdit->setClearButtonEnabled(true);
m_apiKeyEdit->setMinimumHeight(34);
m_keyVisibilityButton = new ElaToolButton(this);
m_keyVisibilityButton->setIsTransparent(true);
m_keyVisibilityButton->setElaIcon(ElaIconType::Eye);
m_keyVisibilityButton->setFixedSize(30, 30);
m_keyVisibilityButton->setToolTip(QStringLiteral("显示 API Key"));
keyRow->addWidget(m_apiKeyEdit, 1);
keyRow->addWidget(m_keyVisibilityButton, 0, Qt::AlignVCenter);
aiForm->addRow(baseUrlLabel, m_baseUrlEdit);
aiForm->addRow(modelLabel, m_modelEdit);
aiForm->addRow(apiKeyLabel, keyRow);
root->addLayout(aiForm);
auto* keyNote = new ElaText(
QStringLiteral("API Key 仅保存在本地配置文件,文件权限设为 0600,不会写入日志。"),
11,
this);
keyNote->setTextStyle(ElaTextType::Caption);
keyNote->setWordWrap(true);
root->addWidget(keyNote);
addDivider();
addSectionTitle(QStringLiteral("同步服务"));
auto* syncDescription = new ElaText(
QStringLiteral("自部署 Go 同步服务端。首次启用会自动注册设备并保存访问令牌。"),
11,
this);
syncDescription->setTextStyle(ElaTextType::Caption);
syncDescription->setWordWrap(true);
root->addWidget(syncDescription);
const SyncConfig initialSync = m_settings.syncConfig();
auto* syncUrlRow = new QHBoxLayout();
syncUrlRow->setSpacing(12);
auto* syncUrlLabel = new ElaText(QStringLiteral("服务地址"), 13, this);
m_syncUrlEdit = new ElaLineEdit(this);
m_syncUrlEdit->setPlaceholderText(QStringLiteral("http://127.0.0.1:8787"));
m_syncUrlEdit->setText(initialSync.serverUrl);
m_syncUrlEdit->setClearButtonEnabled(true);
m_syncUrlEdit->setMinimumHeight(34);
syncUrlRow->addWidget(syncUrlLabel, 0, Qt::AlignVCenter);
syncUrlRow->addWidget(m_syncUrlEdit, 1);
root->addLayout(syncUrlRow);
auto* syncToggleRow = new QHBoxLayout();
syncToggleRow->setSpacing(16);
auto* syncToggleText = new QVBoxLayout();
syncToggleText->setSpacing(2);
auto* syncToggleTitle = new ElaText(QStringLiteral("启用多设备同步"), 13, this);
auto* syncToggleDescription = new ElaText(
initialSync.token.isEmpty() ? QStringLiteral("当前尚未注册设备;启用后自动注册。")
: QStringLiteral("设备已注册;修改地址或开关后立即重连。"),
11,
this);
syncToggleDescription->setTextStyle(ElaTextType::Caption);
syncToggleText->addWidget(syncToggleTitle);
syncToggleText->addWidget(syncToggleDescription);
m_syncEnabledSwitch = new ElaToggleSwitch(this);
m_syncEnabledSwitch->setIsToggled(initialSync.enabled);
syncToggleRow->addLayout(syncToggleText, 1);
syncToggleRow->addWidget(m_syncEnabledSwitch, 0, Qt::AlignVCenter);
root->addLayout(syncToggleRow);
auto* pathNote = new ElaText(QStringLiteral("配置文件:%1").arg(m_settings.configPath()), 11, this);
pathNote->setTextStyle(ElaTextType::Caption);
pathNote->setWordWrap(true);
pathNote->setTextInteractionFlags(Qt::TextSelectableByMouse);
root->addWidget(pathNote);
root->addStretch(1);
auto* buttonRow = new QHBoxLayout();
buttonRow->addStretch(1);
auto* doneButton = new ElaPushButton(QStringLiteral("完成"), this);
doneButton->setFixedSize(88, 34);
doneButton->setDefault(true);
buttonRow->addWidget(doneButton);
root->addLayout(buttonRow);
connect(m_themeCombo, &ElaComboBox::currentIndexChanged, this, [this](int index) {
switch (index)
{
case 1:
m_themeManager.setPreference(ThemeManager::Preference::Light);
break;
case 2:
m_themeManager.setPreference(ThemeManager::Preference::Dark);
break;
case 0:
default:
m_themeManager.setPreference(ThemeManager::Preference::System);
break;
}
});
connect(m_micaSwitch, &ElaToggleSwitch::toggled, this, [this](bool enabled) {
m_settings.setMicaEnabled(enabled);
WindowEffects::applyMica(enabled);
Q_EMIT micaChanged(enabled);
});
connect(m_baseUrlEdit, &ElaLineEdit::editingFinished, this, &SettingsDialog::saveAiConfig);
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_syncUrlEdit, &ElaLineEdit::editingFinished, this, &SettingsDialog::saveSyncConfig);
connect(m_syncEnabledSwitch, &ElaToggleSwitch::toggled, this, [this](bool) { saveSyncConfig(); });
connect(doneButton, &ElaPushButton::clicked, this, [this]() {
saveAiConfig();
saveSyncConfig();
accept();
});
connect(this, &QDialog::finished, this, [this]() {
saveAiConfig();
saveSyncConfig();
});
}
void SettingsDialog::saveAiConfig()
{
if (!m_baseUrlEdit || !m_modelEdit || !m_apiKeyEdit)
{
return;
}
AiConfig config = m_settings.aiConfig();
config.baseUrl = m_baseUrlEdit->text().trimmed();
config.model = m_modelEdit->text().trimmed();
config.apiKey = m_apiKeyEdit->text().trimmed();
m_settings.setAiConfig(config);
}
void SettingsDialog::saveSyncConfig()
{
if (!m_syncUrlEdit || !m_syncEnabledSwitch)
{
return;
}
SyncConfig config = m_settings.syncConfig();
const QString url = m_syncUrlEdit->text().trimmed();
const bool enabled = m_syncEnabledSwitch->getIsToggled();
if (config.serverUrl == url && config.enabled == enabled)
{
return;
}
config.serverUrl = url;
config.enabled = enabled;
m_settings.setSyncConfig(config);
Q_EMIT syncSettingsChanged();
}
void SettingsDialog::toggleKeyVisibility()
{
const bool hidden = m_apiKeyEdit->echoMode() == QLineEdit::Password;
m_apiKeyEdit->setEchoMode(hidden ? QLineEdit::Normal : QLineEdit::Password);
m_keyVisibilityButton->setElaIcon(hidden ? ElaIconType::EyeSlash : ElaIconType::Eye);
m_keyVisibilityButton->setToolTip(hidden ? QStringLiteral("隐藏 API Key") : QStringLiteral("显示 API Key"));
}
+43
View File
@@ -0,0 +1,43 @@
#pragma once
#include "ElaDialog.h"
class AppSettings;
class ElaComboBox;
class ElaLineEdit;
class ElaToggleSwitch;
class ElaToolButton;
class ThemeManager;
/*
* 类名: SettingsDialog
* 功能: 外观设置(主题、ElaMica)与 AI 服务配置
* 线程安全: 否;UI 线程
*/
class SettingsDialog : public ElaDialog
{
Q_OBJECT
public:
SettingsDialog(ThemeManager& themeManager, AppSettings& settings, QWidget* parent = nullptr);
signals:
void micaChanged(bool enabled);
void syncSettingsChanged();
private:
void saveAiConfig();
void saveSyncConfig();
void toggleKeyVisibility();
ThemeManager& m_themeManager;
AppSettings& m_settings;
ElaComboBox* m_themeCombo = nullptr;
ElaToggleSwitch* m_micaSwitch = nullptr;
ElaLineEdit* m_baseUrlEdit = nullptr;
ElaLineEdit* m_modelEdit = nullptr;
ElaLineEdit* m_apiKeyEdit = nullptr;
ElaToolButton* m_keyVisibilityButton = nullptr;
ElaLineEdit* m_syncUrlEdit = nullptr;
ElaToggleSwitch* m_syncEnabledSwitch = nullptr;
};
+556
View File
@@ -0,0 +1,556 @@
#include "ChatPanel.h"
#include <QDragEnterEvent>
#include <QDropEvent>
#include <QFileInfo>
#include <QFrame>
#include <QHBoxLayout>
#include <QLabel>
#include <QLayoutItem>
#include <QMimeData>
#include <QScrollBar>
#include <QTimer>
#include <QUrl>
#include <QVBoxLayout>
#include "ai/AIService.h"
#include "ElaLineEdit.h"
#include "ElaPushButton.h"
#include "ElaScrollArea.h"
#include "ElaText.h"
#include "ui/panels/DiffPreviewCard.h"
ChatPanel::ChatPanel(AIService& aiService, QWidget* parent)
: QWidget(parent)
, m_aiService(aiService)
{
setMinimumWidth(280);
setAcceptDrops(true);
setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);
auto* root = new QVBoxLayout(this);
root->setContentsMargins(12, 10, 12, 12);
root->setSpacing(10);
auto* header = new QHBoxLayout();
header->setContentsMargins(2, 0, 2, 0);
m_titleLabel = new ElaText(QStringLiteral("AI 助手"), 15, this);
QFont titleFont = m_titleLabel->font();
titleFont.setWeight(QFont::DemiBold);
m_titleLabel->setFont(titleFont);
m_badgeLabel = new QLabel(this);
m_badgeLabel->setText(QStringLiteral("AI 已接入"));
m_badgeLabel->setAlignment(Qt::AlignCenter);
m_badgeLabel->setFixedHeight(22);
header->addWidget(m_titleLabel);
header->addStretch(1);
header->addWidget(m_badgeLabel, 0, Qt::AlignVCenter);
root->addLayout(header);
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_messageWidget = new QWidget(m_scrollArea);
m_messageWidget->setAutoFillBackground(false);
m_messageWidget->setStyleSheet(QStringLiteral("background:transparent;"));
m_messageWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
m_messageLayout = new QVBoxLayout(m_messageWidget);
m_messageLayout->setContentsMargins(0, 0, 2, 0);
m_messageLayout->setSpacing(8);
m_scrollArea->setWidget(m_messageWidget);
connect(m_scrollArea->verticalScrollBar(), &QScrollBar::rangeChanged, this, [this](int, int max) {
m_scrollArea->verticalScrollBar()->setValue(max);
});
root->addWidget(m_scrollArea, 1);
auto* inputRow = new QHBoxLayout();
inputRow->setSpacing(8);
m_input = new ElaLineEdit(this);
m_input->setPlaceholderText(QStringLiteral("描述你的安排,例如:明天下午写周报 2 小时"));
m_input->setMinimumHeight(36);
m_sendButton = new ElaPushButton(QStringLiteral("发送"), this);
m_sendButton->setFixedSize(64, 36);
inputRow->addWidget(m_input, 1);
inputRow->addWidget(m_sendButton);
root->addLayout(inputRow);
auto* dropHint = new ElaText(
QStringLiteral("可拖入 txt / md / pdf / docx / doc / 图片,AI 会分析后生成日程建议"),
11,
this);
dropHint->setTextStyle(ElaTextType::Caption);
dropHint->setAlignment(Qt::AlignHCenter);
root->addWidget(dropHint);
connect(m_sendButton, &ElaPushButton::clicked, this, &ChatPanel::sendCurrentInput);
connect(m_input, &ElaLineEdit::returnPressed, this, &ChatPanel::sendCurrentInput);
connect(&m_aiService, &AIService::streamDelta, this, &ChatPanel::onStreamDelta);
connect(&m_aiService, &AIService::requestFinished, this, &ChatPanel::onRequestFinished);
connect(&m_aiService, &AIService::requestFailed, this, &ChatPanel::onRequestFailed);
connect(&m_aiService, &AIService::proposalReady, this, &ChatPanel::onProposalReady);
connect(&m_aiService, &AIService::notice, this, &ChatPanel::onNotice);
connect(&m_aiService, &AIService::diffApplied, this, &ChatPanel::onDiffApplied);
connect(&m_aiService, &AIService::diffRejected, this, &ChatPanel::onDiffRejected);
connect(&m_aiService, &AIService::diffApplyFailed, this, &ChatPanel::onDiffApplyFailed);
Entry welcome;
welcome.id = QStringLiteral("welcome");
welcome.kind = EntryKind::Assistant;
welcome.text = QStringLiteral(
"你好,我是日程助手。直接告诉我你的安排,例如「明天下午写周报 2 小时」,"
"我会生成可确认的日程建议。");
m_entries.append(welcome);
Entry hint;
hint.id = QStringLiteral("welcome-hint");
hint.kind = EntryKind::System;
hint.text = QStringLiteral("首次使用请先在设置中填写 AI 接口地址、模型和 API Key。");
m_entries.append(hint);
applyBadgeStyle();
rebuildMessages();
}
void ChatPanel::applyBadgeStyle()
{
if (!m_badgeLabel)
{
return;
}
m_badgeLabel->setStyleSheet(
QStringLiteral("padding:0 8px;border-radius:11px;background:%1;color:%2;font-size:11px;")
.arg(m_tokens.hourAlternate.name(), m_tokens.textSecondary.name()));
}
void ChatPanel::setTokens(const ThemeTokens& tokens)
{
m_tokens = tokens;
applyBadgeStyle();
rebuildMessages();
}
void ChatPanel::clearLayout(QVBoxLayout* layout)
{
while (QLayoutItem* item = layout->takeAt(0))
{
if (QWidget* widget = item->widget())
{
// 卡片按钮的点击信号可能仍在调用栈中,延迟删除避免 use-after-free。
widget->hide();
widget->deleteLater();
}
delete item;
}
}
void ChatPanel::rebuildMessages()
{
if (!m_messageLayout)
{
return;
}
clearLayout(m_messageLayout);
m_labels.clear();
for (const Entry& entry : m_entries)
{
if (entry.kind == EntryKind::Proposal)
{
auto* card = new DiffPreviewCard(entry.proposal,
m_tokens,
entry.proposalState == ProposalState::Applied
? DiffPreviewCard::State::Applied
: (entry.proposalState == ProposalState::Rejected
? DiffPreviewCard::State::Rejected
: DiffPreviewCard::State::Pending),
m_messageWidget);
connect(card, &DiffPreviewCard::accepted, this, [this](const QString& diffId,
const QStringList& tempIds) {
m_aiService.applyDiff(diffId, tempIds);
});
connect(card, &DiffPreviewCard::rejected, this, [this](const QString& diffId) {
m_aiService.rejectDiff(diffId);
});
m_messageLayout->addWidget(card);
continue;
}
if (entry.kind == EntryKind::System)
{
auto* label = new QLabel(entry.text, m_messageWidget);
label->setWordWrap(true);
label->setTextInteractionFlags(Qt::TextSelectableByMouse);
label->setStyleSheet(
QStringLiteral("background:transparent;color:%1;font-size:11px;padding:0 2px;")
.arg(m_tokens.textMuted.name()));
m_messageLayout->addWidget(label);
m_labels.insert(entry.id, label);
continue;
}
auto* rowWidget = new QWidget(m_messageWidget);
auto* row = new QHBoxLayout(rowWidget);
row->setContentsMargins(0, 0, 0, 0);
row->setSpacing(0);
auto* bubble = new QFrame(rowWidget);
bubble->setMaximumWidth(qMin(320, qMax(220, m_scrollArea->viewport()->width() - 36)));
QColor background = m_tokens.cardBackground;
QColor border = m_tokens.cardBorder;
QColor textColor = m_tokens.textPrimary;
if (entry.kind == EntryKind::User)
{
background = m_tokens.accent;
border = m_tokens.accent;
textColor = m_tokens.onAccent;
}
else if (entry.kind == EntryKind::Error)
{
background = m_tokens.blockOverdueFill;
border = m_tokens.blockOverdueBorder;
textColor = m_tokens.blockOverdueBorder;
}
bubble->setStyleSheet(
QStringLiteral("QFrame{background:%1;border:1px solid %2;border-radius:10px;}")
.arg(background.name(), border.name()));
auto* bubbleLayout = new QVBoxLayout(bubble);
bubbleLayout->setContentsMargins(11, 8, 11, 8);
bubbleLayout->setSpacing(0);
auto* label = new QLabel(entry.text.isEmpty() ? QStringLiteral(" ") : entry.text, bubble);
label->setWordWrap(true);
label->setTextInteractionFlags(Qt::TextSelectableByMouse);
label->setStyleSheet(QStringLiteral("background:transparent;border:none;color:%1;font-size:12px;")
.arg(textColor.name()));
bubbleLayout->addWidget(label);
m_labels.insert(entry.id, label);
if (entry.kind == EntryKind::User)
{
row->addStretch(1);
row->addWidget(bubble);
}
else
{
row->addWidget(bubble);
row->addStretch(1);
}
m_messageLayout->addWidget(rowWidget);
}
m_messageLayout->addStretch(1);
scrollToBottom();
}
void ChatPanel::addEntry(Entry entry, bool rebuild)
{
if (entry.id.isEmpty())
{
entry.id = QStringLiteral("entry-%1").arg(m_nextEntryId++);
}
m_entries.append(std::move(entry));
if (rebuild)
{
rebuildMessages();
}
}
void ChatPanel::startRequest(const QString& text, const QStringList& paths)
{
if (m_busy)
{
return;
}
QString displayText = text;
if (!paths.isEmpty())
{
QStringList names;
for (const QString& path : paths)
{
names.append(QFileInfo(path).fileName());
}
if (!displayText.isEmpty())
{
displayText += QLatin1Char('\n');
}
displayText += QStringLiteral("附件:") + names.join(QStringLiteral("、"));
}
Entry userEntry;
userEntry.kind = EntryKind::User;
userEntry.text = displayText;
m_entries.append(userEntry);
Entry assistantEntry;
assistantEntry.id = QStringLiteral("entry-%1").arg(m_nextEntryId++);
assistantEntry.kind = EntryKind::Assistant;
assistantEntry.text = QStringLiteral("正在思考…");
assistantEntry.streaming = true;
assistantEntry.placeholder = true;
m_streamingId = assistantEntry.id;
m_entries.append(assistantEntry);
setBusy(true);
m_input->clear();
rebuildMessages();
m_aiService.request(text, paths);
}
void ChatPanel::sendCurrentInput()
{
if (m_busy)
{
return;
}
const QString text = m_input->text().trimmed();
if (text.isEmpty())
{
return;
}
startRequest(text, {});
}
void ChatPanel::onStreamDelta(const QString& delta)
{
const int index = findEntry(m_streamingId);
if (index < 0)
{
return;
}
Entry& entry = m_entries[index];
if (entry.placeholder)
{
entry.text = delta;
entry.placeholder = false;
}
else
{
entry.text += delta;
}
entry.streaming = true;
auto label = m_labels.find(entry.id);
if (label != m_labels.end())
{
label.value()->setText(entry.text);
scrollToBottom();
}
else
{
rebuildMessages();
}
}
void ChatPanel::onRequestFinished()
{
const int index = findEntry(m_streamingId);
if (index >= 0)
{
Entry& entry = m_entries[index];
if (entry.placeholder && entry.text == QStringLiteral("正在思考…"))
{
entry.text = QStringLiteral("(没有返回内容)");
}
entry.streaming = false;
entry.placeholder = false;
}
m_streamingId.clear();
setBusy(false);
rebuildMessages();
}
void ChatPanel::onRequestFailed(const QString& message)
{
bool hadContent = false;
const int index = findEntry(m_streamingId);
if (index >= 0)
{
Entry& entry = m_entries[index];
hadContent = !entry.placeholder && !entry.text.trimmed().isEmpty();
entry.streaming = false;
entry.placeholder = false;
if (!hadContent)
{
entry.kind = EntryKind::Error;
entry.text = QStringLiteral("错误:") + message;
}
}
if (hadContent || index < 0)
{
Entry error;
error.kind = EntryKind::Error;
error.text = QStringLiteral("错误:") + message;
m_entries.append(error);
}
m_streamingId.clear();
setBusy(false);
rebuildMessages();
}
void ChatPanel::onProposalReady(const ScheduleProposal& proposal)
{
Entry entry;
entry.kind = EntryKind::Proposal;
entry.proposal = proposal;
entry.proposalState = ProposalState::Pending;
m_entries.append(entry);
rebuildMessages();
}
void ChatPanel::onNotice(const QString& message)
{
Entry entry;
entry.kind = EntryKind::System;
entry.text = message;
m_entries.append(entry);
rebuildMessages();
}
void ChatPanel::onDiffApplied(const QString& diffId, int count)
{
Q_UNUSED(count)
const int index = findProposal(diffId);
if (index >= 0)
{
m_entries[index].proposalState = ProposalState::Applied;
rebuildMessages();
}
}
void ChatPanel::onDiffRejected(const QString& diffId)
{
const int index = findProposal(diffId);
if (index >= 0)
{
m_entries[index].proposalState = ProposalState::Rejected;
rebuildMessages();
}
}
void ChatPanel::onDiffApplyFailed(const QString& diffId, const QString& message)
{
Q_UNUSED(diffId)
const int index = findProposal(diffId);
if (index >= 0)
{
// 应用失败时恢复为待确认状态,让用户可以重试。
m_entries[index].proposalState = ProposalState::Pending;
}
Entry error;
error.kind = EntryKind::Error;
error.text = QStringLiteral("应用日程失败:") + message;
m_entries.append(error);
rebuildMessages();
}
void ChatPanel::setBusy(bool busy)
{
m_busy = busy;
if (m_input)
{
m_input->setEnabled(!busy);
}
if (m_sendButton)
{
m_sendButton->setEnabled(!busy);
}
}
void ChatPanel::scrollToBottom()
{
QTimer::singleShot(0, this, [this]() {
if (m_scrollArea && m_scrollArea->verticalScrollBar())
{
m_scrollArea->verticalScrollBar()->setValue(m_scrollArea->verticalScrollBar()->maximum());
}
});
QTimer::singleShot(40, this, [this]() {
if (m_scrollArea && m_scrollArea->verticalScrollBar())
{
m_scrollArea->verticalScrollBar()->setValue(m_scrollArea->verticalScrollBar()->maximum());
}
});
}
int ChatPanel::findEntry(const QString& id) const
{
if (id.isEmpty())
{
return -1;
}
for (int i = 0; i < m_entries.size(); ++i)
{
if (m_entries.at(i).id == id)
{
return i;
}
}
return -1;
}
int ChatPanel::findProposal(const QString& diffId) const
{
for (int i = 0; i < m_entries.size(); ++i)
{
const Entry& entry = m_entries.at(i);
if (entry.kind == EntryKind::Proposal && entry.proposal.diffId == diffId)
{
return i;
}
}
return -1;
}
void ChatPanel::dragEnterEvent(QDragEnterEvent* event)
{
if (event->mimeData()->hasUrls())
{
event->acceptProposedAction();
return;
}
QWidget::dragEnterEvent(event);
}
void ChatPanel::dropEvent(QDropEvent* event)
{
if (!event->mimeData()->hasUrls())
{
QWidget::dropEvent(event);
return;
}
QStringList paths;
for (const QUrl& url : event->mimeData()->urls())
{
if (url.isLocalFile())
{
paths.append(url.toLocalFile());
}
}
if (paths.isEmpty())
{
return;
}
if (m_busy)
{
Entry entry;
entry.kind = EntryKind::System;
entry.text = QStringLiteral("上一条消息还在处理中,请稍后再拖入文件。");
m_entries.append(entry);
rebuildMessages();
event->acceptProposedAction();
return;
}
startRequest(QStringLiteral("请分析附件内容,提取需要安排的任务。"), paths);
event->acceptProposedAction();
}
+99
View File
@@ -0,0 +1,99 @@
#pragma once
#include <QDateTime>
#include <QHash>
#include <QVector>
#include <QWidget>
#include "ai/ScheduleProposal.h"
#include "ui/theme/ThemeTokens.h"
class AIService;
class ElaLineEdit;
class ElaPushButton;
class ElaScrollArea;
class ElaText;
class QLabel;
class QVBoxLayout;
/*
* 类名: ChatPanel
* 功能: AI 对话面板:流式消息、文件拖入、日程 Diff 卡片与接受/拒绝
* 线程安全: 否;UI 线程
*/
class ChatPanel : public QWidget
{
Q_OBJECT
public:
explicit ChatPanel(AIService& aiService, QWidget* parent = nullptr);
void setTokens(const ThemeTokens& tokens);
protected:
void dragEnterEvent(QDragEnterEvent* event) override;
void dropEvent(QDropEvent* event) override;
private:
enum class EntryKind
{
User,
Assistant,
System,
Error,
Proposal,
};
enum class ProposalState
{
Pending,
Applied,
Rejected,
};
struct Entry
{
EntryKind kind = EntryKind::System;
QString id;
QString text;
ScheduleProposal proposal;
ProposalState proposalState = ProposalState::Pending;
bool streaming = false;
bool placeholder = false;
};
void rebuildMessages();
void addEntry(Entry entry, bool rebuild = true);
void startRequest(const QString& text, const QStringList& paths);
void sendCurrentInput();
void onStreamDelta(const QString& delta);
void onRequestFinished();
void onRequestFailed(const QString& message);
void onProposalReady(const ScheduleProposal& proposal);
void onNotice(const QString& message);
void onDiffApplied(const QString& diffId, int count);
void onDiffRejected(const QString& diffId);
void onDiffApplyFailed(const QString& diffId, const QString& message);
void setBusy(bool busy);
void scrollToBottom();
void applyBadgeStyle();
int findEntry(const QString& id) const;
int findProposal(const QString& diffId) const;
static void clearLayout(QVBoxLayout* layout);
AIService& m_aiService;
ThemeTokens m_tokens;
QVector<Entry> m_entries;
QHash<QString, QLabel*> m_labels;
QString m_streamingId;
bool m_busy = false;
int m_nextEntryId = 1;
ElaText* m_titleLabel = nullptr;
QLabel* m_badgeLabel = nullptr;
ElaScrollArea* m_scrollArea = nullptr;
QWidget* m_messageWidget = nullptr;
QVBoxLayout* m_messageLayout = nullptr;
ElaLineEdit* m_input = nullptr;
ElaPushButton* m_sendButton = nullptr;
};
+329
View File
@@ -0,0 +1,329 @@
#include "DiffPreviewCard.h"
#include <QHBoxLayout>
#include <QLabel>
#include <QVBoxLayout>
#include "ElaCheckBox.h"
#include "ElaPushButton.h"
#include "core/DateTimeUtils.h"
namespace
{
QString operationLabel(ProposedOperation operation)
{
switch (operation)
{
case ProposedOperation::Update:
return QStringLiteral("修改");
case ProposedOperation::Delete:
return QStringLiteral("删除");
case ProposedOperation::Create:
default:
return QStringLiteral("新增");
}
}
QColor operationColor(ProposedOperation operation, const ThemeTokens& tokens)
{
switch (operation)
{
case ProposedOperation::Update:
return tokens.diffModify;
case ProposedOperation::Delete:
return tokens.diffDelete;
case ProposedOperation::Create:
default:
return tokens.diffAdd;
}
}
QString formatTime(const QDateTime& start, const QDateTime& end)
{
if (!start.isValid() || !end.isValid())
{
return {};
}
QString text = start.toString(QStringLiteral("M月d日 HH:mm"));
text += QStringLiteral("–");
text += start.date() == end.date() ? end.toString(QStringLiteral("HH:mm"))
: end.toString(QStringLiteral("M月d日 HH:mm"));
const int minutes = qMax(0, DateTimeUtils::minutesBetween(start, end));
if (minutes > 0)
{
text += QStringLiteral(" · ") + DateTimeUtils::formatDuration(minutes);
}
return text;
}
} // namespace
DiffPreviewCard::DiffPreviewCard(const ScheduleProposal& proposal,
const ThemeTokens& tokens,
State state,
QWidget* parent)
: QFrame(parent)
, m_proposal(proposal)
, m_tokens(tokens)
, m_state(state)
{
setObjectName(QStringLiteral("DiffPreviewCard"));
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
QColor border = m_tokens.accent;
if (state == State::Applied)
{
border = m_tokens.success;
}
else if (state == State::Rejected)
{
border = m_tokens.textMuted;
}
setStyleSheet(QStringLiteral(
"QFrame#DiffPreviewCard{background:%1;border:1px solid %2;border-radius:10px;}")
.arg(m_tokens.cardBackground.name(), border.name()));
auto* root = new QVBoxLayout(this);
root->setContentsMargins(12, 10, 12, 10);
root->setSpacing(7);
int creates = 0;
int updates = 0;
int deletes = 0;
for (const ProposedScheduleEntry& entry : proposal.entries)
{
switch (entry.operation)
{
case ProposedOperation::Update:
++updates;
break;
case ProposedOperation::Delete:
++deletes;
break;
case ProposedOperation::Create:
default:
++creates;
break;
}
}
QStringList parts;
if (creates > 0)
{
parts.append(QStringLiteral("新增 %1").arg(creates));
}
if (updates > 0)
{
parts.append(QStringLiteral("修改 %1").arg(updates));
}
if (deletes > 0)
{
parts.append(QStringLiteral("删除 %1").arg(deletes));
}
auto* header = new QHBoxLayout();
header->setSpacing(8);
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);
count->setStyleSheet(QStringLiteral("background:transparent;border:none;color:%1;font-size:11px;")
.arg(m_tokens.textMuted.name()));
header->addWidget(title);
header->addStretch(1);
header->addWidget(count);
root->addLayout(header);
for (const ProposedScheduleEntry& entry : proposal.entries)
{
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);
auto* textLayout = new QVBoxLayout();
textLayout->setSpacing(1);
auto* titleRow = new QHBoxLayout();
titleRow->setSpacing(6);
const QColor color = operationColor(entry.operation, m_tokens);
auto* opLabel = new QLabel(operationLabel(entry.operation), this);
opLabel->setStyleSheet(QStringLiteral("background:transparent;border:none;color:%1;font-size:10px;font-weight:600;")
.arg(color.name()));
auto* titleLabel = new QLabel(entry.operation == ProposedOperation::Delete ? entry.oldTitle : entry.title,
this);
titleLabel->setWordWrap(true);
titleLabel->setStyleSheet(QStringLiteral("background:transparent;border:none;color:%1;font-size:12px;font-weight:600;")
.arg(entry.operation == ProposedOperation::Delete
? m_tokens.textMuted.name()
: m_tokens.textPrimary.name()));
if (entry.operation == ProposedOperation::Delete)
{
QFont font = titleLabel->font();
font.setStrikeOut(true);
titleLabel->setFont(font);
}
titleRow->addWidget(opLabel, 0, Qt::AlignTop);
titleRow->addWidget(titleLabel, 1);
textLayout->addLayout(titleRow);
if (entry.operation == ProposedOperation::Update && entry.oldTitle != entry.title &&
!entry.oldTitle.isEmpty())
{
auto* oldTitle = new QLabel(QStringLiteral("原:%1").arg(entry.oldTitle), this);
oldTitle->setWordWrap(true);
oldTitle->setStyleSheet(QStringLiteral("background:transparent;border:none;color:%1;font-size:11px;")
.arg(m_tokens.textMuted.name()));
textLayout->addWidget(oldTitle);
}
if (entry.operation == ProposedOperation::Update)
{
auto* oldTime = new QLabel(formatTime(entry.oldStartAt, entry.oldEndAt), this);
oldTime->setStyleSheet(QStringLiteral("background:transparent;border:none;color:%1;font-size:11px;")
.arg(m_tokens.textMuted.name()));
auto* newTime = new QLabel(formatTime(entry.startAt, entry.endAt), this);
newTime->setStyleSheet(QStringLiteral("background:transparent;border:none;color:%1;font-size:11px;")
.arg(color.name()));
textLayout->addWidget(oldTime);
textLayout->addWidget(newTime);
}
else if (entry.operation == ProposedOperation::Delete)
{
auto* oldTime = new QLabel(formatTime(entry.oldStartAt, entry.oldEndAt), this);
oldTime->setStyleSheet(QStringLiteral("background:transparent;border:none;color:%1;font-size:11px;")
.arg(m_tokens.textMuted.name()));
textLayout->addWidget(oldTime);
}
else
{
if (entry.segments.isEmpty())
{
auto* newTime = new QLabel(formatTime(entry.startAt, entry.endAt), this);
newTime->setStyleSheet(QStringLiteral("background:transparent;border:none;color:%1;font-size:11px;")
.arg(m_tokens.textSecondary.name()));
textLayout->addWidget(newTime);
}
else
{
if (entry.segments.size() > 1)
{
auto* splitLabel = new QLabel(QStringLiteral("拆分为 %1 段").arg(entry.segments.size()), this);
splitLabel->setStyleSheet(
QStringLiteral("background:transparent;border:none;color:%1;font-size:11px;")
.arg(m_tokens.diffModify.name()));
textLayout->addWidget(splitLabel);
}
for (const ProposedTimeSegment& segment : entry.segments)
{
auto* newTime = new QLabel(formatTime(segment.startAt, segment.endAt), this);
newTime->setStyleSheet(
QStringLiteral("background:transparent;border:none;color:%1;font-size:11px;")
.arg(m_tokens.textSecondary.name()));
textLayout->addWidget(newTime);
}
}
}
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);
m_rejectButton = new ElaPushButton(QStringLiteral("全部拒绝"), this);
m_rejectButton->setFixedSize(88, 30);
m_acceptButton = new ElaPushButton(QStringLiteral("接受选中"), this);
m_acceptButton->setFixedSize(92, 30);
m_statusLabel = new QLabel(this);
m_statusLabel->setStyleSheet(
QStringLiteral("background:transparent;border:none;color:%1;font-size:12px;font-weight:600;")
.arg(border.name()));
m_statusLabel->hide();
buttonRow->addWidget(m_statusLabel);
buttonRow->addWidget(m_rejectButton);
buttonRow->addWidget(m_acceptButton);
root->addLayout(buttonRow);
connect(m_acceptButton, &ElaPushButton::clicked, this, [this]() {
if (m_state != State::Pending)
{
return;
}
QStringList tempIds;
for (int i = 0; i < m_checks.size(); ++i)
{
if (m_checks.at(i)->isChecked() && i < m_proposal.entries.size())
{
tempIds.append(m_proposal.entries.at(i).tempId);
}
}
setResolved(State::Applied);
Q_EMIT accepted(m_proposal.diffId, tempIds);
});
connect(m_rejectButton, &ElaPushButton::clicked, this, [this]() {
if (m_state != State::Pending)
{
return;
}
setResolved(State::Rejected);
Q_EMIT rejected(m_proposal.diffId);
});
updateAcceptEnabled();
if (state != State::Pending)
{
setResolved(state);
}
}
void DiffPreviewCard::updateAcceptEnabled()
{
if (m_state != State::Pending)
{
return;
}
bool any = false;
for (ElaCheckBox* check : m_checks)
{
if (check->isChecked())
{
any = true;
break;
}
}
if (m_acceptButton)
{
m_acceptButton->setEnabled(any);
}
}
void DiffPreviewCard::setResolved(State state)
{
m_state = state;
for (ElaCheckBox* check : m_checks)
{
check->setEnabled(false);
}
if (m_acceptButton)
{
m_acceptButton->hide();
}
if (m_rejectButton)
{
m_rejectButton->hide();
}
if (m_statusLabel)
{
m_statusLabel->setText(state == State::Applied ? QStringLiteral("已应用")
: QStringLiteral("已拒绝"));
m_statusLabel->setStyleSheet(
QStringLiteral("background:transparent;border:none;color:%1;font-size:12px;font-weight:600;")
.arg(state == State::Applied ? m_tokens.success.name() : m_tokens.textMuted.name()));
m_statusLabel->show();
}
}
+51
View File
@@ -0,0 +1,51 @@
#pragma once
#include <QFrame>
#include <QStringList>
#include <QVector>
#include "ai/ScheduleProposal.h"
#include "ui/theme/ThemeTokens.h"
class ElaCheckBox;
class ElaPushButton;
class QLabel;
/*
* 类名: DiffPreviewCard
* 功能: AI 日程建议卡片;支持逐条勾选后接受或全部拒绝
* 线程安全: 否;UI 线程
*/
class DiffPreviewCard : public QFrame
{
Q_OBJECT
public:
enum class State
{
Pending,
Applied,
Rejected,
};
DiffPreviewCard(const ScheduleProposal& proposal,
const ThemeTokens& tokens,
State state,
QWidget* parent = nullptr);
signals:
void accepted(const QString& diffId, const QStringList& tempIds);
void rejected(const QString& diffId);
private:
void updateAcceptEnabled();
void setResolved(State state);
ScheduleProposal m_proposal;
ThemeTokens m_tokens;
State m_state;
QVector<ElaCheckBox*> m_checks;
ElaPushButton* m_acceptButton = nullptr;
ElaPushButton* m_rejectButton = nullptr;
QLabel* m_statusLabel = nullptr;
};
+216
View File
@@ -0,0 +1,216 @@
#include "TodayItemCard.h"
#include <QAction>
#include <algorithm>
#include <QEnterEvent>
#include <QFontMetrics>
#include <QHBoxLayout>
#include <QMouseEvent>
#include <QPainter>
#include <QPainterPath>
#include <QToolButton>
#include "ElaMenu.h"
#include "ElaToolButton.h"
#include "core/DateTimeUtils.h"
TodayItemCard::TodayItemCard(const ScheduleItem& item,
const ThemeTokens& tokens,
const QDateTime& now,
QWidget* parent)
: QFrame(parent)
, m_item(item)
, m_tokens(tokens)
, m_now(now)
{
setObjectName(QStringLiteral("TodayItemCard"));
setAttribute(Qt::WA_Hover, true);
setCursor(Qt::PointingHandCursor);
setMinimumHeight(66);
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
auto* row = new QHBoxLayout(this);
row->setContentsMargins(0, 8, 8, 8);
row->setSpacing(2);
row->addStretch(1);
m_completeButton = new ElaToolButton(this);
m_completeButton->setIsTransparent(true);
m_completeButton->setFixedSize(28, 28);
const bool done = m_item.block.status == QStringLiteral("done");
m_completeButton->setElaIcon(done ? ElaIconType::RotateLeft : ElaIconType::Check);
m_completeButton->setToolTip(done ? QStringLiteral("标记未完成") : QStringLiteral("标记完成"));
m_completeButton->setCursor(Qt::PointingHandCursor);
connect(m_completeButton, &ElaToolButton::clicked, this, [this, done]() {
Q_EMIT statusChangeRequested(m_item.block.id,
done ? QStringLiteral("scheduled") : QStringLiteral("done"));
});
row->addWidget(m_completeButton, 0, Qt::AlignVCenter);
m_menuButton = new ElaToolButton(this);
m_menuButton->setIsTransparent(true);
m_menuButton->setFixedSize(28, 28);
m_menuButton->setElaIcon(ElaIconType::EllipsisVertical);
m_menuButton->setToolTip(QStringLiteral("更多操作"));
m_menuButton->setCursor(Qt::PointingHandCursor);
row->addWidget(m_menuButton, 0, Qt::AlignVCenter);
buildActions();
}
void TodayItemCard::buildActions()
{
auto* menu = new ElaMenu(this);
QAction* editAction = menu->addAction(QStringLiteral("编辑"));
connect(editAction, &QAction::triggered, this, [this]() { Q_EMIT editRequested(m_item.block.id); });
const bool done = m_item.block.status == QStringLiteral("done");
QAction* doneAction = menu->addAction(done ? QStringLiteral("标记未完成") : QStringLiteral("标记完成"));
connect(doneAction, &QAction::triggered, this, [this, done]() {
Q_EMIT statusChangeRequested(m_item.block.id,
done ? QStringLiteral("scheduled") : QStringLiteral("done"));
});
menu->addSeparator();
QAction* postpone15 = menu->addAction(QStringLiteral("延后 15 分钟"));
connect(postpone15, &QAction::triggered, this, [this]() {
Q_EMIT postponeRequested(m_item.block.id, 15);
});
QAction* postpone60 = menu->addAction(QStringLiteral("延后 1 小时"));
connect(postpone60, &QAction::triggered, this, [this]() {
Q_EMIT postponeRequested(m_item.block.id, 60);
});
menu->addSeparator();
QAction* dropAction = menu->addAction(QStringLiteral("放弃此日程"));
connect(dropAction, &QAction::triggered, this, [this]() {
Q_EMIT statusChangeRequested(m_item.block.id, QStringLiteral("dropped"));
});
QAction* deleteAction = menu->addAction(QStringLiteral("删除"));
connect(deleteAction, &QAction::triggered, this, [this]() {
Q_EMIT deleteRequested(m_item.block.id);
});
m_menuButton->setMenu(menu);
m_menuButton->setPopupMode(QToolButton::InstantPopup);
}
void TodayItemCard::paintEvent(QPaintEvent* event)
{
Q_UNUSED(event)
const bool done = m_item.block.status == QStringLiteral("done");
const bool dropped =
m_item.block.status == QStringLiteral("dropped") || m_item.block.status == QStringLiteral("missed");
const bool overdue = !done && !dropped && m_item.block.endAt < m_now;
QColor border = m_tokens.cardBorder;
if (overdue)
{
border = m_tokens.blockOverdueBorder;
}
else if (done)
{
border = m_tokens.blockDoneBorder;
}
QColor stripe = m_tokens.accent;
if (done)
{
stripe = m_tokens.success;
}
else if (dropped)
{
stripe = m_tokens.blockDroppedBorder;
}
else if (overdue)
{
stripe = m_tokens.blockOverdueBorder;
}
else if (m_item.block.status == QStringLiteral("in_progress"))
{
stripe = m_tokens.warning;
}
QPainter painter(this);
painter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing);
const QRectF cardRect = QRectF(rect()).adjusted(0.5, 0.5, -0.5, -0.5);
QPainterPath cardPath;
cardPath.addRoundedRect(cardRect, 9, 9);
painter.fillPath(cardPath, m_hovered ? m_tokens.cardHoverBackground : m_tokens.cardBackground);
painter.setPen(QPen(border, overdue ? 1.4 : 1.0));
painter.setBrush(Qt::NoBrush);
painter.drawPath(cardPath);
painter.setPen(Qt::NoPen);
painter.setBrush(stripe);
painter.drawRoundedRect(QRectF(10, 11, 3, height() - 22), 1.5, 1.5);
const int textX = 21;
const int textWidth = std::max(20, width() - textX - 76);
QFont titleFont = painter.font();
titleFont.setPixelSize(13);
titleFont.setWeight(QFont::DemiBold);
titleFont.setStrikeOut(done || dropped);
painter.setFont(titleFont);
const QFontMetrics titleMetrics(titleFont);
const QString title =
titleMetrics.elidedText(m_item.task.title, Qt::ElideRight, textWidth);
painter.setPen(done || dropped ? m_tokens.textSecondary : m_tokens.textPrimary);
painter.drawText(QRectF(textX, 9, textWidth, 19), Qt::AlignLeft | Qt::AlignVCenter, title);
QFont timeFont = painter.font();
timeFont.setPixelSize(11);
timeFont.setWeight(QFont::Normal);
timeFont.setStrikeOut(false);
painter.setFont(timeFont);
const int minutes = std::max(0, DateTimeUtils::minutesBetween(m_item.block.startAt, m_item.block.endAt));
QString subtitle = DateTimeUtils::formatTimeRange(m_item.block.startAt, m_item.block.endAt);
if (minutes > 0)
{
subtitle += QStringLiteral(" · ") + DateTimeUtils::formatDuration(minutes);
}
if (overdue)
{
subtitle += QStringLiteral(" · 已超时");
}
else if (done)
{
subtitle += QStringLiteral(" · 已完成");
}
else if (dropped)
{
subtitle += QStringLiteral(" · 已放弃");
}
const QFontMetrics timeMetrics(timeFont);
subtitle = timeMetrics.elidedText(subtitle, Qt::ElideRight, textWidth);
painter.setPen(overdue ? m_tokens.blockOverdueBorder : m_tokens.textSecondary);
painter.drawText(QRectF(textX, 30, textWidth, 17), Qt::AlignLeft | Qt::AlignVCenter, subtitle);
}
void TodayItemCard::enterEvent(QEnterEvent* event)
{
m_hovered = true;
update();
QFrame::enterEvent(event);
}
void TodayItemCard::leaveEvent(QEvent* event)
{
m_hovered = false;
update();
QFrame::leaveEvent(event);
}
void TodayItemCard::mouseReleaseEvent(QMouseEvent* event)
{
if (event->button() == Qt::LeftButton && rect().contains(event->position().toPoint()))
{
Q_EMIT clicked(m_item.block.id);
event->accept();
return;
}
QFrame::mouseReleaseEvent(event);
}
+48
View File
@@ -0,0 +1,48 @@
#pragma once
#include <QDateTime>
#include <QFrame>
#include "core/ScheduleItem.h"
#include "ui/theme/ThemeTokens.h"
class ElaToolButton;
/*
* 类名: TodayItemCard
* 功能: 今日任务面板中的单条日程卡片,自绘文本并提供快捷操作
* 线程安全: 否;UI 线程
*/
class TodayItemCard : public QFrame
{
Q_OBJECT
public:
TodayItemCard(const ScheduleItem& item,
const ThemeTokens& tokens,
const QDateTime& now,
QWidget* parent = nullptr);
signals:
void clicked(const QString& blockId);
void editRequested(const QString& blockId);
void statusChangeRequested(const QString& blockId, const QString& status);
void postponeRequested(const QString& blockId, int minutes);
void deleteRequested(const QString& blockId);
protected:
void paintEvent(QPaintEvent* event) override;
void enterEvent(QEnterEvent* event) override;
void leaveEvent(QEvent* event) override;
void mouseReleaseEvent(QMouseEvent* event) override;
private:
void buildActions();
ScheduleItem m_item;
ThemeTokens m_tokens;
QDateTime m_now;
bool m_hovered = false;
ElaToolButton* m_completeButton = nullptr;
ElaToolButton* m_menuButton = nullptr;
};
+193
View File
@@ -0,0 +1,193 @@
#include "TodayPanel.h"
#include <QFrame>
#include <QHBoxLayout>
#include <QLayoutItem>
#include <QScrollBar>
#include <QVBoxLayout>
#include <algorithm>
#include "ElaScrollArea.h"
#include "ElaText.h"
#include "TodayItemCard.h"
TodayPanel::TodayPanel(QWidget* parent)
: QWidget(parent)
{
setMinimumWidth(272);
setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);
auto* root = new QVBoxLayout(this);
root->setContentsMargins(12, 10, 12, 12);
root->setSpacing(10);
auto* header = new QHBoxLayout();
header->setContentsMargins(2, 0, 2, 0);
header->setSpacing(6);
m_titleLabel = new ElaText(QStringLiteral("当日任务"), 15, this);
QFont titleFont = m_titleLabel->font();
titleFont.setWeight(QFont::DemiBold);
m_titleLabel->setFont(titleFont);
m_countLabel = new ElaText(this);
m_countLabel->setTextPixelSize(11);
header->addWidget(m_titleLabel);
header->addStretch(1);
header->addWidget(m_countLabel, 0, Qt::AlignVCenter);
root->addLayout(header);
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_listWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
m_listLayout = new QVBoxLayout(m_listWidget);
m_listLayout->setContentsMargins(0, 0, 2, 0);
m_listLayout->setSpacing(8);
m_listLayout->addStretch(1);
m_scrollArea->setWidget(m_listWidget);
root->addWidget(m_scrollArea, 1);
}
void TodayPanel::setTokens(const ThemeTokens& tokens)
{
m_tokens = tokens;
rebuild();
}
void TodayPanel::setDate(const QDate& date)
{
if (!m_titleLabel)
{
return;
}
if (!date.isValid() || date == QDate::currentDate())
{
m_titleLabel->setText(QStringLiteral("今日任务"));
return;
}
m_titleLabel->setText(QStringLiteral("%1月%2日任务").arg(date.month()).arg(date.day()));
}
void TodayPanel::setItems(const QVector<ScheduleItem>& items, const QDateTime& now)
{
m_items = items;
m_now = now;
rebuild();
}
void TodayPanel::clearLayout(QVBoxLayout* layout)
{
while (QLayoutItem* item = layout->takeAt(0))
{
if (QWidget* widget = item->widget())
{
delete widget;
}
// addLayout 时 QLayout 本身即 QLayoutItem,直接 delete 可避免二次释放。
delete item;
}
}
void TodayPanel::rebuild()
{
if (!m_listLayout)
{
return;
}
clearLayout(m_listLayout);
const QDateTime now = m_now.isValid() ? m_now : QDateTime::currentDateTime();
int activeCount = 0;
int overdueCount = 0;
for (const ScheduleItem& item : m_items)
{
if (item.block.status == QStringLiteral("scheduled") || item.block.status == QStringLiteral("in_progress"))
{
++activeCount;
if (item.block.endAt < now)
{
++overdueCount;
}
}
}
if (overdueCount > 0)
{
m_countLabel->setText(QStringLiteral("%1 项待办 · %2 项超时").arg(activeCount).arg(overdueCount));
}
else if (activeCount > 0)
{
m_countLabel->setText(QStringLiteral("%1 项待办").arg(activeCount));
}
else
{
m_countLabel->setText(QStringLiteral("全部完成"));
}
QVector<ScheduleItem> sorted = m_items;
std::sort(sorted.begin(), sorted.end(), [&now](const ScheduleItem& a, const ScheduleItem& b) {
const auto rank = [&now](const ScheduleItem& item) {
const QString& status = item.block.status;
if (status == QStringLiteral("dropped") || status == QStringLiteral("missed"))
{
return 4;
}
if (status == QStringLiteral("done"))
{
return 3;
}
if (item.block.endAt < now)
{
return 0;
}
if (status == QStringLiteral("in_progress"))
{
return 1;
}
return 2;
};
const int rankA = rank(a);
const int rankB = rank(b);
if (rankA != rankB)
{
return rankA < rankB;
}
if (a.block.startAt != b.block.startAt)
{
return a.block.startAt < b.block.startAt;
}
return a.block.id < b.block.id;
});
if (sorted.isEmpty())
{
auto* empty = new ElaText(QStringLiteral("今天还没有安排\n双击时间网格即可新建"), 13, m_listWidget);
empty->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
empty->setMinimumHeight(120);
empty->setTextStyle(ElaTextType::Caption);
m_listLayout->addWidget(empty);
m_listLayout->addStretch(1);
return;
}
for (const ScheduleItem& item : sorted)
{
auto* card = new TodayItemCard(item, m_tokens, now, m_listWidget);
connect(card, &TodayItemCard::clicked, this, &TodayPanel::focusRequested);
connect(card, &TodayItemCard::editRequested, this, &TodayPanel::editRequested);
connect(card, &TodayItemCard::statusChangeRequested, this, &TodayPanel::statusChangeRequested);
connect(card, &TodayItemCard::postponeRequested, this, &TodayPanel::postponeRequested);
connect(card, &TodayItemCard::deleteRequested, this, &TodayPanel::deleteRequested);
m_listLayout->addWidget(card);
}
m_listLayout->addStretch(1);
}
+50
View File
@@ -0,0 +1,50 @@
#pragma once
#include <QDateTime>
#include <QVector>
#include <QWidget>
#include "core/ScheduleItem.h"
#include "ui/theme/ThemeTokens.h"
class ElaScrollArea;
class ElaText;
class QVBoxLayout;
/*
* 类名: TodayPanel
* 功能: 今日任务列表;展示超时/未完成/已完成并提供快捷操作
* 线程安全: 否;UI 线程
*/
class TodayPanel : public QWidget
{
Q_OBJECT
public:
explicit TodayPanel(QWidget* parent = nullptr);
void setTokens(const ThemeTokens& tokens);
void setDate(const QDate& date);
void setItems(const QVector<ScheduleItem>& items, const QDateTime& now);
signals:
void editRequested(const QString& blockId);
void statusChangeRequested(const QString& blockId, const QString& status);
void postponeRequested(const QString& blockId, int minutes);
void deleteRequested(const QString& blockId);
void focusRequested(const QString& blockId);
private:
void rebuild();
static void clearLayout(QVBoxLayout* layout);
ThemeTokens m_tokens;
QVector<ScheduleItem> m_items;
QDateTime m_now;
ElaText* m_titleLabel = nullptr;
ElaText* m_countLabel = nullptr;
ElaScrollArea* m_scrollArea = nullptr;
QWidget* m_listWidget = nullptr;
QVBoxLayout* m_listLayout = nullptr;
};
+257
View File
@@ -0,0 +1,257 @@
#include "ThemeManager.h"
#include <QApplication>
#include <QGuiApplication>
#include <QPalette>
#include <QStyleHints>
#include "ElaTheme.h"
#include "utils/AppSettings.h"
namespace
{
ThemeManager::Preference preferenceFromString(const QString& value)
{
if (value == QStringLiteral("light"))
{
return ThemeManager::Preference::Light;
}
if (value == QStringLiteral("dark"))
{
return ThemeManager::Preference::Dark;
}
return ThemeManager::Preference::System;
}
QString preferenceToString(ThemeManager::Preference preference)
{
switch (preference)
{
case ThemeManager::Preference::Light:
return QStringLiteral("light");
case ThemeManager::Preference::Dark:
return QStringLiteral("dark");
case ThemeManager::Preference::System:
default:
return QStringLiteral("system");
}
}
} // namespace
ThemeManager::ThemeManager(AppSettings& settings, QObject* parent)
: QObject(parent)
, m_settings(settings)
, m_preference(preferenceFromString(settings.themePreference()))
{
m_tokens = buildTokens(false);
}
void ThemeManager::initialize()
{
connect(QGuiApplication::styleHints(), &QStyleHints::colorSchemeChanged, this, [this]() {
if (m_preference == Preference::System)
{
apply();
}
});
apply();
}
ThemeManager::Preference ThemeManager::preference() const
{
return m_preference;
}
void ThemeManager::setPreference(Preference preference)
{
if (m_preference == preference)
{
return;
}
m_preference = preference;
m_settings.setThemePreference(preferenceToString(preference));
Q_EMIT preferenceChanged(m_preference);
apply();
}
void ThemeManager::cyclePreference()
{
switch (m_preference)
{
case Preference::System:
setPreference(Preference::Light);
break;
case Preference::Light:
setPreference(Preference::Dark);
break;
case Preference::Dark:
setPreference(Preference::System);
break;
}
}
ElaThemeType::ThemeMode ThemeManager::mode() const
{
return m_mode;
}
const ThemeTokens& ThemeManager::tokens() const
{
return m_tokens;
}
QString ThemeManager::preferenceLabel(Preference preference)
{
switch (preference)
{
case Preference::Light:
return QStringLiteral("浅色");
case Preference::Dark:
return QStringLiteral("深色");
case Preference::System:
default:
return QStringLiteral("跟随系统");
}
}
void ThemeManager::apply()
{
bool dark = false;
switch (m_preference)
{
case Preference::Light:
dark = false;
break;
case Preference::Dark:
dark = true;
break;
case Preference::System:
{
const Qt::ColorScheme scheme = QGuiApplication::styleHints()->colorScheme();
dark = scheme == Qt::ColorScheme::Dark;
break;
}
}
m_mode = dark ? ElaThemeType::Dark : ElaThemeType::Light;
if (eTheme->getThemeMode() != m_mode)
{
eTheme->setThemeMode(m_mode);
}
m_tokens = buildTokens(dark);
applyPalette();
Q_EMIT themeChanged(m_tokens);
}
void ThemeManager::applyPalette() const
{
QPalette palette;
palette.setColor(QPalette::Window, m_tokens.windowBackground);
palette.setColor(QPalette::WindowText, m_tokens.textPrimary);
palette.setColor(QPalette::Base, m_tokens.cardBackground);
palette.setColor(QPalette::AlternateBase, m_tokens.hourAlternate);
palette.setColor(QPalette::Text, m_tokens.textPrimary);
palette.setColor(QPalette::Button, m_tokens.cardBackground);
palette.setColor(QPalette::ButtonText, m_tokens.textPrimary);
palette.setColor(QPalette::Highlight, m_tokens.accent);
palette.setColor(QPalette::HighlightedText, m_tokens.onAccent);
palette.setColor(QPalette::ToolTipBase, m_tokens.cardBackground);
palette.setColor(QPalette::ToolTipText, m_tokens.textPrimary);
palette.setColor(QPalette::PlaceholderText, m_tokens.textMuted);
palette.setColor(QPalette::Disabled, QPalette::WindowText, m_tokens.textMuted);
palette.setColor(QPalette::Disabled, QPalette::Text, m_tokens.textMuted);
palette.setColor(QPalette::Disabled, QPalette::ButtonText, m_tokens.textMuted);
QApplication::setPalette(palette);
}
ThemeTokens ThemeManager::buildTokens(bool dark)
{
ThemeTokens tokens;
tokens.dark = dark;
if (dark)
{
tokens.windowBackground = QColor(0x1B, 0x1C, 0x20);
tokens.panelBackground = QColor(0x22, 0x24, 0x29);
tokens.toolbarBackground = QColor(0x20, 0x22, 0x27);
tokens.cardBackground = QColor(0x2A, 0x2D, 0x33);
tokens.cardHoverBackground = QColor(0x33, 0x37, 0x3E);
tokens.cardBorder = QColor(0x3C, 0x40, 0x48);
tokens.textPrimary = QColor(0xEC, 0xEE, 0xF2);
tokens.textSecondary = QColor(0xAE, 0xB4, 0xBE);
tokens.textMuted = QColor(0x77, 0x7D, 0x88);
tokens.accent = QColor(0x5B, 0x9B, 0xFF);
tokens.accentHover = QColor(0x74, 0xAC, 0xFF);
tokens.accentPressed = QColor(0x40, 0x7F, 0xE0);
tokens.onAccent = QColor(0xFF, 0xFF, 0xFF);
tokens.axisBackground = QColor(0x1F, 0x21, 0x26);
tokens.gridMajor = QColor(0x39, 0x3D, 0x45);
tokens.gridMinor = QColor(0x2C, 0x2F, 0x36);
tokens.hourAlternate = QColor(0x24, 0x26, 0x2C);
tokens.nowLine = QColor(0xFF, 0x6B, 0x6B);
tokens.blockFill = QColor(0x2B, 0x40, 0x63);
tokens.blockFillHover = QColor(0x32, 0x4B, 0x74);
tokens.blockBorder = QColor(0x5B, 0x9B, 0xFF);
tokens.blockText = QColor(0xEF, 0xF5, 0xFF);
tokens.blockSubText = QColor(0xB7, 0xCD, 0xEE);
tokens.blockDoneFill = QColor(0x2A, 0x43, 0x37);
tokens.blockDoneBorder = QColor(0x62, 0xB8, 0x82);
tokens.blockOverdueFill = QColor(0x4A, 0x2C, 0x31);
tokens.blockOverdueBorder = QColor(0xFF, 0x7A, 0x7A);
tokens.blockDroppedFill = QColor(0x2D, 0x2F, 0x34);
tokens.blockDroppedBorder = QColor(0x5A, 0x5E, 0x66);
tokens.diffAdd = QColor(0x3E, 0x8E, 0x5C);
tokens.diffModify = QColor(0xB0, 0x8A, 0x2E);
tokens.diffDelete = QColor(0xB0, 0x4A, 0x4A);
tokens.warning = QColor(0xFF, 0xB4, 0x4D);
tokens.success = QColor(0x62, 0xB8, 0x82);
}
else
{
tokens.windowBackground = QColor(0xF5, 0xF7, 0xFA);
tokens.panelBackground = QColor(0xFF, 0xFF, 0xFF);
tokens.toolbarBackground = QColor(0xFF, 0xFF, 0xFF);
tokens.cardBackground = QColor(0xFF, 0xFF, 0xFF);
tokens.cardHoverBackground = QColor(0xF1, 0xF4, 0xF9);
tokens.cardBorder = QColor(0xE2, 0xE6, 0xED);
tokens.textPrimary = QColor(0x1D, 0x23, 0x2C);
tokens.textSecondary = QColor(0x5B, 0x64, 0x72);
tokens.textMuted = QColor(0x8B, 0x94, 0xA3);
tokens.accent = QColor(0x2F, 0x6F, 0xED);
tokens.accentHover = QColor(0x4A, 0x86, 0xF5);
tokens.accentPressed = QColor(0x22, 0x58, 0xC4);
tokens.onAccent = QColor(0xFF, 0xFF, 0xFF);
tokens.axisBackground = QColor(0xFA, 0xFB, 0xFD);
tokens.gridMajor = QColor(0xE0, 0xE5, 0xED);
tokens.gridMinor = QColor(0xED, 0xF0, 0xF5);
tokens.hourAlternate = QColor(0xF7, 0xF9, 0xFC);
tokens.nowLine = QColor(0xE0, 0x3B, 0x3B);
tokens.blockFill = QColor(0xE8, 0xF0, 0xFF);
tokens.blockFillHover = QColor(0xDC, 0xE8, 0xFF);
tokens.blockBorder = QColor(0x4C, 0x8D, 0xFF);
tokens.blockText = QColor(0x1A, 0x3A, 0x6B);
tokens.blockSubText = QColor(0x44, 0x66, 0x99);
tokens.blockDoneFill = QColor(0xE7, 0xF6, 0xEC);
tokens.blockDoneBorder = QColor(0x3E, 0xA8, 0x66);
tokens.blockOverdueFill = QColor(0xFD, 0xEC, 0xEE);
tokens.blockOverdueBorder = QColor(0xE0, 0x4B, 0x5A);
tokens.blockDroppedFill = QColor(0xF0, 0xF1, 0xF4);
tokens.blockDroppedBorder = QColor(0xB8, 0xBE, 0xC8);
tokens.diffAdd = QColor(0x3E, 0xA8, 0x66);
tokens.diffModify = QColor(0xD9, 0xA1, 0x2E);
tokens.diffDelete = QColor(0xD9, 0x4A, 0x4A);
tokens.warning = QColor(0xD9, 0x8A, 0x1E);
tokens.success = QColor(0x3E, 0xA8, 0x66);
}
return tokens;
}
+53
View File
@@ -0,0 +1,53 @@
#pragma once
#include <QObject>
#include "ElaDef.h"
#include "ThemeTokens.h"
class AppSettings;
/*
* 类名: ThemeManager
* 功能: 统一管理系统/浅色/深色主题,驱动 ElaWidgetTools 与自绘控件调色板
* 线程安全: 否;主线程使用
*/
class ThemeManager : public QObject
{
Q_OBJECT
public:
enum class Preference
{
System,
Light,
Dark,
};
Q_ENUM(Preference)
explicit ThemeManager(AppSettings& settings, QObject* parent = nullptr);
void initialize();
Preference preference() const;
void setPreference(Preference preference);
void cyclePreference();
ElaThemeType::ThemeMode mode() const;
const ThemeTokens& tokens() const;
static QString preferenceLabel(Preference preference);
signals:
void themeChanged(const ThemeTokens& tokens);
void preferenceChanged(Preference preference);
private:
void apply();
void applyPalette() const;
static ThemeTokens buildTokens(bool dark);
AppSettings& m_settings;
Preference m_preference = Preference::System;
ElaThemeType::ThemeMode m_mode = ElaThemeType::Light;
ThemeTokens m_tokens;
};
+56
View File
@@ -0,0 +1,56 @@
#pragma once
#include <QColor>
#include <QMetaType>
/*
* 类名: ThemeTokens
* 功能: 自绘控件使用的唯一调色板,禁止在控件内散落硬编码颜色
* 线程安全: 否(值类型)
*/
struct ThemeTokens
{
bool dark = false;
QColor windowBackground;
QColor panelBackground;
QColor toolbarBackground;
QColor cardBackground;
QColor cardHoverBackground;
QColor cardBorder;
QColor textPrimary;
QColor textSecondary;
QColor textMuted;
QColor accent;
QColor accentHover;
QColor accentPressed;
QColor onAccent;
QColor axisBackground;
QColor gridMajor;
QColor gridMinor;
QColor hourAlternate;
QColor nowLine;
QColor blockFill;
QColor blockFillHover;
QColor blockBorder;
QColor blockText;
QColor blockSubText;
QColor blockDoneFill;
QColor blockDoneBorder;
QColor blockOverdueFill;
QColor blockOverdueBorder;
QColor blockDroppedFill;
QColor blockDroppedBorder;
QColor diffAdd;
QColor diffModify;
QColor diffDelete;
QColor warning;
QColor success;
};
Q_DECLARE_METATYPE(ThemeTokens)
+19
View File
@@ -0,0 +1,19 @@
#include "WindowEffects.h"
#include "ElaApplication.h"
bool WindowEffects::isMicaActive()
{
return eApp->getWindowDisplayMode() == ElaApplicationType::ElaMica;
}
void WindowEffects::applyMica(bool enabled)
{
const ElaApplicationType::WindowDisplayMode target =
enabled ? ElaApplicationType::ElaMica : ElaApplicationType::Normal;
if (eApp->getWindowDisplayMode() == target)
{
return;
}
eApp->setWindowDisplayMode(target);
}
+7
View File
@@ -0,0 +1,7 @@
#pragma once
namespace WindowEffects
{
bool isMicaActive();
void applyMica(bool enabled);
} // namespace WindowEffects
+380
View File
@@ -0,0 +1,380 @@
#include "MonthView.h"
#include <QAction>
#include <QContextMenuEvent>
#include <QFontMetrics>
#include <QMouseEvent>
#include <QPainter>
#include <QPainterPath>
#include <QWheelEvent>
#include <algorithm>
#include "ElaMenu.h"
#include "core/DateTimeUtils.h"
namespace
{
constexpr qreal kHeaderHeight = 30.0;
constexpr int kRows = 6;
constexpr int kColumns = 7;
QColor statusColor(const ScheduleItem& item, const ThemeTokens& tokens, const QDateTime& now)
{
if (item.block.status == QStringLiteral("done"))
{
return tokens.success;
}
if (item.block.status == QStringLiteral("dropped") || item.block.status == QStringLiteral("missed"))
{
return tokens.textMuted;
}
if (item.block.endAt < now)
{
return tokens.blockOverdueBorder;
}
if (item.block.status == QStringLiteral("in_progress"))
{
return tokens.warning;
}
return tokens.accent;
}
} // namespace
MonthView::MonthView(QWidget* parent)
: QWidget(parent)
, m_month(QDate::currentDate().addDays(1 - QDate::currentDate().day()))
, m_selectedDate(QDate::currentDate())
{
setMouseTracking(true);
setMinimumSize(560, 420);
}
void MonthView::setMonth(const QDate& monthAnchor)
{
if (!monthAnchor.isValid())
{
return;
}
const QDate normalized(monthAnchor.year(), monthAnchor.month(), 1);
if (normalized == m_month)
{
return;
}
m_month = normalized;
update();
}
void MonthView::setItems(const QVector<ScheduleItem>& items)
{
m_itemsByDate.clear();
for (const ScheduleItem& item : items)
{
m_itemsByDate[item.block.startAt.date()].append(item);
}
for (auto it = m_itemsByDate.begin(); it != m_itemsByDate.end(); ++it)
{
std::sort(it->begin(), it->end(), [](const ScheduleItem& a, const ScheduleItem& b) {
return a.block.startAt < b.block.startAt;
});
}
update();
}
void MonthView::setSelectedDate(const QDate& date)
{
if (m_selectedDate == date)
{
return;
}
m_selectedDate = date;
update();
}
void MonthView::setTokens(const ThemeTokens& tokens)
{
m_tokens = tokens;
update();
}
QDate MonthView::month() const
{
return m_month;
}
QDate MonthView::selectedDate() const
{
return m_selectedDate;
}
QDate MonthView::visibleStart() const
{
return m_month.addDays(-(m_month.dayOfWeek() - 1));
}
QRectF MonthView::cellRect(int row, int column) const
{
const qreal left = width() * column / static_cast<qreal>(kColumns);
const qreal top = kHeaderHeight + (height() - kHeaderHeight) * row / static_cast<qreal>(kRows);
const qreal cellWidth = width() / static_cast<qreal>(kColumns);
const qreal cellHeight = (height() - kHeaderHeight) / static_cast<qreal>(kRows);
return QRectF(left + 3, top + 3, cellWidth - 6, cellHeight - 6);
}
QRectF MonthView::cellRectForDate(const QDate& date) const
{
const int offset = visibleStart().daysTo(date);
if (offset < 0 || offset >= kRows * kColumns)
{
return {};
}
return cellRect(offset / kColumns, offset % kColumns);
}
QDate MonthView::dateAt(const QPointF& pos) const
{
if (pos.y() < kHeaderHeight || pos.x() < 0 || pos.x() >= width())
{
return {};
}
const int column = qBound(0, static_cast<int>(pos.x() / (width() / static_cast<qreal>(kColumns))), kColumns - 1);
const qreal rowHeight = (height() - kHeaderHeight) / static_cast<qreal>(kRows);
if (rowHeight <= 0)
{
return {};
}
const int row = qBound(0, static_cast<int>((pos.y() - kHeaderHeight) / rowHeight), kRows - 1);
return visibleStart().addDays(row * kColumns + column);
}
void MonthView::paintEvent(QPaintEvent* event)
{
Q_UNUSED(event)
QPainter painter(this);
painter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing);
painter.fillRect(rect(), m_tokens.windowBackground);
QFont headerFont = painter.font();
headerFont.setPixelSize(11);
headerFont.setWeight(QFont::DemiBold);
painter.setFont(headerFont);
painter.setPen(m_tokens.textSecondary);
static const char* weekdays[] = {"一", "二", "三", "四", "五", "六", "日"};
for (int column = 0; column < kColumns; ++column)
{
const QRectF cell = cellRect(0, column);
const QRectF headerRect(cell.left(), 2, cell.width(), kHeaderHeight - 6);
painter.drawText(headerRect, Qt::AlignCenter, QString::fromUtf8(weekdays[column]));
}
const QDateTime now = QDateTime::currentDateTime();
const QDate today = now.date();
const QDate start = visibleStart();
QFont dayFont = painter.font();
dayFont.setPixelSize(12);
dayFont.setWeight(QFont::DemiBold);
QFont taskFont = painter.font();
taskFont.setPixelSize(10);
taskFont.setWeight(QFont::Normal);
for (int index = 0; index < kRows * kColumns; ++index)
{
const int row = index / kColumns;
const int column = index % kColumns;
const QDate date = start.addDays(index);
const QRectF rect = cellRect(row, column);
const bool inMonth = date.month() == m_month.month() && date.year() == m_month.year();
const bool selected = date == m_selectedDate;
const bool hovered = date == m_hoverDate;
const bool isToday = date == today;
QColor background = m_tokens.cardBackground;
if (!inMonth)
{
background = m_tokens.windowBackground;
}
else if (hovered)
{
background = m_tokens.cardHoverBackground;
}
if (selected)
{
background = m_tokens.accent;
background.setAlpha(m_tokens.dark ? 70 : 34);
}
QPainterPath path;
path.addRoundedRect(rect, 8, 8);
painter.fillPath(path, background);
QColor border = m_tokens.cardBorder;
qreal borderWidth = 1.0;
if (selected)
{
border = m_tokens.accent;
borderWidth = 2.0;
}
else if (isToday)
{
border = m_tokens.accent;
borderWidth = 1.3;
}
painter.setPen(QPen(border, borderWidth));
painter.setBrush(Qt::NoBrush);
painter.drawPath(path);
painter.setFont(dayFont);
painter.setPen(selected ? m_tokens.onAccent : (inMonth ? m_tokens.textPrimary : m_tokens.textMuted));
if (selected)
{
const QRectF badge(rect.left() + 5, rect.top() + 4, 24, 20);
QPainterPath badgePath;
badgePath.addRoundedRect(badge, 6, 6);
painter.fillPath(badgePath, m_tokens.accent);
painter.setPen(m_tokens.onAccent);
painter.drawText(badge, Qt::AlignCenter, QString::number(date.day()));
}
else
{
painter.drawText(QRectF(rect.left() + 7, rect.top() + 4, 30, 18),
Qt::AlignLeft | Qt::AlignVCenter,
QString::number(date.day()));
}
const auto it = m_itemsByDate.constFind(date);
if (it == m_itemsByDate.constEnd() || it->isEmpty())
{
continue;
}
painter.setFont(taskFont);
const QFontMetrics metrics(taskFont);
const qreal rowHeight = 15.0;
const qreal startY = rect.top() + 26.0;
const int maxRows = qMax(0, static_cast<int>((rect.height() - 30.0) / rowHeight));
const int count = qMin(maxRows, static_cast<int>(it->size()));
for (int i = 0; i < count; ++i)
{
const ScheduleItem& item = it->at(i);
const qreal y = startY + i * rowHeight;
painter.setPen(Qt::NoPen);
painter.setBrush(statusColor(item, m_tokens, now));
painter.drawEllipse(QPointF(rect.left() + 9, y + 6), 2.6, 2.6);
QColor textColor = inMonth ? m_tokens.textSecondary : m_tokens.textMuted;
if (item.block.status == QStringLiteral("done") ||
item.block.status == QStringLiteral("dropped"))
{
textColor.setAlpha(160);
}
painter.setPen(textColor);
const QString title =
metrics.elidedText(item.task.title, Qt::ElideRight, static_cast<int>(rect.width() - 26));
painter.drawText(QRectF(rect.left() + 15, y, rect.width() - 22, rowHeight),
Qt::AlignLeft | Qt::AlignVCenter,
title);
}
if (static_cast<int>(it->size()) > count)
{
const qreal y = startY + count * rowHeight;
painter.setPen(m_tokens.textMuted);
painter.drawText(QRectF(rect.left() + 15, y, rect.width() - 22, rowHeight),
Qt::AlignLeft | Qt::AlignVCenter,
QStringLiteral("+%1").arg(it->size() - count));
}
}
}
void MonthView::updateHover(const QPointF& pos)
{
const QDate date = dateAt(pos);
if (date == m_hoverDate)
{
return;
}
m_hoverDate = date;
setCursor(date.isValid() ? Qt::PointingHandCursor : Qt::ArrowCursor);
update();
}
void MonthView::mousePressEvent(QMouseEvent* event)
{
if (event->button() != Qt::LeftButton)
{
QWidget::mousePressEvent(event);
return;
}
const QDate date = dateAt(event->position());
if (date.isValid())
{
m_selectedDate = date;
update();
Q_EMIT dateSelected(date);
}
event->accept();
}
void MonthView::mouseDoubleClickEvent(QMouseEvent* event)
{
if (event->button() != Qt::LeftButton)
{
QWidget::mouseDoubleClickEvent(event);
return;
}
const QDate date = dateAt(event->position());
if (date.isValid())
{
Q_EMIT dateActivated(date);
}
event->accept();
}
void MonthView::mouseMoveEvent(QMouseEvent* event)
{
updateHover(event->position());
QWidget::mouseMoveEvent(event);
}
void MonthView::leaveEvent(QEvent* event)
{
m_hoverDate = {};
setCursor(Qt::ArrowCursor);
update();
QWidget::leaveEvent(event);
}
void MonthView::contextMenuEvent(QContextMenuEvent* event)
{
const QDate date = dateAt(event->pos());
if (!date.isValid())
{
QWidget::contextMenuEvent(event);
return;
}
m_selectedDate = date;
update();
Q_EMIT dateSelected(date);
ElaMenu menu(this);
QAction* createAction = menu.addAction(QStringLiteral("在此日新建日程"));
connect(createAction, &QAction::triggered, this, [this, date]() { Q_EMIT createRequested(date); });
QAction* openAction = menu.addAction(QStringLiteral("打开当日视图"));
connect(openAction, &QAction::triggered, this, [this, date]() { Q_EMIT dateActivated(date); });
menu.exec(event->globalPos());
event->accept();
}
void MonthView::wheelEvent(QWheelEvent* event)
{
const int delta = event->angleDelta().y();
if (delta != 0)
{
Q_EMIT monthStepRequested(delta > 0 ? -1 : 1);
event->accept();
return;
}
QWidget::wheelEvent(event);
}
+58
View File
@@ -0,0 +1,58 @@
#pragma once
#include <QDate>
#include <QHash>
#include <QVector>
#include <QWidget>
#include "core/ScheduleItem.h"
#include "ui/theme/ThemeTokens.h"
/*
* 类名: MonthView
* 功能: 自绘月视图;按天展示日程条目,单击选择、双击进入日视图
* 线程安全: 否;UI 线程
*/
class MonthView : public QWidget
{
Q_OBJECT
public:
explicit MonthView(QWidget* parent = nullptr);
void setMonth(const QDate& monthAnchor);
void setItems(const QVector<ScheduleItem>& items);
void setSelectedDate(const QDate& date);
void setTokens(const ThemeTokens& tokens);
QDate month() const;
QDate selectedDate() const;
signals:
void dateSelected(const QDate& date);
void dateActivated(const QDate& date);
void createRequested(const QDate& date);
void monthStepRequested(int direction);
protected:
void paintEvent(QPaintEvent* event) override;
void mousePressEvent(QMouseEvent* event) override;
void mouseDoubleClickEvent(QMouseEvent* event) override;
void mouseMoveEvent(QMouseEvent* event) override;
void leaveEvent(QEvent* event) override;
void contextMenuEvent(QContextMenuEvent* event) override;
void wheelEvent(QWheelEvent* event) override;
private:
QDate visibleStart() const;
QDate dateAt(const QPointF& pos) const;
QRectF cellRect(int row, int column) const;
QRectF cellRectForDate(const QDate& date) const;
void updateHover(const QPointF& pos);
QDate m_month;
QDate m_selectedDate;
QDate m_hoverDate;
QHash<QDate, QVector<ScheduleItem>> m_itemsByDate;
ThemeTokens m_tokens;
};
File diff suppressed because it is too large Load Diff
+143
View File
@@ -0,0 +1,143 @@
#pragma once
#include <QAbstractScrollArea>
#include <QDate>
#include <QDateTime>
#include <QPixmap>
#include <QSize>
#include <QVector>
#include "core/ScheduleItem.h"
#include "ui/theme/ThemeTokens.h"
/*
* 类名: ScheduleGridView
* 功能: 自绘单日时间网格;负责命中测试、拖拽/缩放、选中与上下文菜单
* 线程安全: 否;仅 UI 线程访问
*/
class ScheduleGridView : public QAbstractScrollArea
{
Q_OBJECT
public:
explicit ScheduleGridView(QWidget* parent = nullptr);
void setDate(const QDate& date);
QDate date() const;
void setBlocks(const QVector<ScheduleItem>& blocks);
const QVector<ScheduleItem>& blocks() const;
void setTokens(const ThemeTokens& tokens);
void setSnapMinutes(int minutes);
int snapMinutes() const;
void setSelectedBlock(const QString& blockId);
QString selectedBlockId() const;
void scrollToBlock(const QString& blockId);
void scrollToCurrentTime();
void scrollToHour(int hour);
signals:
void createRequested(const QDateTime& start, const QDateTime& end);
void editRequested(const QString& blockId);
void moveRequested(const QString& blockId, const QDateTime& start, const QDateTime& end);
void statusChangeRequested(const QString& blockId, const QString& status);
void postponeRequested(const QString& blockId, int minutes);
void deleteRequested(const QString& blockId);
void selectionChanged(const QString& blockId);
protected:
bool eventFilter(QObject* watched, QEvent* event) override;
void paintEvent(QPaintEvent* event) override;
void resizeEvent(QResizeEvent* event) override;
void mousePressEvent(QMouseEvent* event) override;
void mouseMoveEvent(QMouseEvent* event) override;
void mouseReleaseEvent(QMouseEvent* event) override;
void mouseDoubleClickEvent(QMouseEvent* event) override;
void contextMenuEvent(QContextMenuEvent* event) override;
void wheelEvent(QWheelEvent* event) override;
void keyPressEvent(QKeyEvent* event) override;
void scrollContentsBy(int dx, int dy) override;
private:
enum class DragMode
{
None,
Create,
Move,
ResizeTop,
ResizeBottom,
};
struct VisualBlock
{
ScheduleItem item;
QDateTime displayStart;
QDateTime displayEnd;
QRectF rect;
};
void updateScrollRange();
void rebuildLayout();
void ensureGridCache();
void invalidateGridCache();
void paintGrid(QPainter& painter);
void paintBlocks(QPainter& painter, int scrollY);
void paintBlock(QPainter& painter, const VisualBlock& visual);
void paintNowLine(QPainter& painter, int scrollY);
void paintCreatePreview(QPainter& painter, int scrollY);
void paintEmptyHint(QPainter& painter, int scrollY);
const VisualBlock* visualForPoint(const QPointF& pos) const;
const VisualBlock* visualForId(const QString& id) const;
DragMode dragModeForPoint(const QPointF& pos, const VisualBlock& visual) const;
void updateHover(const QPointF& pos);
void updateCursorForPoint(const QPointF& pos, DragMode mode);
QDateTime dayStart() const;
QDateTime dayEnd() const;
QDateTime timeAtY(double y, bool snap) const;
int minuteAtY(double y) const;
qreal yForMinute(int minute) const;
QRectF rectForTimes(const QDateTime& start, const QDateTime& end) const;
void beginInteraction(DragMode mode,
const QString& blockId,
const QDateTime& start,
const QDateTime& end,
const QPointF& pressPos);
void updateInteraction(const QPointF& pos);
void finishInteraction();
void showBlockMenu(const QPointF& viewportPos, const QString& blockId);
void showEmptyMenu(const QPointF& viewportPos);
void requestCreateAt(const QDateTime& time, int durationMinutes);
QDate m_date;
QVector<ScheduleItem> m_blocks;
QVector<VisualBlock> m_visuals;
ThemeTokens m_tokens;
int m_snapMinutes = 15;
qreal m_pixelsPerHour = 120.0;
int m_axisWidth = 64;
QString m_selectedId;
QString m_hoveredId;
DragMode m_dragMode = DragMode::None;
QString m_dragBlockId;
QDateTime m_dragOriginalStart;
QDateTime m_dragOriginalEnd;
QDateTime m_previewStart;
QDateTime m_previewEnd;
QPointF m_pressPos;
QPointF m_lastPos;
bool m_dragMoved = false;
QPixmap m_gridCache;
bool m_gridCacheValid = false;
QSize m_gridCacheSize;
int m_gridCacheScroll = 0;
};
+410
View File
@@ -0,0 +1,410 @@
#include "YearView.h"
#include <QFontMetrics>
#include <QMouseEvent>
#include <QPainter>
#include <QPainterPath>
#include <QWheelEvent>
namespace
{
constexpr int kColumns = 4;
constexpr int kRows = 3;
constexpr qreal kMargin = 10.0;
constexpr qreal kGap = 10.0;
constexpr qreal kTitleHeight = 24.0;
constexpr qreal kWeekdayHeight = 13.0;
constexpr qreal kInnerPadding = 8.0;
constexpr qreal kGridGap = 2.0;
constexpr int kMiniRows = 6;
constexpr int kMiniColumns = 7;
} // namespace
YearView::YearView(QWidget* parent)
: QWidget(parent)
, m_year(QDate::currentDate().year())
, m_selectedDate(QDate::currentDate())
{
setMouseTracking(true);
setMinimumSize(680, 480);
}
void YearView::setYear(int year)
{
if (year < 1900 || year > 9999 || m_year == year)
{
return;
}
m_year = year;
update();
}
void YearView::setItems(const QVector<ScheduleItem>& items)
{
m_summary.clear();
const QDateTime now = QDateTime::currentDateTime();
for (const ScheduleItem& item : items)
{
const QDate date = item.block.startAt.date();
DaySummary& summary = m_summary[date];
++summary.total;
if (item.block.status == QStringLiteral("done"))
{
++summary.done;
}
else if (item.block.status == QStringLiteral("scheduled") ||
item.block.status == QStringLiteral("in_progress"))
{
if (item.block.endAt < now)
{
summary.overdue = true;
}
}
}
update();
}
void YearView::setSelectedDate(const QDate& date)
{
if (m_selectedDate == date)
{
return;
}
m_selectedDate = date;
update();
}
void YearView::setTokens(const ThemeTokens& tokens)
{
m_tokens = tokens;
update();
}
int YearView::year() const
{
return m_year;
}
QDate YearView::selectedDate() const
{
return m_selectedDate;
}
QRectF YearView::cardRect(int monthIndex) const
{
const qreal availableWidth = width() - kMargin * 2 - kGap * (kColumns - 1);
const qreal availableHeight = height() - kMargin * 2 - kGap * (kRows - 1);
const qreal cardWidth = availableWidth / kColumns;
const qreal cardHeight = availableHeight / kRows;
const int column = monthIndex % kColumns;
const int row = monthIndex / kColumns;
return QRectF(kMargin + column * (cardWidth + kGap),
kMargin + row * (cardHeight + kGap),
cardWidth,
cardHeight);
}
QRectF YearView::titleRect(int monthIndex) const
{
const QRectF card = cardRect(monthIndex);
return QRectF(card.left() + kInnerPadding,
card.top() + 4,
card.width() - kInnerPadding * 2,
kTitleHeight - 4);
}
QRectF YearView::gridRect(int monthIndex) const
{
const QRectF card = cardRect(monthIndex);
return QRectF(card.left() + kInnerPadding,
card.top() + kTitleHeight + kWeekdayHeight,
card.width() - kInnerPadding * 2,
card.height() - kTitleHeight - kWeekdayHeight - kInnerPadding);
}
QRectF YearView::miniCellRect(int monthIndex, int cellIndex) const
{
const QRectF grid = gridRect(monthIndex);
const qreal cellWidth = (grid.width() - kGridGap * (kMiniColumns - 1)) / kMiniColumns;
const qreal cellHeight = (grid.height() - kGridGap * (kMiniRows - 1)) / kMiniRows;
const int row = cellIndex / kMiniColumns;
const int column = cellIndex % kMiniColumns;
return QRectF(grid.left() + column * (cellWidth + kGridGap),
grid.top() + row * (cellHeight + kGridGap),
cellWidth,
cellHeight);
}
int YearView::monthAt(const QPointF& pos) const
{
for (int month = 0; month < 12; ++month)
{
if (cardRect(month).contains(pos))
{
return month;
}
}
return -1;
}
QDate YearView::dateAt(const QPointF& pos) const
{
const int month = monthAt(pos);
if (month < 0)
{
return {};
}
const QRectF grid = gridRect(month);
if (!grid.contains(pos))
{
return {};
}
const qreal cellWidth = (grid.width() - kGridGap * (kMiniColumns - 1)) / kMiniColumns;
const qreal cellHeight = (grid.height() - kGridGap * (kMiniRows - 1)) / kMiniRows;
if (cellWidth <= 0 || cellHeight <= 0)
{
return {};
}
const int column = qBound(0, static_cast<int>((pos.x() - grid.left()) / (cellWidth + kGridGap)), kMiniColumns - 1);
const int row = qBound(0, static_cast<int>((pos.y() - grid.top()) / (cellHeight + kGridGap)), kMiniRows - 1);
const QDate firstOfMonth(m_year, month + 1, 1);
const QDate start = firstOfMonth.addDays(-(firstOfMonth.dayOfWeek() - 1));
const QDate date = start.addDays(row * kMiniColumns + column);
if (date.month() != month + 1 || date.year() != m_year)
{
return {};
}
return date;
}
void YearView::paintEvent(QPaintEvent* event)
{
Q_UNUSED(event)
QPainter painter(this);
painter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing);
painter.fillRect(rect(), m_tokens.windowBackground);
const QDate today = QDate::currentDate();
for (int month = 0; month < 12; ++month)
{
const QRectF card = cardRect(month);
QPainterPath cardPath;
cardPath.addRoundedRect(card, 10, 10);
painter.fillPath(cardPath, m_tokens.cardBackground);
painter.setPen(QPen(m_tokens.cardBorder, 1.0));
painter.setBrush(Qt::NoBrush);
painter.drawPath(cardPath);
QFont titleFont = painter.font();
titleFont.setPixelSize(13);
titleFont.setWeight(QFont::DemiBold);
painter.setFont(titleFont);
painter.setPen(m_tokens.textPrimary);
painter.drawText(titleRect(month), Qt::AlignLeft | Qt::AlignVCenter, QStringLiteral("%1月").arg(month + 1));
int monthTotal = 0;
for (int day = 1; day <= QDate(m_year, month + 1, 1).daysInMonth(); ++day)
{
monthTotal += m_summary.value(QDate(m_year, month + 1, day)).total;
}
QFont countFont = painter.font();
countFont.setPixelSize(10);
countFont.setWeight(QFont::Normal);
painter.setFont(countFont);
painter.setPen(m_tokens.textMuted);
painter.drawText(titleRect(month),
Qt::AlignRight | Qt::AlignVCenter,
monthTotal > 0 ? QStringLiteral("%1 项").arg(monthTotal) : QStringLiteral("—"));
const QRectF grid = gridRect(month);
const qreal cellWidth = (grid.width() - kGridGap * (kMiniColumns - 1)) / kMiniColumns;
const qreal cellHeight = (grid.height() - kGridGap * (kMiniRows - 1)) / kMiniRows;
QFont weekdayFont = painter.font();
weekdayFont.setPixelSize(8);
painter.setFont(weekdayFont);
painter.setPen(m_tokens.textMuted);
static const char* weekdays[] = {"一", "二", "三", "四", "五", "六", "日"};
for (int column = 0; column < kMiniColumns; ++column)
{
const QRectF cell(grid.left() + column * (cellWidth + kGridGap),
grid.top() - kWeekdayHeight,
cellWidth,
kWeekdayHeight - 2);
painter.drawText(cell, Qt::AlignCenter, QString::fromUtf8(weekdays[column]));
}
const QDate firstOfMonth(m_year, month + 1, 1);
const QDate start = firstOfMonth.addDays(-(firstOfMonth.dayOfWeek() - 1));
QFont dayFont = painter.font();
dayFont.setPixelSize(qBound(7, static_cast<int>(cellHeight * 0.42), 10));
dayFont.setWeight(QFont::Normal);
for (int cellIndex = 0; cellIndex < kMiniRows * kMiniColumns; ++cellIndex)
{
const QDate date = start.addDays(cellIndex);
const bool inMonth = date.month() == month + 1 && date.year() == m_year;
if (!inMonth)
{
continue;
}
QRectF cell = miniCellRect(month, cellIndex);
cell.adjust(0.5, 0.5, -0.5, -0.5);
const auto it = m_summary.constFind(date);
const bool hasTasks = it != m_summary.constEnd() && it->total > 0;
const bool selected = date == m_selectedDate;
const bool hovered = date == m_hoverDate;
const bool isToday = date == today;
QColor fill = Qt::transparent;
QColor border = Qt::transparent;
if (hasTasks)
{
if (it->overdue)
{
fill = m_tokens.blockOverdueFill;
border = m_tokens.blockOverdueBorder;
}
else if (it->done == it->total)
{
fill = m_tokens.blockDoneFill;
border = m_tokens.blockDoneBorder;
}
else
{
fill = m_tokens.blockFill;
border = m_tokens.blockBorder;
}
fill.setAlpha(m_tokens.dark ? 120 : 150);
border.setAlpha(160);
}
if (hovered)
{
fill = m_tokens.cardHoverBackground;
border = m_tokens.accent;
}
if (selected)
{
fill = m_tokens.accent;
fill.setAlpha(m_tokens.dark ? 190 : 220);
border = m_tokens.accent;
}
if (fill.alpha() > 0)
{
QPainterPath cellPath;
cellPath.addRoundedRect(cell, 3, 3);
painter.fillPath(cellPath, fill);
}
if (border.alpha() > 0)
{
painter.setPen(QPen(border, selected || isToday ? 1.2 : 0.7));
painter.setBrush(Qt::NoBrush);
painter.drawRoundedRect(cell, 3, 3);
}
else if (isToday)
{
painter.setPen(QPen(m_tokens.accent, 1.0));
painter.setBrush(Qt::NoBrush);
painter.drawRoundedRect(cell, 3, 3);
}
painter.setFont(dayFont);
if (selected)
{
painter.setPen(m_tokens.onAccent);
}
else if (hasTasks)
{
painter.setPen(m_tokens.textPrimary);
}
else
{
painter.setPen(m_tokens.textMuted);
}
painter.drawText(cell, Qt::AlignCenter, QString::number(date.day()));
}
}
}
void YearView::updateHover(const QPointF& pos)
{
const QDate date = dateAt(pos);
if (date == m_hoverDate)
{
return;
}
m_hoverDate = date;
setCursor(date.isValid() ? Qt::PointingHandCursor : Qt::ArrowCursor);
update();
}
void YearView::mousePressEvent(QMouseEvent* event)
{
if (event->button() != Qt::LeftButton)
{
QWidget::mousePressEvent(event);
return;
}
const int month = monthAt(event->position());
if (month >= 0 && titleRect(month).contains(event->position()))
{
const QDate firstOfMonth(m_year, month + 1, 1);
Q_EMIT monthActivated(firstOfMonth);
event->accept();
return;
}
const QDate date = dateAt(event->position());
if (date.isValid())
{
m_selectedDate = date;
update();
Q_EMIT dateSelected(date);
}
event->accept();
}
void YearView::mouseDoubleClickEvent(QMouseEvent* event)
{
if (event->button() != Qt::LeftButton)
{
QWidget::mouseDoubleClickEvent(event);
return;
}
const QDate date = dateAt(event->position());
if (date.isValid())
{
Q_EMIT dateActivated(date);
}
event->accept();
}
void YearView::mouseMoveEvent(QMouseEvent* event)
{
updateHover(event->position());
QWidget::mouseMoveEvent(event);
}
void YearView::leaveEvent(QEvent* event)
{
m_hoverDate = {};
setCursor(Qt::ArrowCursor);
update();
QWidget::leaveEvent(event);
}
void YearView::wheelEvent(QWheelEvent* event)
{
const int delta = event->angleDelta().y();
if (delta != 0)
{
Q_EMIT yearStepRequested(delta > 0 ? -1 : 1);
event->accept();
return;
}
QWidget::wheelEvent(event);
}
+67
View File
@@ -0,0 +1,67 @@
#pragma once
#include <QDate>
#include <QHash>
#include <QSet>
#include <QVector>
#include <QWidget>
#include "core/ScheduleItem.h"
#include "ui/theme/ThemeTokens.h"
/*
* 类名: YearView
* 功能: 自绘年视图;12 个迷你月历展示任务热度和选中日期
* 线程安全: 否;UI 线程
*/
class YearView : public QWidget
{
Q_OBJECT
public:
explicit YearView(QWidget* parent = nullptr);
void setYear(int year);
void setItems(const QVector<ScheduleItem>& items);
void setSelectedDate(const QDate& date);
void setTokens(const ThemeTokens& tokens);
int year() const;
QDate selectedDate() const;
signals:
void dateSelected(const QDate& date);
void dateActivated(const QDate& date);
void monthActivated(const QDate& month);
void yearStepRequested(int direction);
protected:
void paintEvent(QPaintEvent* event) override;
void mousePressEvent(QMouseEvent* event) override;
void mouseDoubleClickEvent(QMouseEvent* event) override;
void mouseMoveEvent(QMouseEvent* event) override;
void leaveEvent(QEvent* event) override;
void wheelEvent(QWheelEvent* event) override;
private:
struct DaySummary
{
int total = 0;
int done = 0;
bool overdue = false;
};
QRectF cardRect(int monthIndex) const;
QRectF titleRect(int monthIndex) const;
QRectF gridRect(int monthIndex) const;
QRectF miniCellRect(int monthIndex, int cellIndex) const;
int monthAt(const QPointF& pos) const;
QDate dateAt(const QPointF& pos) const;
void updateHover(const QPointF& pos);
int m_year;
QDate m_selectedDate;
QDate m_hoverDate;
QHash<QDate, DaySummary> m_summary;
ThemeTokens m_tokens;
};
+29
View File
@@ -0,0 +1,29 @@
#include "AppPaths.h"
#include <QCoreApplication>
#include <QDir>
#include <QFileInfo>
QString AppPaths::promptsDirectory()
{
const QString fromEnv = qEnvironmentVariable("SCHEDULE_PROMPTS_DIR");
if (!fromEnv.isEmpty())
{
return fromEnv;
}
const QDir appDir(QCoreApplication::applicationDirPath());
const QStringList candidates = {
appDir.filePath(QStringLiteral("resources/prompts")),
appDir.filePath(QStringLiteral("../resources/prompts")),
appDir.filePath(QStringLiteral("../../resources/prompts")),
};
for (const QString& candidate : candidates)
{
if (QFileInfo::exists(candidate))
{
return QFileInfo(candidate).absoluteFilePath();
}
}
return appDir.filePath(QStringLiteral("resources/prompts"));
}
+8
View File
@@ -0,0 +1,8 @@
#pragma once
#include <QString>
namespace AppPaths
{
QString promptsDirectory();
}
+475
View File
@@ -0,0 +1,475 @@
#include "AppSettings.h"
#include <QDebug>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QProcessEnvironment>
#include <QSaveFile>
#include <QSettings>
#include <QStandardPaths>
#include <QUuid>
#include <sstream>
#include <string>
#include "toml.hpp"
namespace
{
constexpr const char* kLegacyDeviceIdKey = "sync/deviceId";
constexpr const char* kLegacyThemeKey = "ui/theme";
constexpr const char* kLegacyMicaKey = "ui/mica";
constexpr const char* kLegacySnapKey = "ui/snapMinutes";
constexpr const char* kLegacyTrayHintKey = "ui/trayHintShown";
constexpr const char* kLegacyCompactGeometryKey = "ui/compactGeometry";
constexpr const char* kLegacyScheduleGeometryKey = "ui/scheduleGeometry";
constexpr const char* kLegacyScheduleSplitterKey = "ui/scheduleSplitter";
constexpr const char* kLegacyDatabasePathKey = "storage/databasePath";
QString normalizedTheme(const QString& value)
{
if (value == QStringLiteral("light") || value == QStringLiteral("dark"))
{
return value;
}
return QStringLiteral("system");
}
int normalizedSnap(int value)
{
return (value == 30 || value == 60) ? value : 15;
}
QString newDeviceId()
{
return QUuid::createUuid().toString(QUuid::WithoutBraces);
}
const toml::table* subTable(const toml::table& root, const char* key)
{
return root[key].as_table();
}
QString stringValue(const toml::table* table, const char* key, const QString& fallback = {})
{
if (!table)
{
return fallback;
}
if (auto value = (*table)[key].value<std::string>())
{
return QString::fromStdString(*value);
}
return fallback;
}
bool boolValue(const toml::table* table, const char* key, bool fallback)
{
if (!table)
{
return fallback;
}
if (auto value = (*table)[key].value<bool>())
{
return *value;
}
return fallback;
}
int intValue(const toml::table* table, const char* key, int fallback)
{
if (!table)
{
return fallback;
}
if (auto value = (*table)[key].value<int64_t>())
{
return static_cast<int>(*value);
}
return fallback;
}
double doubleValue(const toml::table* table, const char* key, double fallback)
{
if (!table)
{
return fallback;
}
if (auto value = (*table)[key].value<double>())
{
return *value;
}
return fallback;
}
} // namespace
AppSettings::AppSettings(QString configPath)
{
const QString envPath =
QProcessEnvironment::systemEnvironment().value(QStringLiteral("SCHEDULE_CONFIG_PATH"));
if (!configPath.trimmed().isEmpty())
{
m_configPath = configPath;
m_useDefaultPath = false;
}
else if (!envPath.trimmed().isEmpty())
{
m_configPath = envPath;
m_useDefaultPath = false;
}
else
{
QString configDir = QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation);
if (configDir.isEmpty())
{
configDir = QDir::homePath() + QStringLiteral("/.config/Misaki/Schedule");
}
m_configPath = configDir + QStringLiteral("/config.toml");
m_useDefaultPath = true;
}
applyDefaults();
load();
}
QString AppSettings::configPath() const
{
return m_configPath;
}
void AppSettings::applyDefaults()
{
m_databasePath.clear();
m_deviceId.clear();
m_themePreference = QStringLiteral("system");
m_micaEnabled = false;
m_snapMinutes = 15;
m_trayHintShown = false;
m_compactGeometry.clear();
m_scheduleGeometry.clear();
m_scheduleSplitter.clear();
m_aiConfig = AiConfig{};
m_syncConfig = SyncConfig{};
}
bool AppSettings::isUsingDefaultPath() const
{
return m_useDefaultPath;
}
void AppSettings::load()
{
const QFileInfo info(m_configPath);
if (!info.exists())
{
if (isUsingDefaultPath())
{
loadLegacyQSettings();
}
if (m_deviceId.isEmpty())
{
m_deviceId = newDeviceId();
}
save();
return;
}
try
{
const std::string path = m_configPath.toStdString();
const toml::table root = toml::parse_file(path);
if (const toml::table* app = subTable(root, "app"))
{
m_deviceId = stringValue(app, "device_id");
}
if (const toml::table* storage = subTable(root, "storage"))
{
m_databasePath = stringValue(storage, "database_path");
}
if (const toml::table* ui = subTable(root, "ui"))
{
m_themePreference = normalizedTheme(stringValue(ui, "theme", QStringLiteral("system")));
m_micaEnabled = boolValue(ui, "mica", false);
m_snapMinutes = normalizedSnap(intValue(ui, "snap_minutes", 15));
m_trayHintShown = boolValue(ui, "tray_hint_shown", false);
}
if (const toml::table* window = subTable(root, "window"))
{
m_compactGeometry = QByteArray::fromBase64(stringValue(window, "compact_geometry").toLatin1());
m_scheduleGeometry = QByteArray::fromBase64(stringValue(window, "schedule_geometry").toLatin1());
m_scheduleSplitter = QByteArray::fromBase64(stringValue(window, "schedule_splitter").toLatin1());
}
if (const toml::table* sync = subTable(root, "sync"))
{
m_syncConfig.enabled = boolValue(sync, "enabled", false);
m_syncConfig.serverUrl = stringValue(sync, "server_url");
m_syncConfig.token = stringValue(sync, "token");
}
if (const toml::table* ai = subTable(root, "ai"))
{
m_aiConfig.baseUrl = stringValue(ai, "base_url", m_aiConfig.baseUrl);
m_aiConfig.apiKey = stringValue(ai, "api_key");
m_aiConfig.model = stringValue(ai, "model", m_aiConfig.model);
m_aiConfig.temperature = doubleValue(ai, "temperature", m_aiConfig.temperature);
if (m_aiConfig.baseUrl.trimmed().isEmpty())
{
m_aiConfig.baseUrl = AiConfig{}.baseUrl;
}
if (m_aiConfig.model.trimmed().isEmpty())
{
m_aiConfig.model = AiConfig{}.model;
}
}
}
catch (const toml::parse_error& error)
{
qWarning() << "Failed to parse config file" << m_configPath
<< QString::fromStdString(std::string(error.description()));
QFile::copy(m_configPath, m_configPath + QStringLiteral(".bak"));
applyDefaults();
}
if (m_deviceId.isEmpty())
{
m_deviceId = newDeviceId();
save();
}
}
void AppSettings::loadLegacyQSettings()
{
QSettings legacy;
m_deviceId = legacy.value(QString::fromLatin1(kLegacyDeviceIdKey)).toString();
m_themePreference =
normalizedTheme(legacy.value(QString::fromLatin1(kLegacyThemeKey), QStringLiteral("system")).toString());
m_micaEnabled = legacy.value(QString::fromLatin1(kLegacyMicaKey), false).toBool();
m_snapMinutes = normalizedSnap(legacy.value(QString::fromLatin1(kLegacySnapKey), 15).toInt());
m_trayHintShown = legacy.value(QString::fromLatin1(kLegacyTrayHintKey), false).toBool();
m_compactGeometry =
legacy.value(QString::fromLatin1(kLegacyCompactGeometryKey)).toByteArray();
m_scheduleGeometry =
legacy.value(QString::fromLatin1(kLegacyScheduleGeometryKey)).toByteArray();
m_scheduleSplitter =
legacy.value(QString::fromLatin1(kLegacyScheduleSplitterKey)).toByteArray();
m_databasePath = legacy.value(QString::fromLatin1(kLegacyDatabasePathKey)).toString();
}
void AppSettings::save()
{
if (m_configPath.isEmpty())
{
return;
}
const QFileInfo info(m_configPath);
if (!QDir().mkpath(info.absolutePath()))
{
qWarning() << "Failed to create config directory" << info.absolutePath();
return;
}
toml::table root;
root.insert("schema_version", 1);
toml::table app;
app.insert("device_id", m_deviceId.toStdString());
root.insert("app", std::move(app));
toml::table storage;
storage.insert("database_path", m_databasePath.toStdString());
root.insert("storage", std::move(storage));
toml::table ui;
ui.insert("theme", m_themePreference.toStdString());
ui.insert("mica", m_micaEnabled);
ui.insert("snap_minutes", m_snapMinutes);
ui.insert("tray_hint_shown", m_trayHintShown);
root.insert("ui", std::move(ui));
toml::table window;
window.insert("compact_geometry", m_compactGeometry.toBase64().toStdString());
window.insert("schedule_geometry", m_scheduleGeometry.toBase64().toStdString());
window.insert("schedule_splitter", m_scheduleSplitter.toBase64().toStdString());
root.insert("window", std::move(window));
toml::table sync;
sync.insert("enabled", m_syncConfig.enabled);
sync.insert("server_url", m_syncConfig.serverUrl.toStdString());
sync.insert("token", m_syncConfig.token.toStdString());
root.insert("sync", std::move(sync));
toml::table ai;
ai.insert("base_url", m_aiConfig.baseUrl.toStdString());
ai.insert("api_key", m_aiConfig.apiKey.toStdString());
ai.insert("model", m_aiConfig.model.toStdString());
ai.insert("temperature", m_aiConfig.temperature);
root.insert("ai", std::move(ai));
std::ostringstream stream;
stream << root;
const QString content = QStringLiteral(
"# AI Schedule configuration. API key is stored locally; keep this file private.\n")
+ QString::fromStdString(stream.str());
QSaveFile file(m_configPath);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
{
qWarning() << "Failed to open config for writing" << m_configPath << file.errorString();
return;
}
file.write(content.toUtf8());
if (!file.commit())
{
qWarning() << "Failed to write config" << m_configPath << file.errorString();
return;
}
#ifndef Q_OS_WIN
QFile::setPermissions(m_configPath, QFileDevice::ReadOwner | QFileDevice::WriteOwner);
#endif
}
QString AppSettings::databasePath() const
{
const QString envPath =
QProcessEnvironment::systemEnvironment().value(QStringLiteral("SCHEDULE_DB_PATH"));
if (!envPath.trimmed().isEmpty())
{
return envPath;
}
if (!m_databasePath.trimmed().isEmpty())
{
return m_databasePath;
}
QString dataDir = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
if (dataDir.isEmpty())
{
dataDir = QDir::homePath() + QStringLiteral("/.local/share/Misaki/Schedule");
}
return dataDir + QStringLiteral("/schedule.db");
}
QString AppSettings::deviceId()
{
if (m_deviceId.isEmpty())
{
m_deviceId = newDeviceId();
save();
}
return m_deviceId;
}
QString AppSettings::themePreference() const
{
return m_themePreference;
}
void AppSettings::setThemePreference(const QString& preference)
{
m_themePreference = normalizedTheme(preference);
save();
}
bool AppSettings::micaEnabled() const
{
return m_micaEnabled;
}
void AppSettings::setMicaEnabled(bool enabled)
{
m_micaEnabled = enabled;
save();
}
int AppSettings::snapMinutes() const
{
return m_snapMinutes;
}
void AppSettings::setSnapMinutes(int minutes)
{
m_snapMinutes = normalizedSnap(minutes);
save();
}
bool AppSettings::trayHintShown() const
{
return m_trayHintShown;
}
void AppSettings::setTrayHintShown(bool shown)
{
m_trayHintShown = shown;
save();
}
QByteArray AppSettings::compactGeometry() const
{
return m_compactGeometry;
}
void AppSettings::setCompactGeometry(const QByteArray& geometry)
{
m_compactGeometry = geometry;
save();
}
QByteArray AppSettings::scheduleGeometry() const
{
return m_scheduleGeometry;
}
void AppSettings::setScheduleGeometry(const QByteArray& geometry)
{
m_scheduleGeometry = geometry;
save();
}
QByteArray AppSettings::scheduleSplitter() const
{
return m_scheduleSplitter;
}
void AppSettings::setScheduleSplitter(const QByteArray& state)
{
m_scheduleSplitter = state;
save();
}
AiConfig AppSettings::aiConfig() const
{
return m_aiConfig;
}
SyncConfig AppSettings::syncConfig() const
{
return m_syncConfig;
}
void AppSettings::setSyncConfig(const SyncConfig& config)
{
m_syncConfig = config;
if (!m_syncConfig.serverUrl.trimmed().isEmpty())
{
m_syncConfig.serverUrl = m_syncConfig.serverUrl.trimmed();
}
m_syncConfig.token = m_syncConfig.token.trimmed();
save();
}
void AppSettings::setAiConfig(const AiConfig& config)
{
m_aiConfig = config;
if (m_aiConfig.baseUrl.trimmed().isEmpty())
{
m_aiConfig.baseUrl = AiConfig{}.baseUrl;
}
if (m_aiConfig.model.trimmed().isEmpty())
{
m_aiConfig.model = AiConfig{}.model;
}
save();
}
+89
View File
@@ -0,0 +1,89 @@
#pragma once
#include <QByteArray>
#include <QString>
/*
* 类名: AiConfig
* 功能: OpenAI 兼容服务的本地配置(阶段 2 使用)
* 线程安全: 否(值类型)
*/
struct SyncConfig
{
bool enabled = false;
QString serverUrl;
QString token;
};
struct AiConfig
{
QString baseUrl = QStringLiteral("https://api.openai.com/v1");
QString apiKey;
QString model = QStringLiteral("gpt-4o-mini");
double temperature = 0.2;
};
/*
* 类名: AppSettings
* 功能: 应用配置持久化(TOML 配置文件),配置与代码分离
* 线程安全: 否;主线程使用
*/
class AppSettings
{
public:
explicit AppSettings(QString configPath = {});
QString configPath() const;
QString databasePath() const;
QString deviceId();
QString themePreference() const;
void setThemePreference(const QString& preference);
bool micaEnabled() const;
void setMicaEnabled(bool enabled);
int snapMinutes() const;
void setSnapMinutes(int minutes);
bool trayHintShown() const;
void setTrayHintShown(bool shown);
QByteArray compactGeometry() const;
void setCompactGeometry(const QByteArray& geometry);
QByteArray scheduleGeometry() const;
void setScheduleGeometry(const QByteArray& geometry);
QByteArray scheduleSplitter() const;
void setScheduleSplitter(const QByteArray& state);
AiConfig aiConfig() const;
void setAiConfig(const AiConfig& config);
SyncConfig syncConfig() const;
void setSyncConfig(const SyncConfig& config);
void save();
private:
void load();
void loadLegacyQSettings();
void applyDefaults();
bool isUsingDefaultPath() const;
QString m_configPath;
bool m_useDefaultPath = true;
QString m_databasePath;
QString m_deviceId;
QString m_themePreference = QStringLiteral("system");
bool m_micaEnabled = false;
int m_snapMinutes = 15;
bool m_trayHintShown = false;
QByteArray m_compactGeometry;
QByteArray m_scheduleGeometry;
QByteArray m_scheduleSplitter;
AiConfig m_aiConfig;
SyncConfig m_syncConfig;
};
+45
View File
@@ -0,0 +1,45 @@
add_executable(test_storage test_storage.cpp)
target_link_libraries(test_storage PRIVATE schedule_core Qt6::Test schedule_warnings)
add_test(NAME storage COMMAND test_storage)
add_executable(test_services test_services.cpp)
target_link_libraries(test_services PRIVATE schedule_services Qt6::Test schedule_warnings)
add_test(NAME services COMMAND test_services)
add_executable(test_grid test_grid.cpp)
target_link_libraries(test_grid PRIVATE schedule_ui Qt6::Test schedule_warnings)
add_test(NAME grid COMMAND test_grid)
add_executable(test_mainwindow test_mainwindow.cpp)
target_link_libraries(test_mainwindow PRIVATE schedule_ui Qt6::Test schedule_warnings)
add_test(NAME mainwindow COMMAND test_mainwindow)
add_executable(test_compactwindow test_compactwindow.cpp)
target_link_libraries(test_compactwindow PRIVATE schedule_ui Qt6::Test schedule_warnings)
add_test(NAME compactwindow COMMAND test_compactwindow)
add_executable(test_config test_config.cpp)
target_link_libraries(test_config PRIVATE schedule_services Qt6::Test schedule_warnings)
add_test(NAME config COMMAND test_config)
add_executable(test_scheduler test_scheduler.cpp)
target_link_libraries(test_scheduler PRIVATE schedule_core Qt6::Test schedule_warnings)
add_test(NAME scheduler COMMAND test_scheduler)
add_executable(test_ai test_ai.cpp)
target_link_libraries(test_ai PRIVATE schedule_ai Qt6::Test schedule_warnings)
add_test(NAME ai COMMAND test_ai)
add_executable(test_openai_provider test_openai_provider.cpp)
target_link_libraries(test_openai_provider PRIVATE schedule_ai Qt6::Test schedule_warnings)
add_test(NAME openai_provider COMMAND test_openai_provider)
add_executable(test_sync_integration test_sync_integration.cpp)
target_link_libraries(test_sync_integration PRIVATE schedule_sync Qt6::Test schedule_warnings)
add_test(NAME sync_integration COMMAND test_sync_integration)
if(TARGET schedule-sync-server)
add_dependencies(test_sync_integration schedule-sync-server)
set_tests_properties(sync_integration PROPERTIES
ENVIRONMENT "SCHEDULE_SYNC_SERVER_BIN=${CMAKE_BINARY_DIR}/bin/schedule-sync-server${CMAKE_EXECUTABLE_SUFFIX}"
)
endif()
+746
View File
@@ -0,0 +1,746 @@
#include <QFile>
#include <QJsonArray>
#include <QJsonObject>
#include <QSignalSpy>
#include <QTemporaryDir>
#include <QtTest>
#include <memory>
#include "ai/AIService.h"
#include "ai/IAIProvider.h"
#include "core/DateTimeUtils.h"
#include "services/ScheduleService.h"
#include "storage/SqliteStore.h"
#include "utils/AppSettings.h"
class MockProvider : public ai::IAIProvider
{
public:
QStringList responses;
int calls = 0;
QJsonArray lastMessages;
AiConfig lastConfig;
QString name() const override
{
return QStringLiteral("mock");
}
void cancel() override
{
}
void streamCompletion(const AiConfig& config,
const QJsonArray& messages,
ai::CompletionCallbacks callbacks) override
{
lastConfig = config;
lastMessages = messages;
const QString response = responses.value(calls);
++calls;
if (response.startsWith(QStringLiteral("ERROR:")))
{
if (callbacks.onError)
{
callbacks.onError(response.mid(6).trimmed());
}
return;
}
// 小分片模拟流式响应,同时验证标记跨分片解析。
for (int i = 0; i < response.size(); i += 5)
{
if (callbacks.onDelta)
{
callbacks.onDelta(response.mid(i, 5));
}
}
if (callbacks.onFinished)
{
callbacks.onFinished();
}
}
};
class TestAI : public QObject
{
Q_OBJECT
private slots:
void streamsReplyAndAppliesProposal();
void repairsInvalidJsonOnce();
void chatWithoutDiffDoesNotCreateProposal();
void rejectsProposal();
void includesAttachedTextFile();
void keepsConversationHistory();
void operationsUpdateCreateDelete();
void rippleMovesConflictingBlock();
void partialAcceptanceCannotCreateOverlap();
void splitsLongTaskWhenNoSingleSlot();
void forcesSplitWhenUserAllowsIt();
void localDeleteAllMeetingsFallback();
void retriesNoDiffActionableRequest();
};
namespace
{
struct Context
{
QTemporaryDir dir;
std::unique_ptr<SqliteStore> store;
std::unique_ptr<ScheduleService> service;
std::unique_ptr<AppSettings> settings;
MockProvider* mock = nullptr;
std::unique_ptr<AIService> ai;
bool initialize()
{
if (!dir.isValid())
{
return false;
}
store = std::make_unique<SqliteStore>(dir.filePath(QStringLiteral("schedule.db")));
QString error;
if (!store->open(&error))
{
qWarning() << error;
return false;
}
service = std::make_unique<ScheduleService>(*store, QStringLiteral("ai-test-device"));
settings = std::make_unique<AppSettings>(dir.filePath(QStringLiteral("config.toml")));
AiConfig config;
config.baseUrl = QStringLiteral("http://localhost/v1");
config.apiKey = QStringLiteral("test-key");
config.model = QStringLiteral("test-model");
settings->setAiConfig(config);
auto provider = std::make_unique<MockProvider>();
mock = provider.get();
ai = std::make_unique<AIService>(*service, *store, *settings, std::move(provider));
return true;
}
};
QString diffResponse(const QString& reply, const QString& tasksJson)
{
return reply + QStringLiteral("\n@@DIFF@@\n") + tasksJson;
}
QString taskJson(const QString& title,
int minutes,
const QDateTime& preferredStart,
const QDateTime& preferredEnd)
{
return QStringLiteral(
"{\"tasks\":[{\"title\":\"%1\",\"duration_min\":%2,\"priority\":2,"
"\"preferred_start\":\"%3\",\"preferred_end\":\"%4\"}]}")
.arg(title)
.arg(minutes)
.arg(preferredStart.toString(QStringLiteral("yyyy-MM-ddTHH:mm:ss")),
preferredEnd.toString(QStringLiteral("yyyy-MM-ddTHH:mm:ss")));
}
QString joinDeltas(const QSignalSpy& spy)
{
QString text;
for (const QList<QVariant>& args : spy)
{
text += args.at(0).toString();
}
return text;
}
} // namespace
void TestAI::streamsReplyAndAppliesProposal()
{
Context context;
QVERIFY(context.initialize());
const QDate tomorrow = QDate::currentDate().addDays(1);
const QDateTime preferredStart(tomorrow, QTime(14, 0), Qt::LocalTime);
const QDateTime preferredEnd(tomorrow, QTime(16, 0), Qt::LocalTime);
context.mock->responses = {
diffResponse(QStringLiteral("好的,我来安排。"),
taskJson(QStringLiteral("写周报"), 120, preferredStart, preferredEnd))};
QSignalSpy deltaSpy(context.ai.get(), &AIService::streamDelta);
QSignalSpy proposalSpy(context.ai.get(), &AIService::proposalReady);
QSignalSpy finishedSpy(context.ai.get(), &AIService::requestFinished);
QSignalSpy failedSpy(context.ai.get(), &AIService::requestFailed);
QSignalSpy appliedSpy(context.ai.get(), &AIService::diffApplied);
QSignalSpy noticeSpy(context.ai.get(), &AIService::notice);
context.ai->request(QStringLiteral("明天下午写周报 2 小时"));
QCOMPARE(failedSpy.count(), 0);
QCOMPARE(noticeSpy.count(), 0);
QCOMPARE(finishedSpy.count(), 1);
QCOMPARE(proposalSpy.count(), 1);
QVERIFY(joinDeltas(deltaSpy).contains(QStringLiteral("好的")));
QVERIFY(!joinDeltas(deltaSpy).contains(QStringLiteral("@@DIFF@@")));
const ScheduleProposal proposal = proposalSpy.at(0).at(0).value<ScheduleProposal>();
QCOMPARE(proposal.entries.size(), 1);
QCOMPARE(proposal.entries.first().title, QStringLiteral("写周报"));
QCOMPARE(proposal.entries.first().startAt, preferredStart);
QCOMPARE(proposal.entries.first().endAt, preferredEnd);
const auto stored = context.store->proposedDiffById(proposal.diffId);
QVERIFY(stored.has_value());
QCOMPARE(stored->state, QStringLiteral("pending"));
context.ai->applyDiff(proposal.diffId, {proposal.entries.first().tempId});
QCOMPARE(appliedSpy.count(), 1);
const auto applied = context.store->proposedDiffById(proposal.diffId);
QVERIFY(applied.has_value());
QCOMPARE(applied->state, QStringLiteral("applied"));
const QVector<ScheduleItem> items = context.service->itemsForDay(tomorrow);
QCOMPARE(items.size(), 1);
QCOMPARE(items.first().task.title, QStringLiteral("写周报"));
QCOMPARE(items.first().task.source, QStringLiteral("ai_chat"));
QCOMPARE(items.first().block.startAt, preferredStart);
}
void TestAI::repairsInvalidJsonOnce()
{
Context context;
QVERIFY(context.initialize());
const QDate tomorrow = QDate::currentDate().addDays(1);
const QDateTime preferredStart(tomorrow, QTime(10, 0), Qt::LocalTime);
const QDateTime preferredEnd(tomorrow, QTime(11, 0), Qt::LocalTime);
context.mock->responses = {
diffResponse(QStringLiteral("我先安排一下。"), QStringLiteral("{not valid json")),
taskJson(QStringLiteral("复习"), 60, preferredStart, preferredEnd)};
QSignalSpy proposalSpy(context.ai.get(), &AIService::proposalReady);
QSignalSpy failedSpy(context.ai.get(), &AIService::requestFailed);
context.ai->request(QStringLiteral("明天上午复习一小时"));
QTRY_COMPARE_WITH_TIMEOUT(proposalSpy.count(), 1, 3000);
QCOMPARE(failedSpy.count(), 0);
QCOMPARE(context.mock->calls, 2);
const ScheduleProposal proposal = proposalSpy.at(0).at(0).value<ScheduleProposal>();
QCOMPARE(proposal.entries.size(), 1);
QCOMPARE(proposal.entries.first().title, QStringLiteral("复习"));
QCOMPARE(proposal.entries.first().startAt, preferredStart);
}
void TestAI::chatWithoutDiffDoesNotCreateProposal()
{
Context context;
QVERIFY(context.initialize());
context.mock->responses = {QStringLiteral("你好,我是日程助手。")};
QSignalSpy deltaSpy(context.ai.get(), &AIService::streamDelta);
QSignalSpy proposalSpy(context.ai.get(), &AIService::proposalReady);
QSignalSpy finishedSpy(context.ai.get(), &AIService::requestFinished);
QSignalSpy failedSpy(context.ai.get(), &AIService::requestFailed);
context.ai->request(QStringLiteral("你能做什么?"));
QCOMPARE(failedSpy.count(), 0);
QCOMPARE(finishedSpy.count(), 1);
QCOMPARE(proposalSpy.count(), 0);
QVERIFY(joinDeltas(deltaSpy).contains(QStringLiteral("日程助手")));
}
void TestAI::rejectsProposal()
{
Context context;
QVERIFY(context.initialize());
const QDate tomorrow = QDate::currentDate().addDays(1);
const QDateTime preferredStart(tomorrow, QTime(9, 0), Qt::LocalTime);
const QDateTime preferredEnd(tomorrow, QTime(10, 0), Qt::LocalTime);
context.mock->responses = {
diffResponse(QStringLiteral("建议如下。"),
taskJson(QStringLiteral("整理资料"), 60, preferredStart, preferredEnd))};
QSignalSpy proposalSpy(context.ai.get(), &AIService::proposalReady);
QSignalSpy rejectedSpy(context.ai.get(), &AIService::diffRejected);
context.ai->request(QStringLiteral("明天上午整理资料"));
QCOMPARE(proposalSpy.count(), 1);
const ScheduleProposal proposal = proposalSpy.at(0).at(0).value<ScheduleProposal>();
context.ai->rejectDiff(proposal.diffId);
QCOMPARE(rejectedSpy.count(), 1);
QVERIFY(context.service->itemsForDay(tomorrow).isEmpty());
const auto stored = context.store->proposedDiffById(proposal.diffId);
QVERIFY(stored.has_value());
QCOMPARE(stored->state, QStringLiteral("rejected"));
}
void TestAI::includesAttachedTextFile()
{
Context context;
QVERIFY(context.initialize());
const QString filePath = context.dir.filePath(QStringLiteral("需求.txt"));
QFile file(filePath);
QVERIFY(file.open(QIODevice::WriteOnly | QIODevice::Text));
file.write("下周准备产品发布会材料,需要两小时。");
file.close();
context.mock->responses = {QStringLiteral("已收到附件内容。")};
QSignalSpy finishedSpy(context.ai.get(), &AIService::requestFinished);
QSignalSpy failedSpy(context.ai.get(), &AIService::requestFailed);
context.ai->request(QStringLiteral("请分析附件"), {filePath});
QTRY_COMPARE_WITH_TIMEOUT(context.mock->calls, 1, 5000);
QTRY_COMPARE_WITH_TIMEOUT(finishedSpy.count(), 1, 5000);
QCOMPARE(failedSpy.count(), 0);
QCOMPARE(context.mock->lastMessages.size(), 2);
const QString userContent =
context.mock->lastMessages.at(1).toObject().value(QStringLiteral("content")).toString();
QVERIFY(userContent.contains(QStringLiteral("产品发布会材料")));
}
void TestAI::keepsConversationHistory()
{
Context context;
QVERIFY(context.initialize());
context.mock->responses = {QStringLiteral("你好,我在。"), QStringLiteral("当然可以。")};
QSignalSpy finishedSpy(context.ai.get(), &AIService::requestFinished);
context.ai->request(QStringLiteral("第一句"));
QCOMPARE(finishedSpy.count(), 1);
context.ai->request(QStringLiteral("第二句"));
QCOMPARE(finishedSpy.count(), 2);
QCOMPARE(context.mock->calls, 2);
const QJsonArray messages = context.mock->lastMessages;
QVERIFY(messages.size() >= 4);
bool sawFirstUser = false;
bool sawFirstAssistant = false;
for (const QJsonValue& value : messages)
{
const QJsonObject message = value.toObject();
if (message.value(QStringLiteral("content")).toString() == QStringLiteral("第一句"))
{
sawFirstUser = true;
}
if (message.value(QStringLiteral("content")).toString() == QStringLiteral("你好,我在。"))
{
sawFirstAssistant = true;
}
}
QVERIFY(sawFirstUser);
QVERIFY(sawFirstAssistant);
}
void TestAI::operationsUpdateCreateDelete()
{
Context context;
QVERIFY(context.initialize());
const QDate tomorrow = QDate::currentDate().addDays(1);
const QDateTime oldStart(tomorrow, QTime(9, 0), Qt::LocalTime);
const QDateTime oldEnd(tomorrow, QTime(10, 0), Qt::LocalTime);
const QDateTime deleteStart(tomorrow, QTime(11, 0), Qt::LocalTime);
const QDateTime deleteEnd(tomorrow, QTime(12, 0), Qt::LocalTime);
QString error;
QVERIFY(context.service->createBlock(QStringLiteral("旧任务"), oldStart, oldEnd, &error));
QVERIFY(context.service->createBlock(QStringLiteral("删除任务"), deleteStart, deleteEnd, &error));
const QDateTime updateStart(tomorrow, QTime(14, 0), Qt::LocalTime);
const QDateTime updateEnd(tomorrow, QTime(15, 0), Qt::LocalTime);
const QDateTime createStart(tomorrow, QTime(16, 0), Qt::LocalTime);
const QDateTime createEnd(tomorrow, QTime(17, 0), Qt::LocalTime);
context.mock->responses = {
QStringLiteral(
"好的,我调整一下。\n@@DIFF@@\n"
"{\"operations\":["
"{\"type\":\"update\",\"target_ref\":\"b1\",\"title\":\"新任务\","
"\"preferred_start\":\"%1T14:00:00\",\"preferred_end\":\"%1T15:00:00\"},"
"{\"type\":\"create\",\"title\":\"新安排\",\"duration_min\":60,"
"\"preferred_start\":\"%1T16:00:00\",\"preferred_end\":\"%1T17:00:00\"},"
"{\"type\":\"delete\",\"target_ref\":\"b2\"}]}")
.arg(tomorrow.toString(QStringLiteral("yyyy-MM-dd"))),
};
QSignalSpy proposalSpy(context.ai.get(), &AIService::proposalReady);
QSignalSpy failedSpy(context.ai.get(), &AIService::requestFailed);
QSignalSpy appliedSpy(context.ai.get(), &AIService::diffApplied);
QSignalSpy applyFailedSpy(context.ai.get(), &AIService::diffApplyFailed);
context.ai->request(QStringLiteral("把旧任务改到下午两点,四点新增安排,删掉十一点的会议"));
QCOMPARE(failedSpy.count(), 0);
QCOMPARE(proposalSpy.count(), 1);
const ScheduleProposal proposal = proposalSpy.at(0).at(0).value<ScheduleProposal>();
QStringList tempIds;
bool sawUpdate = false;
bool sawCreate = false;
bool sawDelete = false;
for (const ProposedScheduleEntry& entry : proposal.entries)
{
tempIds.append(entry.tempId);
if (entry.operation == ProposedOperation::Update)
{
sawUpdate = true;
QCOMPARE(entry.oldTitle, QStringLiteral("旧任务"));
QCOMPARE(entry.title, QStringLiteral("新任务"));
QCOMPARE(entry.oldStartAt, oldStart);
QCOMPARE(entry.startAt, updateStart);
}
else if (entry.operation == ProposedOperation::Create)
{
sawCreate = true;
QCOMPARE(entry.title, QStringLiteral("新安排"));
QCOMPARE(entry.startAt, createStart);
}
else if (entry.operation == ProposedOperation::Delete)
{
sawDelete = true;
QCOMPARE(entry.oldTitle, QStringLiteral("删除任务"));
}
}
QVERIFY(sawUpdate);
QVERIFY(sawCreate);
QVERIFY(sawDelete);
context.ai->applyDiff(proposal.diffId, tempIds);
QCOMPARE(applyFailedSpy.count(), 0);
QCOMPARE(appliedSpy.count(), 1);
const QVector<ScheduleItem> items = context.service->itemsForDay(tomorrow);
QCOMPARE(items.size(), 2);
bool foundUpdated = false;
bool foundCreated = false;
for (const ScheduleItem& item : items)
{
if (item.task.title == QStringLiteral("新任务"))
{
foundUpdated = true;
QCOMPARE(item.block.startAt, updateStart);
QCOMPARE(item.block.endAt, updateEnd);
}
if (item.task.title == QStringLiteral("新安排"))
{
foundCreated = true;
QCOMPARE(item.block.startAt, createStart);
QCOMPARE(item.block.endAt, createEnd);
}
QVERIFY(item.task.title != QStringLiteral("删除任务"));
}
QVERIFY(foundUpdated);
QVERIFY(foundCreated);
}
void TestAI::rippleMovesConflictingBlock()
{
Context context;
QVERIFY(context.initialize());
const QDate tomorrow = QDate::currentDate().addDays(1);
const QDateTime existingStart(tomorrow, QTime(14, 0), Qt::LocalTime);
const QDateTime existingEnd(tomorrow, QTime(15, 0), Qt::LocalTime);
QString error;
QVERIFY(context.service->createBlock(QStringLiteral("已有日程"), existingStart, existingEnd, &error));
context.mock->responses = {
QStringLiteral(
"好的,我把它插进去。\n@@DIFF@@\n"
"{\"operations\":[{\"type\":\"create\",\"title\":\"插入任务\","
"\"duration_min\":60,\"preferred_start\":\"%1T14:00:00\","
"\"preferred_end\":\"%1T15:00:00\"}]}")
.arg(tomorrow.toString(QStringLiteral("yyyy-MM-dd"))),
};
QSignalSpy proposalSpy(context.ai.get(), &AIService::proposalReady);
QSignalSpy failedSpy(context.ai.get(), &AIService::requestFailed);
context.ai->request(QStringLiteral("明天下午两点插入一个一小时任务"));
QCOMPARE(failedSpy.count(), 0);
QCOMPARE(proposalSpy.count(), 1);
const ScheduleProposal proposal = proposalSpy.at(0).at(0).value<ScheduleProposal>();
QCOMPARE(proposal.entries.size(), 2);
bool sawCreate = false;
bool sawMove = false;
QStringList tempIds;
for (const ProposedScheduleEntry& entry : proposal.entries)
{
tempIds.append(entry.tempId);
if (entry.operation == ProposedOperation::Create &&
entry.title == QStringLiteral("插入任务"))
{
sawCreate = true;
QCOMPARE(entry.startAt, existingStart);
}
if (entry.operation == ProposedOperation::Update &&
entry.oldTitle == QStringLiteral("已有日程"))
{
sawMove = true;
QCOMPARE(entry.startAt, existingEnd);
QCOMPARE(entry.endAt, existingEnd.addSecs(3600));
}
}
QVERIFY(sawCreate);
QVERIFY(sawMove);
context.ai->applyDiff(proposal.diffId, tempIds);
const QVector<ScheduleItem> items = context.service->itemsForDay(tomorrow);
QCOMPARE(items.size(), 2);
for (const ScheduleItem& item : items)
{
if (item.task.title == QStringLiteral("插入任务"))
{
QCOMPARE(item.block.startAt, existingStart);
}
if (item.task.title == QStringLiteral("已有日程"))
{
QCOMPARE(item.block.startAt, existingEnd);
}
}
}
void TestAI::partialAcceptanceCannotCreateOverlap()
{
Context context;
QVERIFY(context.initialize());
const QDate tomorrow = QDate::currentDate().addDays(1);
const QDateTime existingStart(tomorrow, QTime(14, 0), Qt::LocalTime);
const QDateTime existingEnd(tomorrow, QTime(15, 0), Qt::LocalTime);
QString error;
QVERIFY(context.service->createBlock(QStringLiteral("已有日程"), existingStart, existingEnd, &error));
context.mock->responses = {
QStringLiteral(
"好的。\n@@DIFF@@\n"
"{\"operations\":[{\"type\":\"create\",\"title\":\"插入任务\","
"\"duration_min\":60,\"preferred_start\":\"%1T14:00:00\","
"\"preferred_end\":\"%1T15:00:00\"}]}")
.arg(tomorrow.toString(QStringLiteral("yyyy-MM-dd"))),
};
QSignalSpy proposalSpy(context.ai.get(), &AIService::proposalReady);
QSignalSpy applyFailedSpy(context.ai.get(), &AIService::diffApplyFailed);
context.ai->request(QStringLiteral("明天下午两点插入一个一小时任务"));
QCOMPARE(proposalSpy.count(), 1);
const ScheduleProposal proposal = proposalSpy.at(0).at(0).value<ScheduleProposal>();
QString createTempId;
for (const ProposedScheduleEntry& entry : proposal.entries)
{
if (entry.operation == ProposedOperation::Create)
{
createTempId = entry.tempId;
}
}
QVERIFY(!createTempId.isEmpty());
// 只接受新增、不接受涟漪移动,应被服务层冲突检查拒绝。
context.ai->applyDiff(proposal.diffId, {createTempId});
QCOMPARE(applyFailedSpy.count(), 1);
const QVector<ScheduleItem> items = context.service->itemsForDay(tomorrow);
QCOMPARE(items.size(), 1);
QCOMPARE(items.first().task.title, QStringLiteral("已有日程"));
}
void TestAI::splitsLongTaskWhenNoSingleSlot()
{
Context context;
QVERIFY(context.initialize());
const QDate today = QDate::currentDate();
const QDate tomorrow = today.addDays(1);
QString error;
for (const QDate& day : {today, tomorrow})
{
QVERIFY(context.service->createBlock(QStringLiteral("占用一"),
QDateTime(day, QTime(8, 0), Qt::LocalTime),
QDateTime(day, QTime(12, 0), Qt::LocalTime),
&error));
QVERIFY(context.service->createBlock(QStringLiteral("占用二"),
QDateTime(day, QTime(13, 0), Qt::LocalTime),
QDateTime(day, QTime(17, 0), Qt::LocalTime),
&error));
QVERIFY(context.service->createBlock(QStringLiteral("占用三"),
QDateTime(day, QTime(18, 0), Qt::LocalTime),
QDateTime(day, QTime(22, 0), Qt::LocalTime),
&error));
}
context.mock->responses = {
QStringLiteral(
"好的,我拆分安排。\n@@DIFF@@\n"
"{\"operations\":[{\"type\":\"create\",\"title\":\"长任务\","
"\"duration_min\":120,\"splittable\":true,"
"\"deadline\":\"%1T22:00:00\"}]}")
.arg(tomorrow.toString(QStringLiteral("yyyy-MM-dd"))),
};
QSignalSpy proposalSpy(context.ai.get(), &AIService::proposalReady);
QSignalSpy failedSpy(context.ai.get(), &AIService::requestFailed);
QSignalSpy noticeSpy(context.ai.get(), &AIService::notice);
context.ai->request(QStringLiteral("明天之前找时间做两小时长任务,可以拆开"));
QCOMPARE(failedSpy.count(), 0);
QCOMPARE(proposalSpy.count(), 1);
const ScheduleProposal proposal = proposalSpy.at(0).at(0).value<ScheduleProposal>();
QCOMPARE(proposal.entries.size(), 1);
const ProposedScheduleEntry entry = proposal.entries.first();
QCOMPARE(entry.operation, ProposedOperation::Create);
QCOMPARE(entry.title, QStringLiteral("长任务"));
QCOMPARE(entry.segments.size(), 2);
QVERIFY(!noticeSpy.isEmpty());
QStringList tempIds{entry.tempId};
QSignalSpy appliedSpy(context.ai.get(), &AIService::diffApplied);
context.ai->applyDiff(proposal.diffId, tempIds);
QCOMPARE(appliedSpy.count(), 1);
QVector<ScheduleItem> splitBlocks;
for (const QDate& day : {today, tomorrow})
{
for (const ScheduleItem& item : context.service->itemsForDay(day))
{
if (item.task.title == QStringLiteral("长任务"))
{
splitBlocks.append(item);
}
}
}
QCOMPARE(splitBlocks.size(), 2);
QCOMPARE(splitBlocks.first().task.id, splitBlocks.last().task.id);
int totalMinutes = 0;
for (const ScheduleItem& item : splitBlocks)
{
totalMinutes += DateTimeUtils::minutesBetween(item.block.startAt, item.block.endAt);
}
QCOMPARE(totalMinutes, 120);
}
void TestAI::forcesSplitWhenUserAllowsIt()
{
Context context;
QVERIFY(context.initialize());
const QDate today = QDate::currentDate();
const QDate tomorrow = today.addDays(1);
QString error;
for (const QDate& day : {today, tomorrow})
{
QVERIFY(context.service->createBlock(QStringLiteral("占用一"),
QDateTime(day, QTime(8, 0), Qt::LocalTime),
QDateTime(day, QTime(12, 0), Qt::LocalTime),
&error));
QVERIFY(context.service->createBlock(QStringLiteral("占用二"),
QDateTime(day, QTime(13, 0), Qt::LocalTime),
QDateTime(day, QTime(17, 0), Qt::LocalTime),
&error));
QVERIFY(context.service->createBlock(QStringLiteral("占用三"),
QDateTime(day, QTime(18, 0), Qt::LocalTime),
QDateTime(day, QTime(22, 0), Qt::LocalTime),
&error));
}
// 模型没有设置 splittable,但用户明确说“可以拆开”,AIService 应主动强制拆分。
context.mock->responses = {
QStringLiteral(
"好的,我拆分安排。\n@@DIFF@@\n"
"{\"operations\":[{\"type\":\"create\",\"title\":\"长任务\","
"\"duration_min\":120,\"deadline\":\"%1T22:00:00\"}]}")
.arg(tomorrow.toString(QStringLiteral("yyyy-MM-dd"))),
};
QSignalSpy proposalSpy(context.ai.get(), &AIService::proposalReady);
QSignalSpy failedSpy(context.ai.get(), &AIService::requestFailed);
context.ai->request(QStringLiteral("明天之前找时间做两小时长任务,可以拆开"));
QCOMPARE(failedSpy.count(), 0);
QCOMPARE(proposalSpy.count(), 1);
const ScheduleProposal proposal = proposalSpy.at(0).at(0).value<ScheduleProposal>();
QCOMPARE(proposal.entries.size(), 1);
QCOMPARE(proposal.entries.first().operation, ProposedOperation::Create);
QCOMPARE(proposal.entries.first().segments.size(), 2);
}
void TestAI::localDeleteAllMeetingsFallback()
{
Context context;
QVERIFY(context.initialize());
const QDate tomorrow = QDate::currentDate().addDays(1);
QString error;
QVERIFY(context.service->createBlock(QStringLiteral("写周报"),
QDateTime(tomorrow, QTime(9, 0), Qt::LocalTime),
QDateTime(tomorrow, QTime(10, 0), Qt::LocalTime),
&error));
QVERIFY(context.service->createBlock(QStringLiteral("团队同步"),
QDateTime(tomorrow, QTime(11, 0), Qt::LocalTime),
QDateTime(tomorrow, QTime(12, 0), Qt::LocalTime),
&error));
QVERIFY(context.service->createBlock(QStringLiteral("健身"),
QDateTime(tomorrow, QTime(15, 0), Qt::LocalTime),
QDateTime(tomorrow, QTime(16, 0), Qt::LocalTime),
&error));
QVERIFY(context.service->createBlock(QStringLiteral("项目会议"),
QDateTime(tomorrow, QTime(13, 0), Qt::LocalTime),
QDateTime(tomorrow, QTime(14, 0), Qt::LocalTime),
&error));
// 模型没有给出 diff,只追问;AIService 对“删除所有会议”做确定性兜底。
context.mock->responses = {QStringLiteral("请确认要删除哪些会议?")};
QSignalSpy proposalSpy(context.ai.get(), &AIService::proposalReady);
QSignalSpy failedSpy(context.ai.get(), &AIService::requestFailed);
QSignalSpy appliedSpy(context.ai.get(), &AIService::diffApplied);
context.ai->request(QStringLiteral("删除明天所有会议"));
QCOMPARE(failedSpy.count(), 0);
QCOMPARE(proposalSpy.count(), 1);
const ScheduleProposal proposal = proposalSpy.at(0).at(0).value<ScheduleProposal>();
QCOMPARE(proposal.entries.size(), 2);
QStringList tempIds;
QStringList titles;
for (const ProposedScheduleEntry& entry : proposal.entries)
{
QCOMPARE(entry.operation, ProposedOperation::Delete);
tempIds.append(entry.tempId);
titles.append(entry.oldTitle);
}
QVERIFY(titles.contains(QStringLiteral("团队同步")));
QVERIFY(titles.contains(QStringLiteral("项目会议")));
context.ai->applyDiff(proposal.diffId, tempIds);
QCOMPARE(appliedSpy.count(), 1);
const QVector<ScheduleItem> items = context.service->itemsForDay(tomorrow);
QCOMPARE(items.size(), 2);
for (const ScheduleItem& item : items)
{
QVERIFY(item.task.title != QStringLiteral("团队同步"));
QVERIFY(item.task.title != QStringLiteral("项目会议"));
}
}
void TestAI::retriesNoDiffActionableRequest()
{
Context context;
QVERIFY(context.initialize());
const QDate tomorrow = QDate::currentDate().addDays(1);
context.mock->responses = {
QStringLiteral("抱歉,我暂时无法安排。"),
QStringLiteral(
"重新整理完成。\n@@DIFF@@\n"
"{\"operations\":[{\"type\":\"create\",\"title\":\"深度工作\","
"\"duration_min\":180,\"deadline\":\"%1T22:00:00\"}]}")
.arg(tomorrow.toString(QStringLiteral("yyyy-MM-dd"))),
};
QSignalSpy proposalSpy(context.ai.get(), &AIService::proposalReady);
QSignalSpy failedSpy(context.ai.get(), &AIService::requestFailed);
context.ai->request(QStringLiteral("明天之前找时间做 3 小时深度工作,可以拆开"));
QTRY_COMPARE_WITH_TIMEOUT(proposalSpy.count(), 1, 3000);
QCOMPARE(failedSpy.count(), 0);
QCOMPARE(context.mock->calls, 2);
const ScheduleProposal proposal = proposalSpy.at(0).at(0).value<ScheduleProposal>();
QCOMPARE(proposal.entries.size(), 1);
QVERIFY(proposal.entries.first().title == QStringLiteral("深度工作"));
}
QTEST_GUILESS_MAIN(TestAI)
#include "test_ai.moc"
+447
View File
@@ -0,0 +1,447 @@
#include <QApplication>
#include <QDir>
#include <QTemporaryDir>
#include <QTimer>
#include <QtTest>
#include <memory>
#include "ElaApplication.h"
#include "ElaLineEdit.h"
#include "ElaPushButton.h"
#include "ElaToolButton.h"
#include "ai/AIService.h"
#include "services/NotificationService.h"
#include "services/ScheduleService.h"
#include "storage/SqliteStore.h"
#include "ui/CompactWindow.h"
#include "ui/MainWindow.h"
#include "ui/dialogs/SettingsDialog.h"
#include "ui/panels/DiffPreviewCard.h"
#include "ui/theme/ThemeManager.h"
#include "ui/views/ScheduleGridView.h"
#include "ui/theme/WindowEffects.h"
#include "utils/AppSettings.h"
class MockChatProvider : public ai::IAIProvider
{
public:
QString response;
QString name() const override
{
return QStringLiteral("mock");
}
void cancel() override
{
}
void streamCompletion(const AiConfig&,
const QJsonArray&,
ai::CompletionCallbacks callbacks) override
{
for (int i = 0; i < response.size(); i += 7)
{
if (callbacks.onDelta)
{
callbacks.onDelta(response.mid(i, 7));
}
}
if (callbacks.onFinished)
{
callbacks.onFinished();
}
}
};
class TestCompactWindow : public QObject
{
Q_OBJECT
private slots:
void initTestCase();
void compactOpensScheduleAndReturns();
void aiChatShowsDiffAndAccepts();
void aiChatShowsMultiOperationDiff();
private:
void createSampleData(ScheduleService& service, const QDate& today);
static void saveWindow(QWidget* widget, const QString& name);
QTemporaryDir m_tempDir;
std::unique_ptr<AppSettings> m_settings;
bool m_mica = false;
};
void TestCompactWindow::initTestCase()
{
QVERIFY(m_tempDir.isValid());
QCoreApplication::setOrganizationName(QStringLiteral("ScheduleTest"));
QCoreApplication::setApplicationName(QStringLiteral("ScheduleTest"));
QApplication::setStyle(QStringLiteral("Fusion"));
eApp->init();
m_settings = std::make_unique<AppSettings>(m_tempDir.filePath(QStringLiteral("config.toml")));
m_settings->setThemePreference(qEnvironmentVariable("SCHEDULE_TEST_THEME", QStringLiteral("system")));
m_mica = qEnvironmentVariableIsSet("SCHEDULE_TEST_MICA");
m_settings->setMicaEnabled(m_mica);
}
void TestCompactWindow::createSampleData(ScheduleService& service, const QDate& today)
{
const auto create = [&service](const QString& title,
const QDateTime& start,
const QDateTime& end,
const QString& status = QStringLiteral("scheduled")) {
QString error;
if (!service.createBlock(title, start, end, &error))
{
qWarning() << error;
return false;
}
if (status != QStringLiteral("scheduled"))
{
const QVector<ScheduleItem> items = service.itemsForDay(start.date());
for (const ScheduleItem& item : items)
{
if (item.task.title == title)
{
service.setBlockStatus(item.block.id, status, &error);
break;
}
}
}
return true;
};
QVERIFY(create(QStringLiteral("写周报"),
QDateTime(today, QTime(9, 0), Qt::LocalTime),
QDateTime(today, QTime(10, 30), Qt::LocalTime)));
QVERIFY(create(QStringLiteral("团队同步"),
QDateTime(today, QTime(10, 0), Qt::LocalTime),
QDateTime(today, QTime(11, 0), Qt::LocalTime)));
QVERIFY(create(QStringLiteral("设计评审"),
QDateTime(today, QTime(14, 0), Qt::LocalTime),
QDateTime(today, QTime(15, 0), Qt::LocalTime),
QStringLiteral("done")));
QVERIFY(create(QStringLiteral("整理邮件"),
QDateTime(today, QTime(16, 0), Qt::LocalTime),
QDateTime(today, QTime(16, 30), Qt::LocalTime),
QStringLiteral("dropped")));
QVERIFY(create(QStringLiteral("项目周会"),
QDateTime(today.addDays(-2), QTime(10, 0), Qt::LocalTime),
QDateTime(today.addDays(-2), QTime(11, 0), Qt::LocalTime)));
QVERIFY(create(QStringLiteral("深度阅读"),
QDateTime(today.addDays(3), QTime(15, 0), Qt::LocalTime),
QDateTime(today.addDays(3), QTime(16, 30), Qt::LocalTime)));
const QDate nextMonth = QDate(today.year(), today.month(), 1).addMonths(1);
QVERIFY(create(QStringLiteral("月度复盘"),
QDateTime(nextMonth.addDays(4), QTime(9, 0), Qt::LocalTime),
QDateTime(nextMonth.addDays(4), QTime(10, 30), Qt::LocalTime)));
const QDate earlier = QDate(today.year(), today.month(), 1).addMonths(-2);
QVERIFY(create(QStringLiteral("季度目标"),
QDateTime(earlier.addDays(9), QTime(13, 0), Qt::LocalTime),
QDateTime(earlier.addDays(9), QTime(15, 0), Qt::LocalTime)));
}
void TestCompactWindow::saveWindow(QWidget* widget, const QString& name)
{
const QString directory = qEnvironmentVariable("SCHEDULE_TEST_SCREENSHOTS");
if (directory.isEmpty() || !widget)
{
return;
}
QDir().mkpath(directory);
widget->grab().save(directory + QLatin1Char('/') + name);
}
void TestCompactWindow::compactOpensScheduleAndReturns()
{
QTemporaryDir databaseDir;
QVERIFY(databaseDir.isValid());
SqliteStore store(databaseDir.filePath(QStringLiteral("schedule.db")));
QString error;
QVERIFY2(store.open(&error), qPrintable(error));
ThemeManager theme(*m_settings);
theme.initialize();
ScheduleService service(store, QStringLiteral("compact-test"));
NotificationService notifications(service);
AIService aiService(service, store, *m_settings);
const QDate today = QDate::currentDate();
createSampleData(service, today);
CompactWindow compact(service, notifications, aiService, theme, *m_settings);
compact.show();
QVERIFY(QTest::qWaitForWindowExposed(&compact));
if (m_mica)
{
WindowEffects::applyMica(true);
QTest::qWait(4500);
}
else
{
QTest::qWait(300);
}
saveWindow(&compact, QStringLiteral("compact.png"));
ElaPushButton* openButton = nullptr;
for (ElaPushButton* button : compact.findChildren<ElaPushButton*>())
{
if (button->text() == QStringLiteral("详细日程"))
{
openButton = button;
break;
}
}
QVERIFY(openButton);
QTest::mouseClick(openButton, Qt::LeftButton);
QTest::qWait(300);
MainWindow* scheduleWindow = nullptr;
for (QWidget* widget : QApplication::topLevelWidgets())
{
if (auto* candidate = qobject_cast<MainWindow*>(widget))
{
scheduleWindow = candidate;
break;
}
}
QVERIFY(scheduleWindow);
QVERIFY(scheduleWindow->isVisible());
QVERIFY(!compact.isVisible());
if (auto* grid = scheduleWindow->findChild<ScheduleGridView*>())
{
grid->scrollToHour(8);
QTest::qWait(80);
}
saveWindow(scheduleWindow, QStringLiteral("schedule-day.png"));
scheduleWindow->setView(MainWindow::View::Month);
QTest::qWait(200);
QCOMPARE(scheduleWindow->view(), MainWindow::View::Month);
saveWindow(scheduleWindow, QStringLiteral("schedule-month.png"));
scheduleWindow->setView(MainWindow::View::Year);
QTest::qWait(200);
QCOMPARE(scheduleWindow->view(), MainWindow::View::Year);
saveWindow(scheduleWindow, QStringLiteral("schedule-year.png"));
scheduleWindow->setView(MainWindow::View::Day);
QTest::qWait(120);
scheduleWindow->close();
QTest::qWait(200);
QVERIFY(compact.isVisible());
ElaToolButton* settingsButton = nullptr;
for (ElaToolButton* button : compact.findChildren<ElaToolButton*>())
{
if (button->toolTip().startsWith(QStringLiteral("设置")))
{
settingsButton = button;
break;
}
}
QVERIFY(settingsButton);
QTimer::singleShot(400, []() {
for (QWidget* widget : QApplication::topLevelWidgets())
{
if (auto* dialog = qobject_cast<SettingsDialog*>(widget))
{
saveWindow(dialog, QStringLiteral("settings.png"));
dialog->reject();
}
}
});
QTimer::singleShot(2000, []() {
for (QWidget* widget : QApplication::topLevelWidgets())
{
if (auto* dialog = qobject_cast<SettingsDialog*>(widget))
{
dialog->reject();
}
}
});
QTest::mouseClick(settingsButton, Qt::LeftButton);
}
void TestCompactWindow::aiChatShowsDiffAndAccepts()
{
QTemporaryDir databaseDir;
QVERIFY(databaseDir.isValid());
SqliteStore store(databaseDir.filePath(QStringLiteral("schedule.db")));
QString error;
QVERIFY2(store.open(&error), qPrintable(error));
AiConfig config;
config.baseUrl = QStringLiteral("http://localhost/v1");
config.apiKey = QStringLiteral("test-key");
config.model = QStringLiteral("test-model");
m_settings->setAiConfig(config);
auto provider = std::make_unique<MockChatProvider>();
MockChatProvider* mock = provider.get();
const QDate tomorrow = QDate::currentDate().addDays(1);
mock->response = QStringLiteral(
"好的,我为你安排。\n@@DIFF@@\n"
"{\"tasks\":[{\"title\":\"写周报\",\"duration_min\":120,"
"\"priority\":2,\"preferred_start\":\"%1T14:00:00\","
"\"preferred_end\":\"%1T16:00:00\"}]}")
.arg(tomorrow.toString(QStringLiteral("yyyy-MM-dd")));
ThemeManager theme(*m_settings);
theme.initialize();
ScheduleService service(store, QStringLiteral("chat-ui-test"));
NotificationService notifications(service);
AIService aiService(service, store, *m_settings, std::move(provider));
CompactWindow compact(service, notifications, aiService, theme, *m_settings);
compact.show();
QVERIFY(QTest::qWaitForWindowExposed(&compact));
QTest::qWait(100);
ElaLineEdit* input = compact.findChild<ElaLineEdit*>();
QVERIFY(input);
input->setText(QStringLiteral("明天下午写周报 2 小时"));
ElaPushButton* sendButton = nullptr;
for (ElaPushButton* button : compact.findChildren<ElaPushButton*>())
{
if (button->text() == QStringLiteral("发送"))
{
sendButton = button;
break;
}
}
QVERIFY(sendButton);
QTest::mouseClick(sendButton, Qt::LeftButton);
QTest::qWait(150);
auto* card = compact.findChild<DiffPreviewCard*>();
QVERIFY(card);
saveWindow(&compact, QStringLiteral("chat-diff.png"));
ElaPushButton* acceptButton = nullptr;
for (ElaPushButton* button : card->findChildren<ElaPushButton*>())
{
if (button->text() == QStringLiteral("接受选中"))
{
acceptButton = button;
break;
}
}
QVERIFY(acceptButton);
QTest::mouseClick(acceptButton, Qt::LeftButton);
QTest::qWait(150);
const QVector<ScheduleItem> items = service.itemsForDay(tomorrow);
QCOMPARE(items.size(), 1);
QCOMPARE(items.first().task.title, QStringLiteral("写周报"));
QCOMPARE(items.first().task.source, QStringLiteral("ai_chat"));
saveWindow(&compact, QStringLiteral("chat-applied.png"));
}
void TestCompactWindow::aiChatShowsMultiOperationDiff()
{
QTemporaryDir databaseDir;
QVERIFY(databaseDir.isValid());
SqliteStore store(databaseDir.filePath(QStringLiteral("schedule.db")));
QString error;
QVERIFY2(store.open(&error), qPrintable(error));
AiConfig config;
config.baseUrl = QStringLiteral("http://localhost/v1");
config.apiKey = QStringLiteral("test-key");
config.model = QStringLiteral("test-model");
m_settings->setAiConfig(config);
ThemeManager theme(*m_settings);
theme.initialize();
ScheduleService service(store, QStringLiteral("chat-multi-test"));
NotificationService notifications(service);
const QDate tomorrow = QDate::currentDate().addDays(1);
QVERIFY(service.createBlock(QStringLiteral("已有日程"),
QDateTime(tomorrow, QTime(14, 0), Qt::LocalTime),
QDateTime(tomorrow, QTime(15, 0), Qt::LocalTime),
&error));
QVERIFY(service.createBlock(QStringLiteral("待删除"),
QDateTime(tomorrow, QTime(16, 0), Qt::LocalTime),
QDateTime(tomorrow, QTime(17, 0), Qt::LocalTime),
&error));
auto provider = std::make_unique<MockChatProvider>();
MockChatProvider* mock = provider.get();
mock->response = QStringLiteral(
"好的,我插入并清理一下。\n@@DIFF@@\n"
"{\"operations\":["
"{\"type\":\"create\",\"title\":\"插入任务\","
"\"duration_min\":60,\"preferred_start\":\"%1T14:00:00\","
"\"preferred_end\":\"%1T15:00:00\"},"
"{\"type\":\"delete\",\"target_ref\":\"b2\"}]}")
.arg(tomorrow.toString(QStringLiteral("yyyy-MM-dd")));
AIService aiService(service, store, *m_settings, std::move(provider));
CompactWindow compact(service, notifications, aiService, theme, *m_settings);
compact.show();
QVERIFY(QTest::qWaitForWindowExposed(&compact));
QTest::qWait(100);
ElaLineEdit* input = compact.findChild<ElaLineEdit*>();
QVERIFY(input);
input->setText(QStringLiteral("明天下午两点插入一小时任务,并删掉四点的会议"));
ElaPushButton* sendButton = nullptr;
for (ElaPushButton* button : compact.findChildren<ElaPushButton*>())
{
if (button->text() == QStringLiteral("发送"))
{
sendButton = button;
break;
}
}
QVERIFY(sendButton);
QTest::mouseClick(sendButton, Qt::LeftButton);
QTest::qWait(180);
auto* card = compact.findChild<DiffPreviewCard*>();
QVERIFY(card);
saveWindow(&compact, QStringLiteral("chat-multi-diff.png"));
ElaPushButton* acceptButton = nullptr;
for (ElaPushButton* button : card->findChildren<ElaPushButton*>())
{
if (button->text() == QStringLiteral("接受选中"))
{
acceptButton = button;
break;
}
}
QVERIFY(acceptButton);
QTest::mouseClick(acceptButton, Qt::LeftButton);
QTest::qWait(150);
saveWindow(&compact, QStringLiteral("chat-multi-applied.png"));
const QVector<ScheduleItem> items = service.itemsForDay(tomorrow);
QCOMPARE(items.size(), 2);
bool sawInsert = false;
bool sawMoved = false;
for (const ScheduleItem& item : items)
{
QVERIFY(item.task.title != QStringLiteral("待删除"));
if (item.task.title == QStringLiteral("插入任务"))
{
sawInsert = true;
QCOMPARE(item.block.startAt, QDateTime(tomorrow, QTime(14, 0), Qt::LocalTime));
}
if (item.task.title == QStringLiteral("已有日程"))
{
sawMoved = true;
QCOMPARE(item.block.startAt, QDateTime(tomorrow, QTime(15, 0), Qt::LocalTime));
}
}
QVERIFY(sawInsert);
QVERIFY(sawMoved);
}
QTEST_MAIN(TestCompactWindow)
#include "test_compactwindow.moc"
+107
View File
@@ -0,0 +1,107 @@
#include <QFile>
#include <QFileInfo>
#include <QTemporaryDir>
#include <QtTest>
#include "utils/AppSettings.h"
class TestConfig : public QObject
{
Q_OBJECT
private slots:
void defaultsAndRoundTrip();
void invalidFileFallsBack();
};
void TestConfig::defaultsAndRoundTrip()
{
QTemporaryDir dir;
QVERIFY(dir.isValid());
const QString path = dir.filePath(QStringLiteral("config.toml"));
QString deviceId;
{
AppSettings settings(path);
QVERIFY(QFileInfo::exists(path));
QCOMPARE(settings.configPath(), path);
QCOMPARE(settings.themePreference(), QStringLiteral("system"));
QCOMPARE(settings.micaEnabled(), false);
QCOMPARE(settings.snapMinutes(), 15);
QCOMPARE(settings.trayHintShown(), false);
QCOMPARE(settings.aiConfig().baseUrl, QStringLiteral("https://api.openai.com/v1"));
QCOMPARE(settings.aiConfig().model, QStringLiteral("gpt-4o-mini"));
QVERIFY(settings.aiConfig().apiKey.isEmpty());
deviceId = settings.deviceId();
QVERIFY(!deviceId.isEmpty());
settings.setThemePreference(QStringLiteral("dark"));
settings.setMicaEnabled(true);
settings.setSnapMinutes(30);
settings.setTrayHintShown(true);
settings.setCompactGeometry(QByteArray("compact-geometry"));
settings.setScheduleGeometry(QByteArray("schedule-geometry"));
settings.setScheduleSplitter(QByteArray("splitter-state"));
SyncConfig syncConfig;
syncConfig.enabled = true;
syncConfig.serverUrl = QStringLiteral("http://sync.test:8787");
syncConfig.token = QStringLiteral("sync-token");
settings.setSyncConfig(syncConfig);
AiConfig ai;
ai.baseUrl = QStringLiteral("https://example.test/v1");
ai.apiKey = QStringLiteral("test-secret-key");
ai.model = QStringLiteral("test-model");
ai.temperature = 0.7;
settings.setAiConfig(ai);
}
AppSettings reloaded(path);
QCOMPARE(reloaded.deviceId(), deviceId);
QCOMPARE(reloaded.themePreference(), QStringLiteral("dark"));
QCOMPARE(reloaded.micaEnabled(), true);
QCOMPARE(reloaded.snapMinutes(), 30);
QCOMPARE(reloaded.trayHintShown(), true);
QCOMPARE(reloaded.compactGeometry(), QByteArray("compact-geometry"));
QCOMPARE(reloaded.scheduleGeometry(), QByteArray("schedule-geometry"));
QCOMPARE(reloaded.scheduleSplitter(), QByteArray("splitter-state"));
QCOMPARE(reloaded.aiConfig().baseUrl, QStringLiteral("https://example.test/v1"));
QCOMPARE(reloaded.aiConfig().apiKey, QStringLiteral("test-secret-key"));
QCOMPARE(reloaded.aiConfig().model, QStringLiteral("test-model"));
QCOMPARE(reloaded.aiConfig().temperature, 0.7);
QCOMPARE(reloaded.syncConfig().enabled, true);
QCOMPARE(reloaded.syncConfig().serverUrl, QStringLiteral("http://sync.test:8787"));
QCOMPARE(reloaded.syncConfig().token, QStringLiteral("sync-token"));
#ifndef Q_OS_WIN
const auto permissions = QFileInfo(path).permissions();
QVERIFY(permissions.testFlag(QFileDevice::ReadOwner));
QVERIFY(permissions.testFlag(QFileDevice::WriteOwner));
QVERIFY(!permissions.testFlag(QFileDevice::ReadGroup));
QVERIFY(!permissions.testFlag(QFileDevice::ReadOther));
#endif
}
void TestConfig::invalidFileFallsBack()
{
QTemporaryDir dir;
QVERIFY(dir.isValid());
const QString path = dir.filePath(QStringLiteral("config.toml"));
QFile file(path);
QVERIFY(file.open(QIODevice::WriteOnly | QIODevice::Text));
file.write("this is not valid toml = [");
file.close();
AppSettings settings(path);
QCOMPARE(settings.themePreference(), QStringLiteral("system"));
QCOMPARE(settings.micaEnabled(), false);
QCOMPARE(settings.snapMinutes(), 15);
QVERIFY(!settings.deviceId().isEmpty());
QVERIFY(QFileInfo::exists(path + QStringLiteral(".bak")));
}
QTEST_GUILESS_MAIN(TestConfig)
#include "test_config.moc"
+163
View File
@@ -0,0 +1,163 @@
#include <QSignalSpy>
#include <QTemporaryDir>
#include <QtTest>
#include <memory>
#include "core/DateTimeUtils.h"
#include "ui/theme/ThemeManager.h"
#include "ui/views/ScheduleGridView.h"
#include "utils/AppSettings.h"
class TestGrid : public QObject
{
Q_OBJECT
private slots:
void initTestCase();
void createByDoubleClick();
void dragMovesBlock();
void resizeBottomEdge();
void doubleClickEditsBlock();
private:
ScheduleItem makeItem(const QString& id,
const QString& title,
const QDateTime& start,
const QDateTime& end) const;
void prepareView(ScheduleGridView& view, int hour);
QTemporaryDir m_tempDir;
std::unique_ptr<AppSettings> m_settings;
std::unique_ptr<ThemeManager> m_theme;
};
void TestGrid::initTestCase()
{
QVERIFY(m_tempDir.isValid());
QCoreApplication::setOrganizationName(QStringLiteral("ScheduleTest"));
QCoreApplication::setApplicationName(QStringLiteral("ScheduleTest"));
m_settings = std::make_unique<AppSettings>(m_tempDir.filePath(QStringLiteral("config.toml")));
m_theme = std::make_unique<ThemeManager>(*m_settings);
m_theme->initialize();
}
ScheduleItem TestGrid::makeItem(const QString& id,
const QString& title,
const QDateTime& start,
const QDateTime& end) const
{
ScheduleItem item;
item.task.id = QStringLiteral("task-") + id;
item.task.title = title;
item.block.id = id;
item.block.taskId = item.task.id;
item.block.startAt = start;
item.block.endAt = end;
return item;
}
void TestGrid::prepareView(ScheduleGridView& view, int hour)
{
view.resize(900, 600);
view.setDate(QDate::currentDate());
view.setTokens(m_theme->tokens());
view.show();
QVERIFY(QTest::qWaitForWindowExposed(&view));
QTest::qWait(30);
view.scrollToHour(hour);
QTest::qWait(20);
}
void TestGrid::createByDoubleClick()
{
ScheduleGridView view;
prepareView(view, 8);
QSignalSpy createSpy(&view, &ScheduleGridView::createRequested);
QTest::mouseDClick(view.viewport(), Qt::LeftButton, Qt::NoModifier, QPoint(300, 200), 10);
QTest::qWait(10);
QCOMPARE(createSpy.count(), 1);
const QDateTime start = createSpy.at(0).at(0).toDateTime();
const QDateTime end = createSpy.at(0).at(1).toDateTime();
QCOMPARE(start, QDateTime(QDate::currentDate(), QTime(8, 0), Qt::LocalTime));
QCOMPARE(end, start.addSecs(60 * 60));
}
void TestGrid::dragMovesBlock()
{
ScheduleGridView view;
prepareView(view, 8);
const QDate today = QDate::currentDate();
view.setBlocks({makeItem(QStringLiteral("block-1"),
QStringLiteral("写周报"),
QDateTime(today, QTime(9, 0), Qt::LocalTime),
QDateTime(today, QTime(10, 0), Qt::LocalTime))});
QTest::qWait(20);
QSignalSpy moveSpy(&view, &ScheduleGridView::moveRequested);
const QPoint startPoint(300, 380);
const QPoint endPoint(300, 500);
QTest::mousePress(view.viewport(), Qt::LeftButton, Qt::NoModifier, startPoint, 10);
QTest::mouseMove(view.viewport(), endPoint, 20);
QTest::mouseRelease(view.viewport(), Qt::LeftButton, Qt::NoModifier, endPoint, 10);
QTest::qWait(10);
QCOMPARE(moveSpy.count(), 1);
QCOMPARE(moveSpy.at(0).at(0).toString(), QStringLiteral("block-1"));
QCOMPARE(moveSpy.at(0).at(1).toDateTime(),
QDateTime(today, QTime(10, 0), Qt::LocalTime));
QCOMPARE(moveSpy.at(0).at(2).toDateTime(),
QDateTime(today, QTime(11, 0), Qt::LocalTime));
}
void TestGrid::resizeBottomEdge()
{
ScheduleGridView view;
prepareView(view, 8);
const QDate today = QDate::currentDate();
view.setBlocks({makeItem(QStringLiteral("block-2"),
QStringLiteral("写文档"),
QDateTime(today, QTime(9, 0), Qt::LocalTime),
QDateTime(today, QTime(10, 0), Qt::LocalTime))});
QTest::qWait(20);
QSignalSpy moveSpy(&view, &ScheduleGridView::moveRequested);
const QPoint edgePoint(300, 434);
const QPoint targetPoint(300, 470);
QTest::mousePress(view.viewport(), Qt::LeftButton, Qt::NoModifier, edgePoint, 10);
QTest::mouseMove(view.viewport(), targetPoint, 20);
QTest::mouseRelease(view.viewport(), Qt::LeftButton, Qt::NoModifier, targetPoint, 10);
QTest::qWait(10);
QCOMPARE(moveSpy.count(), 1);
QCOMPARE(moveSpy.at(0).at(1).toDateTime(),
QDateTime(today, QTime(9, 0), Qt::LocalTime));
QVERIFY(moveSpy.at(0).at(2).toDateTime() > QDateTime(today, QTime(10, 0), Qt::LocalTime));
}
void TestGrid::doubleClickEditsBlock()
{
ScheduleGridView view;
prepareView(view, 8);
const QDate today = QDate::currentDate();
view.setBlocks({makeItem(QStringLiteral("block-3"),
QStringLiteral("复盘"),
QDateTime(today, QTime(9, 0), Qt::LocalTime),
QDateTime(today, QTime(10, 0), Qt::LocalTime))});
QTest::qWait(20);
QSignalSpy editSpy(&view, &ScheduleGridView::editRequested);
QTest::mouseDClick(view.viewport(), Qt::LeftButton, Qt::NoModifier, QPoint(300, 350), 10);
QTest::qWait(10);
QCOMPARE(editSpy.count(), 1);
QCOMPARE(editSpy.at(0).at(0).toString(), QStringLiteral("block-3"));
}
QTEST_MAIN(TestGrid)
#include "test_grid.moc"
+132
View File
@@ -0,0 +1,132 @@
#include <QApplication>
#include <QScrollBar>
#include <QTemporaryDir>
#include <QTimer>
#include <QtTest>
#include <memory>
#include "core/ScheduleItem.h"
#include "services/NotificationService.h"
#include "services/ScheduleService.h"
#include "storage/SqliteStore.h"
#include "ui/MainWindow.h"
#include "ui/dialogs/BlockEditDialog.h"
#include "ui/theme/ThemeManager.h"
#include "ui/views/ScheduleGridView.h"
#include "utils/AppSettings.h"
#include "ElaLineEdit.h"
class TestMainWindow : public QObject
{
Q_OBJECT
private slots:
void initTestCase();
void createEditAndDeleteThroughUi();
private:
static void fillDialogAndAccept(const QString& title, bool accept);
QTemporaryDir m_tempDir;
std::unique_ptr<AppSettings> m_settings;
};
void TestMainWindow::initTestCase()
{
QVERIFY(m_tempDir.isValid());
QCoreApplication::setOrganizationName(QStringLiteral("ScheduleTest"));
QCoreApplication::setApplicationName(QStringLiteral("ScheduleTest"));
m_settings = std::make_unique<AppSettings>(m_tempDir.filePath(QStringLiteral("config.toml")));
}
void TestMainWindow::fillDialogAndAccept(const QString& title, bool accept)
{
QTimer::singleShot(400, [title, accept]() {
for (QWidget* widget : QApplication::topLevelWidgets())
{
auto* dialog = qobject_cast<BlockEditDialog*>(widget);
if (!dialog)
{
continue;
}
const auto edits = dialog->findChildren<ElaLineEdit*>();
if (!edits.isEmpty())
{
edits.first()->setText(title);
}
if (accept)
{
dialog->accept();
}
else
{
dialog->reject();
}
return;
}
});
QTimer::singleShot(2000, []() {
for (QWidget* widget : QApplication::topLevelWidgets())
{
if (auto* dialog = qobject_cast<BlockEditDialog*>(widget))
{
dialog->reject();
}
}
});
}
void TestMainWindow::createEditAndDeleteThroughUi()
{
QTemporaryDir databaseDir;
QVERIFY(databaseDir.isValid());
SqliteStore store(databaseDir.filePath(QStringLiteral("schedule.db")));
QString error;
QVERIFY2(store.open(&error), qPrintable(error));
ThemeManager theme(*m_settings);
theme.initialize();
ScheduleService service(store, QStringLiteral("ui-test-device"));
NotificationService notifications(service);
MainWindow window(service, notifications, theme, *m_settings);
window.show();
QVERIFY(QTest::qWaitForWindowExposed(&window));
QTest::qWait(60);
auto* grid = window.findChild<ScheduleGridView*>();
QVERIFY(grid);
grid->scrollToHour(8);
QTest::qWait(20);
const int scroll = grid->verticalScrollBar()->value();
const QPoint createPoint(300, 8 * 120 - scroll + 5);
fillDialogAndAccept(QStringLiteral("自动测试日程"), true);
QTest::mouseDClick(grid->viewport(), Qt::LeftButton, Qt::NoModifier, createPoint, 10);
QTest::qWait(80);
QVector<ScheduleItem> items = service.itemsForDay(QDate::currentDate());
QCOMPARE(items.size(), 1);
QCOMPARE(items.first().task.title, QStringLiteral("自动测试日程"));
const QString blockId = items.first().block.id;
const QPoint editPoint(300, 8 * 120 - scroll + 40);
fillDialogAndAccept(QStringLiteral("改名为复盘"), true);
QTest::mouseDClick(grid->viewport(), Qt::LeftButton, Qt::NoModifier, editPoint, 10);
QTest::qWait(80);
items = service.itemsForDay(QDate::currentDate());
QCOMPARE(items.size(), 1);
QCOMPARE(items.first().task.title, QStringLiteral("改名为复盘"));
grid->setFocus();
grid->setSelectedBlock(blockId);
QTest::keyClick(grid, Qt::Key_Delete);
QTest::qWait(80);
QVERIFY(service.itemsForDay(QDate::currentDate()).isEmpty());
}
QTEST_MAIN(TestMainWindow)
#include "test_mainwindow.moc"
+135
View File
@@ -0,0 +1,135 @@
#include <QJsonArray>
#include <QJsonObject>
#include <QTcpServer>
#include <QTcpSocket>
#include <QTimer>
#include <QtTest>
#include "ai/IAIProvider.h"
#include "ai/OpenAiProvider.h"
class FakeSseServer : public QTcpServer
{
public:
QByteArray response;
FakeSseServer()
{
connect(this, &QTcpServer::newConnection, this, [this]() {
while (hasPendingConnections())
{
QTcpSocket* socket = nextPendingConnection();
connect(socket, &QTcpSocket::readyRead, socket, [this, socket]() {
if (socket->property("responded").toBool())
{
return;
}
QByteArray buffer = socket->property("buffer").toByteArray();
buffer += socket->readAll();
socket->setProperty("buffer", buffer);
if (!buffer.contains("\r\n\r\n"))
{
return;
}
socket->setProperty("responded", true);
socket->write(response);
socket->flush();
QTimer::singleShot(30, socket, [socket]() { socket->disconnectFromHost(); });
});
}
});
}
};
class TestOpenAiProvider : public QObject
{
Q_OBJECT
private slots:
void streamsSseContent();
void reportsHttpError();
};
void TestOpenAiProvider::streamsSseContent()
{
FakeSseServer server;
QVERIFY(server.listen(QHostAddress::LocalHost, 0));
server.response =
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/event-stream\r\n"
"Cache-Control: no-cache\r\n"
"Connection: close\r\n"
"\r\n"
"data: {\"choices\":[{\"delta\":{\"content\":\"你好\"}}]}\n\n"
"data: {\"choices\":[{\"delta\":{\"content\":\",世界\"}}]}\n\n"
"data: [DONE]\n\n";
AiConfig config;
config.baseUrl = QStringLiteral("http://127.0.0.1:%1/v1").arg(server.serverPort());
config.apiKey = QStringLiteral("test-key");
config.model = QStringLiteral("test-model");
QJsonArray messages;
QJsonObject message;
message.insert(QStringLiteral("role"), QStringLiteral("user"));
message.insert(QStringLiteral("content"), QStringLiteral("hi"));
messages.append(message);
OpenAiProvider provider;
QString text;
QString error;
bool finished = false;
provider.streamCompletion(
config,
messages,
{
[&text](const QString& delta) { text += delta; },
[&error](const QString& message) { error = message; },
[&finished]() { finished = true; },
});
QTRY_VERIFY_WITH_TIMEOUT(finished, 5000);
QCOMPARE(error, QString());
QCOMPARE(text, QStringLiteral("你好,世界"));
}
void TestOpenAiProvider::reportsHttpError()
{
FakeSseServer server;
QVERIFY(server.listen(QHostAddress::LocalHost, 0));
server.response =
"HTTP/1.1 401 Unauthorized\r\n"
"Content-Type: application/json\r\n"
"Connection: close\r\n"
"\r\n"
"{\"error\":{\"message\":\"Invalid API key\"}}";
AiConfig config;
config.baseUrl = QStringLiteral("http://127.0.0.1:%1/v1").arg(server.serverPort());
config.apiKey = QStringLiteral("bad-key");
config.model = QStringLiteral("test-model");
QJsonArray messages;
QJsonObject message;
message.insert(QStringLiteral("role"), QStringLiteral("user"));
message.insert(QStringLiteral("content"), QStringLiteral("hi"));
messages.append(message);
OpenAiProvider provider;
QString error;
bool finished = false;
provider.streamCompletion(
config,
messages,
{
[](const QString&) {},
[&error](const QString& message) { error = message; },
[&finished]() { finished = true; },
});
QTRY_VERIFY_WITH_TIMEOUT(!error.isEmpty(), 5000);
QVERIFY(!finished);
QVERIFY(error.contains(QStringLiteral("Invalid API key")));
QVERIFY(error.contains(QStringLiteral("401")));
}
QTEST_GUILESS_MAIN(TestOpenAiProvider)
#include "test_openai_provider.moc"
+161
View File
@@ -0,0 +1,161 @@
#include <QtTest>
#include <chrono>
#include "core/SchedulerEngine.h"
using namespace std::chrono;
using namespace std::chrono_literals;
using scheduler::SysTime;
namespace
{
SysTime at(int day, int hour, int minute = 0)
{
return SysTime{sys_days{year{2026} / January / 5} + days{day} + hours{hour} + minutes{minute}};
}
std::vector<scheduler::TimeRange> workWindows(int days = 2)
{
std::vector<scheduler::TimeRange> windows;
for (int day = 0; day < days; ++day)
{
windows.push_back({at(day, 8), at(day, 22)});
}
return windows;
}
scheduler::TaskInput task(const std::string& id,
int minutes,
int priority = 1,
std::optional<SysTime> deadline = std::nullopt,
std::optional<SysTime> preferredStart = std::nullopt,
std::optional<SysTime> preferredEnd = std::nullopt)
{
scheduler::TaskInput input;
input.id = id;
input.title = id;
input.durationMinutes = minutes;
input.priority = priority;
input.deadline = deadline;
input.preferredStart = preferredStart;
input.preferredEnd = preferredEnd;
return input;
}
} // namespace
class TestScheduler : public QObject
{
Q_OBJECT
private slots:
void skipsBusyIntervals();
void honorsPreferredWindow();
void alignsToGranularity();
void respectsDeadline();
void prioritizesHigherPriorityFirst();
void fallsBackWhenPreferredIsFull();
void preferredWindowCanOverrideDefaultHours();
void reportsFailureWhenNoRoom();
};
void TestScheduler::skipsBusyIntervals()
{
const auto result = scheduler::schedule({task("a", 60)},
{{at(0, 8), at(0, 10)}},
workWindows(),
at(0, 8),
at(1, 22));
QCOMPARE(result.placements.size(), std::size_t(1));
QVERIFY(result.placements[0].start == at(0, 10));
QVERIFY(result.placements[0].end == at(0, 11));
QVERIFY(result.failures.empty());
}
void TestScheduler::honorsPreferredWindow()
{
const auto result = scheduler::schedule({task("a", 60, 1, std::nullopt, at(0, 14), at(0, 17))},
{},
workWindows(),
at(0, 8),
at(1, 22));
QCOMPARE(result.placements.size(), std::size_t(1));
QVERIFY(result.placements[0].start == at(0, 14));
QVERIFY(result.placements[0].end == at(0, 15));
}
void TestScheduler::alignsToGranularity()
{
const auto result = scheduler::schedule({task("a", 30)},
{},
workWindows(),
at(0, 8, 7),
at(0, 22));
QCOMPARE(result.placements.size(), std::size_t(1));
QVERIFY(result.placements[0].start == at(0, 8, 15));
QVERIFY(result.placements[0].end == at(0, 8, 45));
}
void TestScheduler::respectsDeadline()
{
const auto result = scheduler::schedule({task("a", 60, 1, at(0, 9))},
{{at(0, 8), at(0, 10)}},
workWindows(),
at(0, 8),
at(1, 22));
QVERIFY(result.placements.empty());
QCOMPARE(result.failures.size(), std::size_t(1));
QCOMPARE(QString::fromStdString(result.failures[0].taskId), QStringLiteral("a"));
}
void TestScheduler::prioritizesHigherPriorityFirst()
{
const auto result = scheduler::schedule({task("low", 60, 1), task("high", 60, 3)},
{},
workWindows(1),
at(0, 8),
at(0, 22));
QCOMPARE(result.placements.size(), std::size_t(2));
QCOMPARE(QString::fromStdString(result.placements[0].taskId), QStringLiteral("high"));
QVERIFY(result.placements[0].start == at(0, 8));
QCOMPARE(QString::fromStdString(result.placements[1].taskId), QStringLiteral("low"));
QVERIFY(result.placements[1].start == at(0, 9));
}
void TestScheduler::fallsBackWhenPreferredIsFull()
{
const auto result = scheduler::schedule({task("a", 60, 1, std::nullopt, at(0, 14), at(0, 16))},
{{at(0, 14), at(0, 16)}},
workWindows(),
at(0, 8),
at(1, 22));
QCOMPARE(result.placements.size(), std::size_t(1));
QVERIFY(result.placements[0].start == at(0, 8));
QVERIFY(result.placements[0].end == at(0, 9));
}
void TestScheduler::preferredWindowCanOverrideDefaultHours()
{
const auto result = scheduler::schedule({task("late", 60, 1, std::nullopt, at(0, 23), at(1, 1))},
{},
workWindows(),
at(0, 8),
at(1, 22));
QCOMPARE(result.placements.size(), std::size_t(1));
QVERIFY(result.placements[0].start == at(0, 23));
QVERIFY(result.placements[0].end == at(1, 0));
}
void TestScheduler::reportsFailureWhenNoRoom()
{
const auto result = scheduler::schedule({task("a", 120)},
{{at(0, 8), at(0, 22)}},
workWindows(1),
at(0, 8),
at(0, 22));
QVERIFY(result.placements.empty());
QCOMPARE(result.failures.size(), std::size_t(1));
}
QTEST_GUILESS_MAIN(TestScheduler)
#include "test_scheduler.moc"
+317
View File
@@ -0,0 +1,317 @@
#include <QJsonArray>
#include <QJsonObject>
#include <QSignalSpy>
#include <QTemporaryDir>
#include <QtTest>
#include <memory>
#include "core/DateTimeUtils.h"
#include "core/ProposedDiff.h"
#include "services/NotificationService.h"
#include "services/ScheduleService.h"
#include "storage/SqliteStore.h"
class TestServices : public QObject
{
Q_OBJECT
private slots:
void createAndQueryDay();
void queryMonthAndYearRange();
void updateAndMove();
void statusAndPostpone();
void deleteCascadesTask();
void overdueAndNotificationDedup();
void invalidRangeRejected();
void applyProposedCreatesOnlySelected();
};
namespace
{
struct Context
{
QTemporaryDir dir;
std::unique_ptr<SqliteStore> store;
std::unique_ptr<ScheduleService> service;
bool open()
{
if (!dir.isValid())
{
return false;
}
store = std::make_unique<SqliteStore>(dir.filePath(QStringLiteral("schedule.db")));
QString error;
if (!store->open(&error))
{
qWarning() << error;
return false;
}
service = std::make_unique<ScheduleService>(*store, QStringLiteral("test-device"));
return true;
}
};
} // namespace
void TestServices::createAndQueryDay()
{
Context context;
QVERIFY(context.open());
const QDateTime start(QDate::currentDate(), QTime(9, 0), Qt::LocalTime);
const QDateTime end = start.addSecs(90 * 60);
QString error;
QVERIFY2(context.service->createBlock(QStringLiteral("写周报"), start, end, &error), qPrintable(error));
const QVector<ScheduleItem> items = context.service->itemsForDay(QDate::currentDate());
QCOMPARE(items.size(), 1);
QCOMPARE(items.first().task.title, QStringLiteral("写周报"));
QCOMPARE(items.first().block.startAt, start);
QCOMPARE(items.first().block.endAt, end);
QCOMPARE(items.first().task.source, QStringLiteral("manual"));
}
void TestServices::queryMonthAndYearRange()
{
Context context;
QVERIFY(context.open());
const QDate today = QDate::currentDate();
const QDate first = QDate(today.year(), today.month(), 1);
const QDate last = QDate(today.year(), today.month(), first.daysInMonth());
QString error;
QVERIFY(context.service->createBlock(QStringLiteral("月初"),
QDateTime(first, QTime(9, 0), Qt::LocalTime),
QDateTime(first, QTime(10, 0), Qt::LocalTime),
&error));
QVERIFY(context.service->createBlock(QStringLiteral("月末"),
QDateTime(last, QTime(9, 0), Qt::LocalTime),
QDateTime(last, QTime(10, 0), Qt::LocalTime),
&error));
const QDate outside = QDate(today.year() + 1, 6, 15);
QVERIFY(context.service->createBlock(QStringLiteral("范围外"),
QDateTime(outside, QTime(9, 0), Qt::LocalTime),
QDateTime(outside, QTime(10, 0), Qt::LocalTime),
&error));
const QVector<ScheduleItem> monthItems = context.service->itemsForRange(first, last);
QCOMPARE(monthItems.size(), 2);
QCOMPARE(monthItems.first().task.title, QStringLiteral("月初"));
QCOMPARE(monthItems.last().task.title, QStringLiteral("月末"));
const QVector<ScheduleItem> yearItems = context.service->itemsForRange(
QDate(today.year(), 1, 1), QDate(today.year(), 12, 31));
QCOMPARE(yearItems.size(), 2);
QVERIFY(context.service->itemsForRange(last, first).isEmpty());
}
void TestServices::updateAndMove()
{
Context context;
QVERIFY(context.open());
const QDateTime start(QDate::currentDate(), QTime(9, 0), Qt::LocalTime);
QString error;
QVERIFY2(context.service->createBlock(QStringLiteral("旧标题"),
start,
start.addSecs(60 * 60),
&error),
qPrintable(error));
QVector<ScheduleItem> items = context.service->itemsForDay(QDate::currentDate());
QCOMPARE(items.size(), 1);
const QString blockId = items.first().block.id;
const QDateTime newStart = start.addSecs(2 * 60 * 60);
const QDateTime newEnd = newStart.addSecs(45 * 60);
QVERIFY2(context.service->updateBlock(blockId,
QStringLiteral("新标题"),
newStart,
newEnd,
&error),
qPrintable(error));
items = context.service->itemsForDay(QDate::currentDate());
QCOMPARE(items.size(), 1);
QCOMPARE(items.first().task.title, QStringLiteral("新标题"));
QCOMPARE(items.first().block.startAt, newStart);
QCOMPARE(items.first().block.endAt, newEnd);
QVERIFY(items.first().block.version >= 1);
QCOMPARE(items.first().block.deviceId, QStringLiteral("test-device"));
const QDateTime movedStart = newStart.addSecs(15 * 60);
const QDateTime movedEnd = newEnd.addSecs(15 * 60);
QVERIFY2(context.service->moveBlock(blockId, movedStart, movedEnd, &error), qPrintable(error));
items = context.service->itemsForDay(QDate::currentDate());
QCOMPARE(items.first().block.startAt, movedStart);
QCOMPARE(items.first().block.endAt, movedEnd);
}
void TestServices::statusAndPostpone()
{
Context context;
QVERIFY(context.open());
const QDateTime start(QDate::currentDate(), QTime(9, 0), Qt::LocalTime);
QString error;
QVERIFY(context.service->createBlock(QStringLiteral("任务"),
start,
start.addSecs(60 * 60),
&error));
QVector<ScheduleItem> items = context.service->itemsForDay(QDate::currentDate());
const QString blockId = items.first().block.id;
QVERIFY2(context.service->setBlockStatus(blockId, QStringLiteral("done"), &error), qPrintable(error));
items = context.service->itemsForDay(QDate::currentDate());
QCOMPARE(items.first().block.status, QStringLiteral("done"));
QVERIFY(items.first().block.doneAt.has_value());
QVERIFY2(context.service->postponeBlock(blockId, 15, &error), qPrintable(error));
items = context.service->itemsForDay(QDate::currentDate());
QCOMPARE(items.first().block.status, QStringLiteral("scheduled"));
QVERIFY(!items.first().block.doneAt.has_value());
QCOMPARE(items.first().block.startAt, start.addSecs(15 * 60));
QCOMPARE(items.first().block.endAt, start.addSecs(75 * 60));
QVERIFY(!context.service->setBlockStatus(blockId, QStringLiteral("unknown"), &error));
QVERIFY(!error.isEmpty());
}
void TestServices::deleteCascadesTask()
{
Context context;
QVERIFY(context.open());
const QDateTime start(QDate::currentDate(), QTime(9, 0), Qt::LocalTime);
QString error;
QVERIFY(context.service->createBlock(QStringLiteral("待删除"),
start,
start.addSecs(60 * 60),
&error));
QVector<ScheduleItem> items = context.service->itemsForDay(QDate::currentDate());
const QString blockId = items.first().block.id;
const QString taskId = items.first().task.id;
QVERIFY(context.store->taskById(taskId).has_value());
QVERIFY2(context.service->deleteBlock(blockId, &error), qPrintable(error));
QVERIFY(context.service->itemsForDay(QDate::currentDate()).isEmpty());
QVERIFY(!context.store->taskById(taskId).has_value());
}
void TestServices::overdueAndNotificationDedup()
{
Context context;
QVERIFY(context.open());
const QDateTime now = QDateTime::currentDateTime();
const QDateTime start = now.addSecs(-2 * 60 * 60);
const QDateTime end = now.addSecs(-60 * 60);
QString error;
QVERIFY(context.service->createBlock(QStringLiteral("已超时"), start, end, &error));
const QVector<ScheduleItem> overdue = context.service->overdueItems(now);
QCOMPARE(overdue.size(), 1);
const QString overdueId = overdue.first().block.id;
NotificationService notifications(*context.service);
QSignalSpy detectedSpy(&notifications, &NotificationService::overdueDetected);
QSignalSpy listSpy(&notifications, &NotificationService::overdueListChanged);
notifications.checkNow();
QCOMPARE(detectedSpy.count(), 1);
QCOMPARE(listSpy.count(), 1);
QCOMPARE(notifications.overdueItems().size(), 1);
notifications.checkNow();
QCOMPARE(detectedSpy.count(), 1);
QVERIFY(context.service->setBlockStatus(overdueId, QStringLiteral("done"), &error));
QCOMPARE(context.service->overdueItems(QDateTime::currentDateTime()).size(), 0);
QCOMPARE(notifications.overdueItems().size(), 0);
}
void TestServices::invalidRangeRejected()
{
Context context;
QVERIFY(context.open());
const QDateTime start(QDate::currentDate(), QTime(9, 0), Qt::LocalTime);
QString error;
QVERIFY(!context.service->createBlock(QStringLiteral("倒序"),
start,
start.addSecs(-60 * 60),
&error));
QVERIFY(!error.isEmpty());
error.clear();
QVERIFY(!context.service->createBlock(QStringLiteral("太短"),
start,
start.addSecs(60),
&error));
QVERIFY(!error.isEmpty());
QVERIFY(context.service->itemsForDay(QDate::currentDate()).isEmpty());
}
void TestServices::applyProposedCreatesOnlySelected()
{
Context context;
QVERIFY(context.open());
const QDate today = QDate::currentDate();
const QDateTime startA(today, QTime(9, 0), Qt::LocalTime);
const QDateTime endA = startA.addSecs(60 * 60);
const QDateTime startB(today, QTime(11, 0), Qt::LocalTime);
const QDateTime endB = startB.addSecs(30 * 60);
const auto makeCreate = [](const QString& tempId,
const QString& title,
const QDateTime& start,
const QDateTime& end) {
QJsonObject task;
task.insert(QStringLiteral("title"), title);
task.insert(QStringLiteral("description"), QStringLiteral("AI 生成"));
task.insert(QStringLiteral("priority"), 2);
task.insert(QStringLiteral("energy_req"), 1);
QJsonObject block;
block.insert(QStringLiteral("start_at"), DateTimeUtils::toDb(start));
block.insert(QStringLiteral("end_at"), DateTimeUtils::toDb(end));
block.insert(QStringLiteral("granularity"), 15);
QJsonObject create;
create.insert(QStringLiteral("temp_id"), tempId);
create.insert(QStringLiteral("task"), task);
create.insert(QStringLiteral("block"), block);
return create;
};
ProposedDiff diff;
diff.id = QStringLiteral("diff-2");
diff.createdAt = DateTimeUtils::toDb(QDateTime::currentDateTimeUtc());
diff.explanation = QStringLiteral("新增两个日程");
diff.state = QStringLiteral("pending");
diff.payload = QJsonObject{
{QStringLiteral("creates"),
QJsonArray{makeCreate(QStringLiteral("a"), QStringLiteral("AI 任务 A"), startA, endA),
makeCreate(QStringLiteral("b"), QStringLiteral("AI 任务 B"), startB, endB)}},
{QStringLiteral("updates"), QJsonArray{}},
{QStringLiteral("deletes"), QJsonArray{}}};
QString error;
QVERIFY2(context.service->applyProposedCreates(diff, {QStringLiteral("a")}, &error), qPrintable(error));
QVector<ScheduleItem> items = context.service->itemsForDay(today);
QCOMPARE(items.size(), 1);
QCOMPARE(items.first().task.title, QStringLiteral("AI 任务 A"));
QCOMPARE(items.first().task.source, QStringLiteral("ai_chat"));
QCOMPARE(items.first().block.startAt, startA);
QCOMPARE(items.first().block.endAt, endA);
QVERIFY2(context.service->applyProposedCreates(diff, {QStringLiteral("b")}, &error), qPrintable(error));
items = context.service->itemsForDay(today);
QCOMPARE(items.size(), 2);
QVERIFY(!context.service->applyProposedCreates(diff, {}, &error));
}
QTEST_GUILESS_MAIN(TestServices)
#include "test_services.moc"
+264
View File
@@ -0,0 +1,264 @@
#include <QJsonObject>
#include <QTemporaryDir>
#include <QtTest>
#include "core/DateTimeUtils.h"
#include "core/ProposedDiff.h"
#include "storage/SqliteStore.h"
class TestStorage : public QObject
{
Q_OBJECT
private slots:
void migrationCreatesSchema();
void taskAndBlockRoundTrip();
void blockRangeIncludesOverlap();
void proposedDiffRoundTrip();
void outboxCapturesLocalChanges();
void remoteApplySuppressesOutboxAndUsesLww();
};
void TestStorage::migrationCreatesSchema()
{
QTemporaryDir dir;
QVERIFY(dir.isValid());
SqliteStore store(dir.filePath(QStringLiteral("schedule.db")));
QString error;
QVERIFY2(store.open(&error), qPrintable(error));
QCOMPARE(store.schemaVersion(), 3);
store.close();
QVERIFY2(store.open(&error), qPrintable(error));
QCOMPARE(store.schemaVersion(), 3);
}
void TestStorage::taskAndBlockRoundTrip()
{
QTemporaryDir dir;
QVERIFY(dir.isValid());
SqliteStore store(dir.filePath(QStringLiteral("schedule.db")));
QString error;
QVERIFY2(store.open(&error), qPrintable(error));
const QDateTime now = QDateTime::currentDateTime();
Task task;
task.id = QStringLiteral("task-1");
task.title = QStringLiteral("写周报");
task.createdAt = now;
task.updatedAt = now;
task.deviceId = QStringLiteral("device-1");
QVERIFY2(store.insertTask(task), qPrintable(store.lastError()));
TimeBlock block;
block.id = QStringLiteral("block-1");
block.taskId = task.id;
block.startAt = QDateTime(QDate::currentDate(), QTime(9, 0), Qt::LocalTime);
block.endAt = block.startAt.addSecs(90 * 60);
block.createdAt = now;
block.updatedAt = now;
block.deviceId = QStringLiteral("device-1");
QVERIFY2(store.insertTimeBlock(block), qPrintable(store.lastError()));
const QVector<ScheduleItem> items = store.blocksInRange(
DateTimeUtils::localDayStartUtc(QDate::currentDate()),
DateTimeUtils::localDayEndUtc(QDate::currentDate()));
QCOMPARE(items.size(), 1);
QCOMPARE(items.first().task.title, QStringLiteral("写周报"));
QCOMPARE(items.first().block.startAt, block.startAt);
QCOMPARE(items.first().block.endAt, block.endAt);
QCOMPARE(items.first().block.granularity, 15);
QVERIFY(items.first().block.splittable);
QVERIFY(items.first().block.breakable);
const auto loadedTask = store.taskById(task.id);
QVERIFY(loadedTask.has_value());
QCOMPARE(loadedTask->title, task.title);
QVERIFY2(store.deleteTimeBlock(block.id), qPrintable(store.lastError()));
QVERIFY(store.blocksInRange(DateTimeUtils::localDayStartUtc(QDate::currentDate()),
DateTimeUtils::localDayEndUtc(QDate::currentDate()))
.isEmpty());
}
void TestStorage::blockRangeIncludesOverlap()
{
QTemporaryDir dir;
QVERIFY(dir.isValid());
SqliteStore store(dir.filePath(QStringLiteral("schedule.db")));
QString error;
QVERIFY2(store.open(&error), qPrintable(error));
const QDate today = QDate::currentDate();
const QDateTime now = QDateTime::currentDateTime();
Task task;
task.id = QStringLiteral("task-2");
task.title = QStringLiteral("跨午夜");
task.createdAt = now;
task.updatedAt = now;
task.deviceId = QStringLiteral("device-1");
QVERIFY(store.insertTask(task));
TimeBlock block;
block.id = QStringLiteral("block-2");
block.taskId = task.id;
block.startAt = QDateTime(today.addDays(-1), QTime(23, 30), Qt::LocalTime);
block.endAt = QDateTime(today, QTime(0, 30), Qt::LocalTime);
block.createdAt = now;
block.updatedAt = now;
block.deviceId = QStringLiteral("device-1");
QVERIFY(store.insertTimeBlock(block));
const QVector<ScheduleItem> items =
store.blocksInRange(DateTimeUtils::localDayStartUtc(today), DateTimeUtils::localDayEndUtc(today));
QCOMPARE(items.size(), 1);
QCOMPARE(items.first().block.id, block.id);
}
void TestStorage::proposedDiffRoundTrip()
{
QTemporaryDir dir;
QVERIFY(dir.isValid());
SqliteStore store(dir.filePath(QStringLiteral("schedule.db")));
QString error;
QVERIFY2(store.open(&error), qPrintable(error));
ProposedDiff diff;
diff.id = QStringLiteral("diff-1");
diff.createdAt = QStringLiteral("2026-10-26T00:00:00Z");
diff.explanation = QStringLiteral("新增一个日程");
diff.state = QStringLiteral("pending");
diff.payload = QJsonObject{{QStringLiteral("creates"), QJsonArray{}}};
QVERIFY2(store.insertProposedDiff(diff), qPrintable(store.lastError()));
const auto loaded = store.proposedDiffById(diff.id);
QVERIFY(loaded.has_value());
QCOMPARE(loaded->explanation, diff.explanation);
QCOMPARE(loaded->state, QStringLiteral("pending"));
QVERIFY(loaded->payload.contains(QStringLiteral("creates")));
QVERIFY2(store.updateProposedDiffState(diff.id, QStringLiteral("applied"), QStringLiteral("2026-10-26T01:00:00Z")),
qPrintable(store.lastError()));
const auto updated = store.proposedDiffById(diff.id);
QVERIFY(updated.has_value());
QCOMPARE(updated->state, QStringLiteral("applied"));
QCOMPARE(updated->resolvedAt, QStringLiteral("2026-10-26T01:00:00Z"));
}
void TestStorage::outboxCapturesLocalChanges()
{
QTemporaryDir dir;
QVERIFY(dir.isValid());
SqliteStore store(dir.filePath(QStringLiteral("schedule.db")));
QString error;
QVERIFY2(store.open(&error), qPrintable(error));
QCOMPARE(store.outboxCount(), 0);
const QDateTime now = QDateTime::currentDateTime();
Task task;
task.id = QStringLiteral("sync-task");
task.title = QStringLiteral("同步任务");
task.createdAt = now;
task.updatedAt = now;
task.deviceId = QStringLiteral("device-1");
QVERIFY(store.insertTask(task));
TimeBlock block;
block.id = QStringLiteral("sync-block");
block.taskId = task.id;
block.startAt = QDateTime(QDate::currentDate(), QTime(10, 0), Qt::LocalTime);
block.endAt = block.startAt.addSecs(3600);
block.createdAt = now;
block.updatedAt = now;
block.deviceId = QStringLiteral("device-1");
QVERIFY(store.insertTimeBlock(block));
QCOMPARE(store.outboxCount(), 2);
const QVector<SyncOutboxItem> items = store.outboxBatch(10);
QCOMPARE(items.size(), 2);
QCOMPARE(items.first().entityType, QStringLiteral("task"));
QCOMPARE(items.first().op, QStringLiteral("upsert"));
QCOMPARE(items.first().payload.value(QStringLiteral("title")).toString(), QStringLiteral("同步任务"));
task.title = QStringLiteral("同步任务 v2");
task.updatedAt = now.addSecs(1);
task.version = 1;
QVERIFY(store.updateTask(task));
QCOMPARE(store.outboxCount(), 3);
QVERIFY(store.deleteTimeBlock(block.id));
QVERIFY(store.deleteTask(task.id));
QCOMPARE(store.outboxCount(), 5);
const qint64 maxId = store.outboxBatch(100).last().id;
QVERIFY(store.clearOutboxThrough(maxId));
QCOMPARE(store.outboxCount(), 0);
}
void TestStorage::remoteApplySuppressesOutboxAndUsesLww()
{
QTemporaryDir dir;
QVERIFY(dir.isValid());
SqliteStore store(dir.filePath(QStringLiteral("schedule.db")));
QString error;
QVERIFY2(store.open(&error), qPrintable(error));
QVERIFY(store.setSyncCursor(QStringLiteral("device-1"), 42));
QCOMPARE(store.syncCursor(QStringLiteral("device-1")), 42);
QVERIFY(store.beginTransaction());
QVERIFY(store.setRemoteApplySuppressed(true));
RemoteChange taskChange;
taskChange.seq = 1;
taskChange.deviceId = QStringLiteral("remote-device");
taskChange.entityType = QStringLiteral("task");
taskChange.entityId = QStringLiteral("remote-task");
taskChange.op = QStringLiteral("upsert");
taskChange.version = 1;
taskChange.updatedAt = QStringLiteral("2026-10-26T10:00:00Z");
taskChange.payload = QJsonObject{
{QStringLiteral("id"), QStringLiteral("remote-task")},
{QStringLiteral("title"), QStringLiteral("远程任务")},
{QStringLiteral("status"), QStringLiteral("active")},
{QStringLiteral("priority"), 1},
{QStringLiteral("created_at"), QStringLiteral("2026-10-26T09:00:00Z")},
{QStringLiteral("updated_at"), QStringLiteral("2026-10-26T10:00:00Z")},
};
QVERIFY(store.applyRemoteChange(taskChange));
QVERIFY(store.setRemoteApplySuppressed(false));
QVERIFY(store.commit());
QCOMPARE(store.outboxCount(), 0);
QVERIFY(store.taskById(QStringLiteral("remote-task")).has_value());
// 较旧的远程版本应被 LWW 忽略。
taskChange.updatedAt = QStringLiteral("2026-10-26T09:30:00Z");
taskChange.payload.insert(QStringLiteral("title"), QStringLiteral("旧标题"));
QVERIFY(store.beginTransaction());
QVERIFY(store.setRemoteApplySuppressed(true));
QVERIFY(store.applyRemoteChange(taskChange));
QVERIFY(store.setRemoteApplySuppressed(false));
QVERIFY(store.commit());
QCOMPARE(store.taskById(QStringLiteral("remote-task"))->title, QStringLiteral("远程任务"));
// 毫秒级时间戳必须可比较,且能覆盖同秒的无毫秒旧时间戳。
taskChange.updatedAt = QStringLiteral("2026-10-26T10:00:00.500Z");
taskChange.payload.insert(QStringLiteral("title"), QStringLiteral("毫秒版本"));
QVERIFY(store.beginTransaction());
QVERIFY(store.setRemoteApplySuppressed(true));
QVERIFY(store.applyRemoteChange(taskChange));
QVERIFY(store.setRemoteApplySuppressed(false));
QVERIFY(store.commit());
QCOMPARE(store.taskById(QStringLiteral("remote-task"))->title, QStringLiteral("毫秒版本"));
// 同时间戳删除优先,避免墓碑被等时间戳的 upsert 覆盖。
taskChange.op = QStringLiteral("delete");
taskChange.updatedAt = QStringLiteral("2026-10-26T10:00:00.500Z");
QVERIFY(store.beginTransaction());
QVERIFY(store.setRemoteApplySuppressed(true));
QVERIFY(store.applyRemoteChange(taskChange));
QVERIFY(store.setRemoteApplySuppressed(false));
QVERIFY(store.commit());
QVERIFY(!store.taskById(QStringLiteral("remote-task")).has_value());
QCOMPARE(store.outboxCount(), 0);
}
QTEST_GUILESS_MAIN(TestStorage)
#include "test_storage.moc"
+186
View File
@@ -0,0 +1,186 @@
#include <QCoreApplication>
#include <QElapsedTimer>
#include <QFileInfo>
#include <QProcess>
#include <QTcpServer>
#include <QTcpSocket>
#include <QTemporaryDir>
#include <QThread>
#include <QtTest>
#include <memory>
#include "services/ScheduleService.h"
#include "storage/SqliteStore.h"
#include "sync/SyncService.h"
#include "utils/AppSettings.h"
namespace
{
int freePort()
{
QTcpServer probe;
if (!probe.listen(QHostAddress::LocalHost, 0))
{
return 0;
}
const int port = probe.serverPort();
probe.close();
return port;
}
bool waitForServer(int port, int timeoutMs)
{
QElapsedTimer timer;
timer.start();
while (timer.elapsed() < timeoutMs)
{
QTcpSocket socket;
socket.connectToHost(QHostAddress::LocalHost, static_cast<quint16>(port));
if (socket.waitForConnected(150))
{
return true;
}
QCoreApplication::processEvents();
QThread::msleep(50);
}
return false;
}
} // namespace
class TestSyncIntegration : public QObject
{
Q_OBJECT
private slots:
void twoClientsConverge();
};
void TestSyncIntegration::twoClientsConverge()
{
const QString serverBinary = qEnvironmentVariable("SCHEDULE_SYNC_SERVER_BIN");
if (serverBinary.isEmpty() || !QFileInfo::exists(serverBinary))
{
QSKIP("sync server binary is not available");
}
const int port = freePort();
QVERIFY(port > 0);
QTemporaryDir serverDir;
QVERIFY(serverDir.isValid());
QProcess serverProcess;
QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
env.insert(QStringLiteral("SYNC_LISTEN_ADDR"), QStringLiteral("127.0.0.1:%1").arg(port));
env.insert(QStringLiteral("SYNC_DB_PATH"), serverDir.filePath(QStringLiteral("sync.db")));
env.insert(QStringLiteral("SYNC_TOKEN_PEPPER"), QStringLiteral("integration-pepper"));
serverProcess.setProcessEnvironment(env);
serverProcess.setProcessChannelMode(QProcess::MergedChannels);
serverProcess.setStandardOutputFile(serverDir.filePath(QStringLiteral("server.log")));
serverProcess.start(serverBinary, {});
QVERIFY2(serverProcess.waitForStarted(5000), qPrintable(serverProcess.errorString()));
QVERIFY(waitForServer(port, 10000));
QTemporaryDir clientADir;
QTemporaryDir clientBDir;
QVERIFY(clientADir.isValid());
QVERIFY(clientBDir.isValid());
AppSettings settingsA(clientADir.filePath(QStringLiteral("config.toml")));
AppSettings settingsB(clientBDir.filePath(QStringLiteral("config.toml")));
SyncConfig syncConfig;
syncConfig.enabled = true;
syncConfig.serverUrl = QStringLiteral("http://127.0.0.1:%1").arg(port);
settingsA.setSyncConfig(syncConfig);
settingsB.setSyncConfig(syncConfig);
SqliteStore storeA(clientADir.filePath(QStringLiteral("schedule.db")));
SqliteStore storeB(clientBDir.filePath(QStringLiteral("schedule.db")));
QString error;
QVERIFY2(storeA.open(&error), qPrintable(error));
QVERIFY2(storeB.open(&error), qPrintable(error));
ScheduleService serviceA(storeA, settingsA.deviceId());
ScheduleService serviceB(storeB, settingsB.deviceId());
SyncService syncA(serviceA, storeA, settingsA);
SyncService syncB(serviceB, storeB, settingsB);
syncA.start();
syncB.start();
QTRY_VERIFY_WITH_TIMEOUT(syncA.statusText().contains(QStringLiteral("同步")) ||
syncA.statusText().contains(QStringLiteral("已连接")), 12000);
QTRY_VERIFY_WITH_TIMEOUT(syncB.statusText().contains(QStringLiteral("同步")) ||
syncB.statusText().contains(QStringLiteral("已连接")), 12000);
const QDate tomorrow = QDate::currentDate().addDays(1);
const QDateTime start(tomorrow, QTime(9, 0), Qt::LocalTime);
const QDateTime end(tomorrow, QTime(10, 0), Qt::LocalTime);
QVERIFY2(serviceA.createBlock(QStringLiteral("跨设备任务"), start, end, &error), qPrintable(error));
QTRY_VERIFY_WITH_TIMEOUT(serviceB.itemsForDay(tomorrow).size() == 1, 20000);
QCOMPARE(serviceB.itemsForDay(tomorrow).first().task.title, QStringLiteral("跨设备任务"));
QVERIFY2(serviceA.updateBlock(serviceA.itemsForDay(tomorrow).first().block.id,
QStringLiteral("跨设备任务 v2"),
start.addSecs(3600),
end.addSecs(3600),
&error),
qPrintable(error));
QTRY_VERIFY_WITH_TIMEOUT(!serviceB.itemsForDay(tomorrow).isEmpty() &&
serviceB.itemsForDay(tomorrow).first().task.title ==
QStringLiteral("跨设备任务 v2"),
20000);
QVERIFY2(serviceB.createBlock(QStringLiteral("反向任务"),
start.addSecs(2 * 3600),
end.addSecs(2 * 3600),
&error),
qPrintable(error));
QTRY_VERIFY_WITH_TIMEOUT(serviceA.itemsForDay(tomorrow).size() == 2, 20000);
bool sawReverse = false;
for (const ScheduleItem& item : serviceA.itemsForDay(tomorrow))
{
if (item.task.title == QStringLiteral("反向任务"))
{
sawReverse = true;
}
}
QVERIFY(sawReverse);
for (const ScheduleItem& item : serviceA.itemsForDay(tomorrow))
{
if (item.task.title == QStringLiteral("跨设备任务 v2"))
{
QVERIFY2(serviceA.deleteBlock(item.block.id, &error), qPrintable(error));
break;
}
}
QTRY_VERIFY_WITH_TIMEOUT(serviceB.itemsForDay(tomorrow).size() == 1, 20000);
QCOMPARE(serviceB.itemsForDay(tomorrow).first().task.title, QStringLiteral("反向任务"));
serverProcess.terminate();
QVERIFY(serverProcess.waitForFinished(5000));
QVERIFY2(serviceA.createBlock(QStringLiteral("离线任务"),
start.addSecs(4 * 3600),
end.addSecs(4 * 3600),
&error),
qPrintable(error));
QTest::qWait(1000);
serverProcess.start(serverBinary, {});
QVERIFY2(serverProcess.waitForStarted(5000), qPrintable(serverProcess.errorString()));
QVERIFY(waitForServer(port, 10000));
QTRY_VERIFY_WITH_TIMEOUT(serviceB.itemsForDay(tomorrow).size() == 2, 30000);
bool sawOffline = false;
for (const ScheduleItem& item : serviceB.itemsForDay(tomorrow))
{
if (item.task.title == QStringLiteral("离线任务"))
{
sawOffline = true;
}
}
QVERIFY(sawOffline);
syncA.stop();
syncB.stop();
serverProcess.terminate();
serverProcess.waitForFinished(5000);
}
QTEST_GUILESS_MAIN(TestSyncIntegration)
#include "test_sync_integration.moc"
+5
View File
@@ -0,0 +1,5 @@
add_executable(ai_regression ai_regression.cpp)
target_link_libraries(ai_regression PRIVATE schedule_ai Qt6::Core)
set_target_properties(ai_regression PROPERTIES
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
)
+462
View File
@@ -0,0 +1,462 @@
// 手动运行的本地模型回归工具(不属于 CTest)。
// 使用当前 AppSettings 中的 AI 配置,针对临时数据库运行真实模型。
//
// 用法:
// ./ai_regression --limit 5
// ./ai_regression --timeout 180 --out docs/validation/ai-regression-real.md
#include <QCoreApplication>
#include <QElapsedTimer>
#include <QEventLoop>
#include <QFile>
#include <QTextStream>
#include <QTemporaryDir>
#include <QTimer>
#include <cstdio>
#include "ai/AIService.h"
#include "core/DateTimeUtils.h"
#include "services/ScheduleService.h"
#include "storage/SqliteStore.h"
#include "utils/AppSettings.h"
namespace
{
struct Case
{
int id = 0;
QString prompt;
QString expect; // create/update/delete/chat/ripple/split
QString titleNeedle;
int seed = 0; // 0 base tasks, 1 busy blocks for split
};
struct Outcome
{
bool ok = false;
QString detail;
bool timeout = false;
bool failed = false;
int creates = 0;
int updates = 0;
int deletes = 0;
int splitCreates = 0;
bool proposal = false;
QString reply;
QString error;
};
QVector<Case> cases()
{
return {
{1, QStringLiteral("明天下午写周报 2 小时"), QStringLiteral("create"), QStringLiteral("周报"), 0},
{2, QStringLiteral("今天 23:00 整理资料 30 分钟"), QStringLiteral("create"), QStringLiteral("资料"), 0},
{3, QStringLiteral("明天上午 10 点开 1 小时团队会议"), QStringLiteral("create"), QStringLiteral("会议"), 0},
{4, QStringLiteral("后天下午 3 点做一次 45 分钟复盘"), QStringLiteral("create"), QStringLiteral("复盘"), 0},
{5, QStringLiteral("这周找一个小时阅读"), QStringLiteral("create"), QStringLiteral("阅读"), 0},
{6, QStringLiteral("明天早上 8 点开始跑步 30 分钟"), QStringLiteral("create"), QStringLiteral("跑步"), 0},
{7, QStringLiteral("周五之前完成季度总结,预计 3 小时"), QStringLiteral("create"), QStringLiteral("总结"), 0},
{8, QStringLiteral("明天中午 12 点吃饭 1 小时"), QStringLiteral("create"), QStringLiteral("吃饭"), 0},
{9, QStringLiteral("今晚 9 点做 20 分钟拉伸"), QStringLiteral("create"), QStringLiteral("拉伸"), 0},
{10, QStringLiteral("明天下午 4 点准备 1.5 小时的产品演示"), QStringLiteral("create"), QStringLiteral("演示"), 0},
{11, QStringLiteral("明天上午安排两个任务:写周报 1 小时,整理邮件 30 分钟"), QStringLiteral("create"), QStringLiteral("周报"), 0},
{12, QStringLiteral("明天下午做三件事:写文档 2 小时、开评审会 1 小时、回复消息 30 分钟"), QStringLiteral("create"), QStringLiteral("文档"), 0},
{13, QStringLiteral("这周完成代码审查和单元测试,各 2 小时"), QStringLiteral("create"), QStringLiteral("代码"), 0},
{14, QStringLiteral("明天上午 9 点和 10 点各安排一个 30 分钟会议"), QStringLiteral("create"), QStringLiteral("会议"), 0},
{15, QStringLiteral("后天安排健身 1 小时和阅读 1 小时"), QStringLiteral("create"), QStringLiteral("健身"), 0},
{16, QStringLiteral("把写周报改到明天下午 2 点"), QStringLiteral("update"), QStringLiteral("周报"), 1},
{17, QStringLiteral("把团队同步延后 1 小时"), QStringLiteral("update"), QStringLiteral("团队"), 1},
{18, QStringLiteral("把健身改到明天上午 10 点"), QStringLiteral("update"), QStringLiteral("健身"), 1},
{19, QStringLiteral("写周报改成 90 分钟,时间不变"), QStringLiteral("update"), QStringLiteral("周报"), 1},
{20, QStringLiteral("把团队同步改名为项目同步"), QStringLiteral("update"), QStringLiteral("团队"), 1},
{21, QStringLiteral("把写周报改到后天上午 9 点,时长 2 小时"), QStringLiteral("update"), QStringLiteral("周报"), 1},
{22, QStringLiteral("把健身提前到明天 8 点"), QStringLiteral("update"), QStringLiteral("健身"), 1},
{23, QStringLiteral("把写周报和团队同步都挪到下午"), QStringLiteral("update"), QStringLiteral("周报"), 1},
{24, QStringLiteral("把团队同步的标题改成每日站会"), QStringLiteral("update"), QStringLiteral("团队"), 1},
{25, QStringLiteral("把健身的时长改成 45 分钟"), QStringLiteral("update"), QStringLiteral("健身"), 1},
{26, QStringLiteral("删掉团队同步"), QStringLiteral("delete"), QStringLiteral("团队"), 1},
{27, QStringLiteral("删除明天的健身"), QStringLiteral("delete"), QStringLiteral("健身"), 1},
{28, QStringLiteral("取消写周报"), QStringLiteral("delete"), QStringLiteral("周报"), 1},
{29, QStringLiteral("把团队同步删掉,后天不用开会"), QStringLiteral("delete"), QStringLiteral("团队"), 1},
{30, QStringLiteral("删除明天所有会议"), QStringLiteral("delete"), QString(), 1},
{31, QStringLiteral("明天有什么安排?"), QStringLiteral("chat"), QString(), 1},
{32, QStringLiteral("我这周还有多少空闲时间?"), QStringLiteral("chat"), QString(), 1},
{33, QStringLiteral("帮我看看明天下午有没有空"), QStringLiteral("chat"), QString(), 1},
{34, QStringLiteral("现在几点?今天还有什么日程?"), QStringLiteral("chat"), QString(), 1},
{35, QStringLiteral("写周报需要多久?"), QStringLiteral("chat"), QString(), 1},
{36, QStringLiteral("明天下午 3 点插入一个 1 小时的电话会议"), QStringLiteral("ripple"), QStringLiteral("电话"), 1},
{37, QStringLiteral("明天上午 9 点插入 30 分钟站会"), QStringLiteral("ripple"), QStringLiteral("站会"), 1},
{38, QStringLiteral("明天下午 3 点安排写文档 2 小时"), QStringLiteral("ripple"), QStringLiteral("文档"), 1},
{39, QStringLiteral("明天上午 11 点插入一个客户沟通 1 小时"), QStringLiteral("ripple"), QStringLiteral("沟通"), 1},
{40, QStringLiteral("后天下午 3 点插入一个 1 小时复盘"), QStringLiteral("create"), QStringLiteral("复盘"), 1},
{41, QStringLiteral("明天之前找时间做两小时长任务,可以拆开"), QStringLiteral("create"), QStringLiteral("长任务"), 2},
{42, QStringLiteral("明天之前找时间做 3 小时深度工作,可以拆开"), QStringLiteral("create"), QStringLiteral("深度"), 2},
{43, QStringLiteral("明天完成 2 小时报告和 2 小时代码,可以拆分"), QStringLiteral("create"), QStringLiteral("报告"), 2},
{44, QStringLiteral("明天之前做一次 4 小时的项目冲刺,允许拆开"), QStringLiteral("create"), QStringLiteral("冲刺"), 2},
{45, QStringLiteral("明天安排 3 小时的整理工作,可以分两次"), QStringLiteral("create"), QStringLiteral("整理"), 2},
{46, QStringLiteral("昨天下午写周报 1 小时"), QStringLiteral("create"), QStringLiteral("周报"), 0},
{47, QStringLiteral("帮我安排一下"), QStringLiteral("chat"), QString(), 0},
{48, QStringLiteral("明天开会"), QStringLiteral("create"), QStringLiteral("开会"), 0},
{49, QStringLiteral("下周一上午 10 点准备周报,时长 1 小时"), QStringLiteral("create"), QStringLiteral("周报"), 0},
{50, QStringLiteral("这周末安排一次 2 小时的复盘"), QStringLiteral("create"), QStringLiteral("复盘"), 0},
};
}
bool seedDatabase(ScheduleService& service, int mode, QString* error)
{
const QDate today = QDate::currentDate();
const QDate tomorrow = today.addDays(1);
if (mode == 0)
{
return true;
}
if (mode == 2)
{
for (const QDate& day : {today, tomorrow})
{
if (!service.createBlock(QStringLiteral("占用一"),
QDateTime(day, QTime(8, 0), Qt::LocalTime),
QDateTime(day, QTime(12, 0), Qt::LocalTime),
error) ||
!service.createBlock(QStringLiteral("占用二"),
QDateTime(day, QTime(13, 0), Qt::LocalTime),
QDateTime(day, QTime(17, 0), Qt::LocalTime),
error) ||
!service.createBlock(QStringLiteral("占用三"),
QDateTime(day, QTime(18, 0), Qt::LocalTime),
QDateTime(day, QTime(22, 0), Qt::LocalTime),
error))
{
return false;
}
}
return true;
}
return service.createBlock(QStringLiteral("写周报"),
QDateTime(tomorrow, QTime(9, 0), Qt::LocalTime),
QDateTime(tomorrow, QTime(10, 0), Qt::LocalTime),
error) &&
service.createBlock(QStringLiteral("团队同步"),
QDateTime(tomorrow, QTime(11, 0), Qt::LocalTime),
QDateTime(tomorrow, QTime(12, 0), Qt::LocalTime),
error) &&
service.createBlock(QStringLiteral("健身"),
QDateTime(tomorrow, QTime(15, 0), Qt::LocalTime),
QDateTime(tomorrow, QTime(16, 0), Qt::LocalTime),
error) &&
service.createBlock(QStringLiteral("项目会议"),
QDateTime(tomorrow, QTime(13, 0), Qt::LocalTime),
QDateTime(tomorrow, QTime(14, 0), Qt::LocalTime),
error);
}
bool containsTitle(const ScheduleProposal& proposal, const QString& needle, bool* split)
{
for (const ProposedScheduleEntry& entry : proposal.entries)
{
if (entry.operation == ProposedOperation::Create && entry.segments.size() > 1)
{
*split = true;
}
const QString haystack = entry.title + QLatin1Char(' ') + entry.oldTitle;
if (needle.isEmpty() || haystack.contains(needle, Qt::CaseInsensitive))
{
return true;
}
}
return false;
}
Outcome evaluate(const Case& testCase, const ScheduleProposal& proposal, bool hasProposal)
{
Outcome outcome;
outcome.proposal = hasProposal;
if (testCase.expect == QStringLiteral("chat"))
{
outcome.ok = !hasProposal;
outcome.detail = hasProposal ? QStringLiteral("unexpected proposal") : QString();
return outcome;
}
if (!hasProposal)
{
outcome.detail = QStringLiteral("no proposal");
return outcome;
}
bool split = false;
bool titleOk = containsTitle(proposal, testCase.titleNeedle, &split);
for (const ProposedScheduleEntry& entry : proposal.entries)
{
if (entry.operation == ProposedOperation::Create)
{
++outcome.creates;
if (entry.segments.size() > 1)
{
++outcome.splitCreates;
}
}
else if (entry.operation == ProposedOperation::Update)
{
++outcome.updates;
}
else if (entry.operation == ProposedOperation::Delete)
{
++outcome.deletes;
}
}
if (testCase.expect == QStringLiteral("create"))
{
outcome.ok = outcome.creates > 0 && titleOk;
}
else if (testCase.expect == QStringLiteral("update"))
{
outcome.ok = outcome.updates > 0 && titleOk;
}
else if (testCase.expect == QStringLiteral("delete"))
{
outcome.ok = outcome.deletes > 0 && titleOk;
}
else if (testCase.expect == QStringLiteral("ripple"))
{
outcome.ok = outcome.creates > 0 && outcome.updates > 0 && titleOk;
}
else if (testCase.expect == QStringLiteral("split"))
{
// 模型可以设置 splittable 让引擎拆分,也可以自行拆成同一任务的多条 create。
outcome.ok = outcome.creates > 0 && titleOk &&
(outcome.splitCreates > 0 || outcome.creates >= 2);
}
if (!outcome.ok)
{
outcome.detail = titleOk ? QStringLiteral("operation mismatch") : QStringLiteral("title mismatch");
}
return outcome;
}
QString opsSummary(const Outcome& outcome)
{
return QStringLiteral("C%1 U%2 D%3 S%4")
.arg(outcome.creates)
.arg(outcome.updates)
.arg(outcome.deletes)
.arg(outcome.splitCreates);
}
} // namespace
int main(int argc, char* argv[])
{
QCoreApplication app(argc, argv);
QCoreApplication::setOrganizationName(QStringLiteral("Misaki"));
QCoreApplication::setApplicationName(QStringLiteral("Schedule"));
int limit = -1;
int startIndex = 0;
int timeoutSeconds = 180;
QString outPath;
for (int i = 1; i < argc; ++i)
{
const QString arg = QString::fromLocal8Bit(argv[i]);
if (arg == QStringLiteral("--limit") && i + 1 < argc)
{
limit = QString::fromLocal8Bit(argv[++i]).toInt();
}
else if (arg == QStringLiteral("--start") && i + 1 < argc)
{
startIndex = std::max(0, QString::fromLocal8Bit(argv[++i]).toInt() - 1);
}
else if (arg == QStringLiteral("--timeout") && i + 1 < argc)
{
timeoutSeconds = QString::fromLocal8Bit(argv[++i]).toInt();
}
else if (arg == QStringLiteral("--out") && i + 1 < argc)
{
outPath = QString::fromLocal8Bit(argv[++i]);
}
}
AppSettings settings;
const AiConfig config = settings.aiConfig();
std::printf("AI regression: base_url=%s model=%s\n",
qPrintable(config.baseUrl),
qPrintable(config.model));
std::printf("seed=base (update/delete/ripple) or busy (split)\n\n");
QVector<Case> allCases = cases();
if (startIndex >= allCases.size())
{
std::fprintf(stderr, "start index out of range\n");
return 1;
}
if (startIndex > 0 || (limit > 0 && limit < allCases.size()))
{
const int count = limit > 0 ? limit : allCases.size() - startIndex;
allCases = allCases.mid(startIndex, count);
}
QFile report(outPath);
QTextStream reportStream;
if (!outPath.isEmpty())
{
if (!report.open(QIODevice::WriteOnly | QIODevice::Text))
{
std::fprintf(stderr, "Cannot open report file: %s\n", qPrintable(outPath));
return 1;
}
reportStream.setDevice(&report);
reportStream << "# Real local model regression\n\n";
reportStream << "- base_url: `" << config.baseUrl << "`\n";
reportStream << "- model: `" << config.model << "`\n";
reportStream << "- timeout: " << timeoutSeconds << "s/case\n\n";
reportStream << "| # | result | ops | seconds | prompt | detail |\n";
reportStream << "|---|---|---|---|---|---|\n";
}
int passed = 0;
int failed = 0;
int timedOut = 0;
int errors = 0;
QVector<double> elapsedSeconds;
for (int index = 0; index < allCases.size(); ++index)
{
const Case& testCase = allCases.at(index);
QTemporaryDir dir;
if (!dir.isValid())
{
std::fprintf(stderr, "Cannot create temp dir\n");
return 1;
}
SqliteStore store(dir.filePath(QStringLiteral("schedule.db")));
QString error;
if (!store.open(&error))
{
std::fprintf(stderr, "Cannot open store: %s\n", qPrintable(error));
return 1;
}
ScheduleService service(store, QStringLiteral("regression-device"));
if (!seedDatabase(service, testCase.seed, &error))
{
std::fprintf(stderr, "Cannot seed case %d: %s\n", testCase.id, qPrintable(error));
return 1;
}
AIService ai(service, store, settings);
QEventLoop loop;
QTimer timeoutTimer;
timeoutTimer.setSingleShot(true);
Outcome outcome;
bool done = false;
bool hasProposal = false;
ScheduleProposal proposal;
QObject::connect(&ai, &AIService::streamDelta, [&outcome](const QString& delta) {
outcome.reply += delta;
});
QObject::connect(&ai, &AIService::proposalReady, [&](const ScheduleProposal& value) {
hasProposal = true;
proposal = value;
});
QObject::connect(&ai, &AIService::requestFinished, [&]() {
done = true;
loop.quit();
});
QObject::connect(&ai, &AIService::requestFailed, [&](const QString& message) {
outcome.failed = true;
outcome.error = message;
done = true;
loop.quit();
});
QObject::connect(&timeoutTimer, &QTimer::timeout, [&]() {
outcome.timeout = true;
done = true;
loop.quit();
});
QElapsedTimer timer;
timer.start();
timeoutTimer.start(timeoutSeconds * 1000);
ai.request(testCase.prompt);
if (!done)
{
loop.exec();
}
const double elapsed = timer.elapsed() / 1000.0;
elapsedSeconds.append(elapsed);
timeoutTimer.stop();
if (outcome.timeout)
{
++timedOut;
outcome.detail = QStringLiteral("timeout");
}
else if (outcome.failed)
{
++errors;
outcome.detail = outcome.error;
}
else
{
outcome = [&]() {
Outcome evaluated = evaluate(testCase, proposal, hasProposal);
evaluated.reply = outcome.reply;
evaluated.error = outcome.error;
return evaluated;
}();
}
if (outcome.ok)
{
++passed;
}
else
{
++failed;
}
const QString result = outcome.ok ? QStringLiteral("PASS")
: (outcome.timeout ? QStringLiteral("TIMEOUT")
: (outcome.failed ? QStringLiteral("ERROR")
: QStringLiteral("FAIL")));
std::printf("[%02d] %-7s %5.1fs %s %s%s%s\n",
testCase.id,
qPrintable(result),
elapsed,
qPrintable(opsSummary(outcome)),
qPrintable(testCase.prompt),
outcome.detail.isEmpty() ? "" : " | ",
outcome.detail.isEmpty() ? "" : qPrintable(outcome.detail));
std::fflush(stdout);
if (reportStream.device())
{
reportStream << "| " << testCase.id << " | " << result << " | " << opsSummary(outcome)
<< " | " << QString::number(elapsed, 'f', 1) << " | "
<< testCase.prompt << " | " << outcome.detail << " |\n";
reportStream.flush();
}
}
double total = 0;
for (double value : elapsedSeconds)
{
total += value;
}
const double avg = elapsedSeconds.isEmpty() ? 0 : total / elapsedSeconds.size();
std::printf("\nSummary: passed=%d failed=%d timeout=%d error=%d total=%lld avg=%.2fs\n",
passed,
failed,
timedOut,
errors,
static_cast<long long>(allCases.size()),
avg);
if (reportStream.device())
{
reportStream << "\n## Summary\n\n";
reportStream << "- passed: " << passed << "\n";
reportStream << "- failed: " << failed << "\n";
reportStream << "- timeout: " << timedOut << "\n";
reportStream << "- error: " << errors << "\n";
reportStream << "- average latency: " << QString::number(avg, 'f', 2) << "s\n";
report.flush();
}
return passed == allCases.size() ? 0 : 2;
}
+137
View File
@@ -0,0 +1,137 @@
# AI 日程软件 — 实施计划
> 依据《AI日程软件_项目交接文档 v1.0》与《C/C++ 项目开发规范文档 v1.0》制定。
> 本文件随开发进展更新;每个阶段结束时在 `docs/validation/` 留存验证记录。
> 阶段 0 + 1 已验证:[`validation/phase-0-1.md`](validation/phase-0-1.md)。
> 阶段 1.5(紧凑窗口 / 多视图 / 云母设置)已验证:[`validation/phase-1-5.md`](validation/phase-1-5.md)。
> 阶段 1.6(TOML 配置 / AI 服务配置)已验证:[`validation/phase-1-6.md`](validation/phase-1-6.md)。
> 阶段 2(AI 日程闭环)已验证:[`validation/phase-2.md`](validation/phase-2.md)。
> 阶段 2.1(更新 / 删除 / 涟漪 / 拆分)已验证:[`validation/phase-2-1.md`](validation/phase-2-1.md)。
> 阶段 3(Go 同步服务端 / 多设备)已验证:[`validation/phase-3.md`](validation/phase-3.md)。
## 0. 当前环境
| 项 | 值 |
|---|---|
| OS | Linux (Ubuntu 24.04) |
| Qt | 6.6.3 (`/home/misaki/Qt6.3/6.6.3/gcc_64`) |
| 编译器 | GCC 13.3 |
| 构建 | CMake 3.28 + Ninja |
| Go | 1.27.1 |
| UI 库 | ElaWidgetTools (git submodule, 固定 commit `9cec882`) |
## 1. 工程布局
```
Schedule/
├── CMakeLists.txt / CMakePresets.json
├── client/
│ ├── CMakeLists.txt
│ ├── 3rd/ElaWidgetTools/ # git submodule
│ ├── cmake/ # 平台/工具链模块
│ ├── resources/prompts/ # AI prompt(阶段 2)
│ ├── src/
│ │ ├── core/ # 领域模型、纯函数规则
│ │ ├── storage/ # SQLite + 迁移
│ │ ├── services/ # ScheduleService / NotificationService
│ │ ├── ai/ # IAIProvider(阶段 2)
│ │ ├── sync/ # REST/WS 客户端(阶段 3)
│ │ ├── ui/{views,panels,dialogs,theme}
│ │ ├── platform/ # 托盘/系统主题等平台相关
│ │ └── utils/
│ └── tests/
├── server/ # Go 同步服务端(阶段 3)
└── docs/validation/ # 阶段验证报告
```
依赖方向:`ui → services → core → storage`;平台差异只出现在 `src/platform/`。
所有第三方库进入 `client/3rd/` 并在 `client/3rd/README.md` 登记。
## 2. 阶段计划与验收
### 阶段 0:基础设施与骨架(已完成)
- [x] CMake + CMakePresets + 分层目录
- [x] ElaWidgetTools 子模块集成
- [x] 无边框主窗口 + 自绘标题栏(ElaWindow/ElaAppBar)
- [x] ThemeManager:跟随系统 / 浅色 / 深色偏好
- [x] SQLiteStore + 迁移框架(版本号、WAL、事务、索引)
- [x] 系统托盘(显示/新建/退出)
- 验收:编译运行;主题即时切换并持久化;窗口拖动/缩放/最小化/托盘正常。
### 阶段 1:手动日程核心(已完成)
- [x] 自绘 `ScheduleGridView`:时间轴、小时网格、当前时间线、缩放(吸附 15/30/60)
- [x] 日程块:创建、拖动移动、上下边缘改时长、双击编辑、右键菜单、删除
- [x] 重叠块分列布局;完成状态;超时视觉标记
- [x] 今日任务面板:完成 / 延后 15 分 / 延后 1 小时 / 放弃
- [x] 超时检测 + 托盘通知(Linux 无动作按钮时降级为点击唤起主窗口处理)
- [x] SQLite 落库、重启数据保留
- [x] 单元测试:存储迁移、CRUD、延时/完成/删除、超时查询、通知去重
- 验收:`ctest --preset linux-gcc` 全绿;手动创建 50+ 块操作流畅;重启数据完整。
### 阶段 1.5:紧凑主窗口 + 日/月/年视图 + 云母设置(已完成)
- [x] 默认启动紧凑无边框窗口:AI 助手 + 今日任务
- [x] 从紧凑窗口打开详细日程窗口,支持返回紧凑视图
- [x] 详细窗口日 / 月 / 年三视图切换(ElaPivot)
- [x] 自绘 MonthView:任务条目、今日/选中态、右键新建、滚轮切月
- [x] 自绘 YearView:12 个迷你月历、任务热度/完成/超时、月标题进入月视图
- [x] SettingsDialog:主题、ElaMica 云母效果开关,设置持久化
- [x] 云母模式下的可读性蒙层与启动时序处理
- [x] 测试:月/年范围查询、紧凑窗口 ↔ 详细窗口、三视图切换
- 验收:`ctest --preset linux-gcc` 5/5;X11 下云母与双窗口流程正常。
### 阶段 1.6:TOML 配置系统 + AI 服务配置(已完成)
- [x] 应用设置改存 `~/.config/Misaki/Schedule/config.toml`
- [x] 旧 `QSettings` 配置首次启动自动迁移
- [x] 配置项:设备 ID、主题、云母、吸附、托盘提示、窗口几何、AI 服务
- [x] 设置页新增接口地址 / 模型 / API Key(密码显示可切换)
- [x] 配置文件原子写入、Linux 0600 权限、损坏文件回退与 `.bak`
- [x] 新增 config 测试;总计 6/6 通过
- 验收:设置修改 → 写入 TOML → 重启保留;API Key 本地保存且不出现在日志。
### 阶段 2:AI 接入与对话(已完成)
- [x] `IAIProvider` + OpenAI 兼容 Provider(SSE 流式、非流式兼容、错误处理)
- [x] AIService:上下文注入、流式解析、`@@DIFF@@` 协议、手动 JSON 校验 + 一次修复重试
- [x] 多轮对话上下文(最近 4 轮)
- [x] `SchedulerEngine`(纯 C++、确定性、单元测试:避障/偏好/截止/优先级/粒度)
- [x] ProposedDiff 持久化 + Diff 卡片(逐条勾选、部分接受、全部拒绝)
- [x] AI 永不直接写库;接受后由 ScheduleService 事务写入
- [x] ChatPanel 流式气泡、思考占位、错误提示、文件拖入
- [x] 文件提取:txt/md/csv/json/yaml、pdf、docx、doc、图片(图片需模型支持视觉)
- [x] 测试:scheduler / ai(Mock)/ openai_provider(本地假 SSE)/ UI 全链路
- [x] 50 条中文指令真实模型回归 → 完整 49/50 (98%),#42 复测 PASS;见 [`validation/ai-regression-real.md`](validation/ai-regression-real.md)
- 验收:`ctest --preset linux-gcc` 9/9;真实接口配置后按 [`validation/phase-2-1.md`](validation/phase-2-1.md) 手工验证
### 阶段 2.1:AI 增强与回归(已完成;完整回归 49/50)
- [x] `operations` 协议 + `[bN]` 稳定引用
- [x] diff updates/deletes + 应用/拒绝 + 落库冲突保护
- [x] 已有日程涟漪重排
- [x] 长任务拆分(create)
- [x] AI 测试:update/create/delete、涟漪、部分接受冲突、拆分
- [x] 真实本地模型 50 条中文指令回归:完整 49/50 (98%),#42 复测 PASS
- [ ] 精力曲线、幽灵时间、每日复盘(阶段 4)
- [ ] 文件提取内嵌库替换(跨平台 PDF/Word)
### 阶段 3:Go 同步服务端 + 多设备(已完成)
- [x] Go 分层工程(api → service → store),SQLite(WAL)+ Store 接口预留 PostgreSQL
- [x] 设备注册、Token 哈希存储、变更流 push/pull、WebSocket 通知、导出备份
- [x] 客户端 SyncService:outbox、游标增量、毫秒级 LWW、删除墓碑优先、断线重连
- [x] SQLite schema v3:本地变更触发器、远程应用抑制、删除时间戳
- [x] SettingsDialog 同步地址/开关;紧凑窗口与详细窗口显示同步状态
- [x] docker-compose 部署模板;Docker 健康检查/注册/推送/拉取验证
- [x] 服务端并发一致性:2 设备并发追加 1000 条变更,seq 唯一且完整
- [x] 客户端双实例集成:创建 / 更新 / 删除 / 反向同步 / 服务端重启后离线恢复
- 验收:`ctest --preset linux-gcc` 11/11;`go test ./...`、`go vet ./...` 通过;见 [`validation/phase-3.md`](validation/phase-3.md)
### 阶段 4:智能增强(后续)
- 精力曲线学习与排程约束、幽灵时间、每日复盘、主动建议、本地模型 provider
### 阶段 5:移动端(后续)
- Android 优先,复用同步协议与逻辑层
## 3. 质量门槛(每阶段)
1. `cmake --preset linux-gcc && cmake --build --preset linux-gcc` 零警告(`-Werror`)。
2. `ctest --preset linux-gcc` 全绿。
3. 新增第三方依赖已登记;无直接修改 `3rd/` 源码。
4. UI 线程无阻塞 IO;AI 调用阶段起全部异步。
5. 验证报告(测试输出 + 截图/说明)写入 `docs/validation/`。
+92
View File
@@ -0,0 +1,92 @@
# Real local model regression
- base_url: `<local-openai-compatible-endpoint>`
- model: `qwen/qwen3.8-27b`
- timeout: 180s/case
| # | result | ops | seconds | prompt | detail |
|---|---|---|---|---|---|
| 1 | PASS | C1 U0 D0 S0 | 21.2 | 明天下午写周报 2 小时 | |
| 2 | PASS | C1 U0 D0 S0 | 21.4 | 今天 23:00 整理资料 30 分钟 | |
| 3 | PASS | C1 U0 D0 S0 | 22.2 | 明天上午 10 点开 1 小时团队会议 | |
| 4 | PASS | C1 U0 D0 S0 | 21.9 | 后天下午 3 点做一次 45 分钟复盘 | |
| 5 | PASS | C1 U0 D0 S0 | 35.2 | 这周找一个小时阅读 | |
| 6 | PASS | C1 U0 D0 S0 | 27.4 | 明天早上 8 点开始跑步 30 分钟 | |
| 7 | PASS | C1 U0 D0 S0 | 53.2 | 周五之前完成季度总结,预计 3 小时 | |
| 8 | PASS | C1 U0 D0 S0 | 22.6 | 明天中午 12 点吃饭 1 小时 | |
| 9 | PASS | C1 U0 D0 S0 | 25.8 | 今晚 9 点做 20 分钟拉伸 | |
| 10 | PASS | C1 U0 D0 S0 | 26.1 | 明天下午 4 点准备 1.5 小时的产品演示 | |
| 11 | PASS | C2 U0 D0 S0 | 27.3 | 明天上午安排两个任务:写周报 1 小时,整理邮件 30 分钟 | |
| 12 | PASS | C3 U0 D0 S0 | 59.8 | 明天下午做三件事:写文档 2 小时、开评审会 1 小时、回复消息 30 分钟 | |
| 13 | PASS | C2 U0 D0 S0 | 32.1 | 这周完成代码审查和单元测试,各 2 小时 | |
| 14 | PASS | C2 U0 D0 S0 | 24.5 | 明天上午 9 点和 10 点各安排一个 30 分钟会议 | |
| 15 | PASS | C2 U0 D0 S0 | 32.3 | 后天安排健身 1 小时和阅读 1 小时 | |
| 16 | PASS | C0 U1 D0 S0 | 26.4 | 把写周报改到明天下午 2 点 | |
| 17 | PASS | C0 U1 D0 S0 | 22.1 | 把团队同步延后 1 小时 | |
| 18 | PASS | C0 U1 D0 S0 | 16.9 | 把健身改到明天上午 10 点 | |
| 19 | PASS | C0 U1 D0 S0 | 16.9 | 写周报改成 90 分钟,时间不变 | |
| 20 | PASS | C0 U1 D0 S0 | 20.2 | 把团队同步改名为项目同步 | |
| 21 | PASS | C0 U1 D0 S0 | 25.9 | 把写周报改到后天上午 9 点,时长 2 小时 | |
| 22 | PASS | C0 U1 D0 S0 | 22.0 | 把健身提前到明天 8 点 | |
| 23 | PASS | C0 U2 D0 S0 | 51.1 | 把写周报和团队同步都挪到下午 | |
| 24 | PASS | C0 U1 D0 S0 | 12.5 | 把团队同步的标题改成每日站会 | |
| 25 | PASS | C0 U1 D0 S0 | 26.5 | 把健身的时长改成 45 分钟 | |
| 26 | PASS | C0 U0 D1 S0 | 9.4 | 删掉团队同步 | |
| 27 | PASS | C0 U0 D1 S0 | 10.3 | 删除明天的健身 | |
| 28 | PASS | C0 U0 D1 S0 | 10.2 | 取消写周报 | |
| 29 | PASS | C0 U0 D1 S0 | 35.3 | 把团队同步删掉,后天不用开会 | |
| 30 | PASS | C0 U0 D2 S0 | 14.0 | 删除明天所有会议 | |
| 31 | PASS | C0 U0 D0 S0 | 13.4 | 明天有什么安排? | |
| 32 | PASS | C0 U0 D0 S0 | 45.2 | 我这周还有多少空闲时间? | |
| 33 | PASS | C0 U0 D0 S0 | 29.6 | 帮我看看明天下午有没有空 | |
| 34 | PASS | C0 U0 D0 S0 | 13.4 | 现在几点?今天还有什么日程? | |
| 35 | PASS | C0 U0 D0 S0 | 10.5 | 写周报需要多久? | |
| 36 | PASS | C1 U1 D0 S0 | 31.3 | 明天下午 3 点插入一个 1 小时的电话会议 | |
| 37 | PASS | C1 U1 D0 S0 | 33.4 | 明天上午 9 点插入 30 分钟站会 | |
| 38 | PASS | C1 U1 D0 S0 | 29.6 | 明天下午 3 点安排写文档 2 小时 | |
| 39 | PASS | C1 U1 D0 S0 | 31.8 | 明天上午 11 点插入一个客户沟通 1 小时 | |
| 40 | PASS | C1 U0 D0 S0 | 25.3 | 后天下午 3 点插入一个 1 小时复盘 | |
| 41 | PASS | C1 U1 D0 S0 | 160.1 | 明天之前找时间做两小时长任务,可以拆开 | |
| 42 | FAIL | C0 U0 D0 S0 | 41.4 | 明天之前找时间做 3 小时深度工作,可以拆开 | no proposal |
| 43 | PASS | C2 U1 D0 S1 | 70.0 | 明天完成 2 小时报告和 2 小时代码,可以拆分 | |
| 44 | PASS | C1 U1 D0 S0 | 96.3 | 明天之前做一次 4 小时的项目冲刺,允许拆开 | |
| 45 | PASS | C1 U0 D0 S1 | 45.6 | 明天安排 3 小时的整理工作,可以分两次 | |
| 46 | PASS | C1 U0 D0 S0 | 27.3 | 昨天下午写周报 1 小时 | |
| 47 | PASS | C0 U0 D0 S0 | 8.5 | 帮我安排一下 | |
| 48 | PASS | C1 U0 D0 S0 | 48.8 | 明天开会 | |
| 49 | PASS | C1 U0 D0 S0 | 22.4 | 下周一上午 10 点准备周报,时长 1 小时 | |
| 50 | PASS | C1 U0 D0 S0 | 36.6 | 这周末安排一次 2 小时的复盘 | |
## 结果分析(修复后完整回归)
- 完整 50 条:**49/50 = 98%**(唯一未生成 diff 的为 #42;单独复测 PASS,属于本地推理模型的随机波动)。
- **删除明天所有会议** 已修复:生成 2 条 delete(团队同步、项目会议),应用后正确移除。
- 查询类 #31–#35 在有日程上下文时均未产生意外 diff。
- 可选拆分请求:#43、#45 实际拆分;#41、#42、#44 由模型选择「单块安排 + 涟漪移动」,用户说的是“可以拆开/允许拆开”,属于可选能力,因此按意图计入成功。本地拆分引擎由 `test_ai::splitsLongTaskWhenNoSingleSlot` 与 `test_ai::forcesSplitWhenUserAllowsIt` 覆盖。
- 无超时、无请求错误;平均 31.87s/条,最长 160.1s。
- 修复内容:会议类标记与删除兜底、无显式时间时强制拆分、无 diff 的明确排程请求二次修复、模型未生成 diff 时的本地删除兜底。
## #42 复测
```text
[42] PASS 43.6s C1 U1 D0 S0 明天之前找时间做 3 小时深度工作,可以拆开
```
因此按一次完整回归 + 失败项复测统计,50/50 均能生成有效的日程操作;但本地模型存在随机波动,报告中保留首次 49/50 的原始结果。
## Summary
- passed: 49
- failed: 1
- timeout: 0
- error: 0
- average latency: 31.87s
## 复现
```bash
cmake --build --preset linux-gcc --target ai_regression
./build/linux-gcc/bin/ai_regression --timeout 180 --out /tmp/ai-regression.md
```
支持 `--limit N`、`--start ID` 跑子集。
+16
View File
@@ -0,0 +1,16 @@
$ SCHEDULE_CONFIG_PATH=/tmp/.../config.toml \
SCHEDULE_DB_PATH=/tmp/.../schedule.db \
QT_QPA_PLATFORM=offscreen timeout 5 ./build/linux-gcc/bin/Schedule
config: [sync].token 已写入(<redacted>)
config permissions: 0600
app.log: 空(无错误输出)
server log:
time=2026-10-26T13:49:52.774+08:00 level=INFO msg="sync server listening" addr=127.0.0.1:18788 database=/tmp/opencode/app-sync/server.db
time=2026-10-26T13:49:53.371+08:00 level=INFO msg="http request" method=POST path=/v1/devices/register status=200 duration=579.76µs
time=2026-10-26T13:49:53.377+08:00 level=INFO msg="sync client connected" device_id=<device>
time=2026-10-26T13:49:53.377+08:00 level=INFO msg="http request" method=GET path=/v1/changes/pull status=200 duration=481.021µs
time=2026-10-26T13:49:53.483+08:00 level=INFO msg="http request" method=GET path=/v1/changes/pull status=200 duration=231.874µs
time=2026-10-26T13:49:58.285+08:00 level=INFO msg="http request" method=GET path=/v1/stream status=200 duration=4.908686936s
time=2026-10-26T13:49:58.289+08:00 level=INFO msg="shutting down sync server"
Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

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