Author SHA1 Message Date
Morris cf05e886ac refactor: 全窗口统一 Avalonia,移除 Flutter/Dart,新增 Java 实现
- 恢复同代 GC Avalonia 主界面(主页/下载/设置/关于)替换 Flutter
- 模型窗口统一 Avalonia;HTML 课件用 WebView.Avalonia 内嵌渲染
- 新增 CoursewareServer(回环 HTTP + Range)与 CoursewareWindow
- 彻底移除 Flutter/Dart 前端及构建脚本相关逻辑
- 新增 ./build.sh run 开发运行命令
- 项目源码整理到 C#/ 子目录,新增 Java/ 实现
- 工作日志随项目迁移
2026-11-27 10:09:30 +08:00
Morris 3f1f48f54c Merge pull request 'ci(build-bot): 支持 version= 指定版本并加速 macOS 构建' (#40) from ci/buildbot-mac-speed into main
Reviewed-on: #40
2026-11-22 00:14:12 +00:00
远影科技 8b4cabba28 ci(build-bot): 支持 version= 参数指定版本;mac 大小写不敏感;加速 macOS 构建
PR 审核 / 后端编译 (pull_request) Canceled after 0s
PR 审核 / 后端自检 (pull_request) Canceled after 0s
PR 审核 / 前端检查(Flutter) (pull_request) Canceled after 0s
PR 审核 / 安全扫描 (pull_request) Canceled after 0s
PR 审核 / 审核汇总 (pull_request) Canceled after 0s
1. @build-bot build mac version=1.1.3 可指定版本(缺省仍读 Directory.Build.props)
   - 评论里 version=x.y.z 优先,大小写不敏感
   - mac / Mac / MAC 都能匹配(grep -oiE 已忽略大小写)
   - 版本透传给 build.sh / build.ps1,回帖与 Release notes 都显示版本
2. macOS 构建提速
   - 缓存 NuGet 包(~/.nuget/packages)与 CocoaPods(Pods/ + Caches)
   - runner 固定 macos-14(原生 arm64,避开 Rosetta 模拟)
   - build-bot 与 build-release 两个工作流同步优化
2026-11-22 08:09:23 +08:00
远影科技 40d9da1c3d fix: 后端连接失败自动重连重试;签到与每日计数改按本地日历日
1. 有时无法连接后端:
- 根因:请求连接失败直接抛错,运行中从不重新发现地址(睡眠唤醒后旧连接已死、后端换端口后必现)
- _send 对 GET 连接失败自动 rediscover + 重试 1 次;POST 不自动重试,避免签到/扣积分重复提交
- 启动重试从 5 次(约 31s)放宽到 10 次、间隔封顶 8s

2. 签到读日历,不按 24 小时:
- 根因:签到用 DateTime.UtcNow.Date,东八区要早上 8 点才翻篇,凌晨可同一天签到两次
- UserService(签到/人品值/二选一跨天计数)与 UserPayload 统一改 DateTime.Today 本地日历日
- 实测:本地 11-22 07:33(UTC 仍 11-21)时 last_sign_in=11-22,重复签到被拒,免费次数按本地日重置
2026-11-22 07:33:56 +08:00
远影科技 cfd6809714 feat: 模型回退 Avalonia 独立窗口;积分精确到 0.01;人品值/二选一接入后端计费
模型(回退 Flutter 内嵌 → Avalonia):
- 恢复 model/_sdk、5 个模型 src/、GC-DRAW/PlayerWindow、ModelHost/AvaloniaHost(源自 5b62897)
- FlutterShell 主线程承载 Avalonia 事件循环,根治 1.1.1 的 AppKit 崩溃
- /api/models/{id}/launch 由后端开独立 Avalonia 窗口
- 前端删除 Flutter 模型实现与 ModelViewPage 死代码(13 个文件)

积分:
- Points/ThemePaid int → decimal,精确到 0.01;pw.yaml 兼容旧整数格式
- 主题色退款保留 2 位小数;前端新增 formatPoints 显示

人品值/二选一计费(原前端本地免费随机 → 后端计费):
- 新增 POST /api/user/fortune、/api/user/pick,随机数与扣费都在服务端
- 人品值阶梯:当日免费 1 次 → 0.1×5 → 0.2×5 → 0.5×15 → 1.0 起
- 二选一:当日免费 1 次 → 0.5/次;计数按 UTC 日期持久化,跨天清零
- 前端两个功能需登录,扣费后提示本次消耗

附 RELEASE-1.1.2.md 更新日志。
2026-11-21 21:51:34 +08:00
Morris 38781c9807 refactor(ui): 删除百宝箱页;设置页去掉主题色
- 删除 pages/treasure.dart 与侧栏「百宝箱」入口,用户页从 index 6 前移到 5
- 清理 pages.dart 导出与 i18n 里的 nav.treasure / treasure.* 键
- 设置页移除主题色色板、自定义颜色入口与 _applyAccent 等实现
- 强调色改由用户账号的 theme_color 决定:
  · controller._applySettings 不再应用 settings.accentColor
  · 启动后 _applyUserTheme() 拉一次 /api/user/me 并按 theme_color 上色
  · 退出登录回落到 GcPalette.defaultAccent
- 清理 i18n 中的 set.accent.* 键与 settings.dart 无用的 dart:async 导入
2026-11-21 20:45:25 +08:00
Morris 185a8905f9 Merge pull request 'feat(user): 用户系统重做——人机验证、签到、主题色购买与退款' (#39) from feat/user-system into main
Reviewed-on: #39
2026-11-21 12:43:37 +00:00
Morris ecb71ad347 feat(user): 用户系统重做——人机验证、30 天签到、主题色购买与退款、人品值
PR 审核 / 后端编译 (pull_request) Canceled after 0s
PR 审核 / 后端自检 (pull_request) Canceled after 0s
PR 审核 / 前端检查(Flutter) (pull_request) Canceled after 0s
PR 审核 / 安全扫描 (pull_request) Canceled after 0s
PR 审核 / 审核汇总 (pull_request) Canceled after 0s
存储
- 目录改为 .GC/user/<用户名>/pw.yaml(用户名、积分、sha512 口令 + 盐)
- .GC/user/user.yaml 记住当前登录(用户名 + session token),启动自动登录
- 自动迁移旧的 .GC/user/<用户名>.yaml

注册 / 登录
- 新增算术人机验证:GET /api/user/captcha(5 分钟有效、一次性、用后即焚)
- 用户名不可重复、不能含空格、1–20 字符
- 口令只存 sha512(密码 + ":" + 随机盐),不存明文
- 新增 /api/user/logout

签到
- 30 天一循环:1–6 天 +10,第 7 天 +30,8–13 +15,第 14 天 +40,
  15–20 +20,第 21 天 +50,22–27 +25,第 28 天 +60,29 天 +40,第 30 天 +100
- 断签重置连续天数;接口返回 cycle_day / next_reward / today_signed

主题色
- 默认蓝免费,预置色 50,自定义色 150(服务端算价,不信客户端)
- 购买后 1 小时内换色退 80%,record 里存 theme_paid / theme_paid_at
- 禁止充值:积分只能签到获得

前端用户页
- 账号卡片:积分、连续天数、周期进度条、一键签到、退出登录
- 注册表单内嵌验证码(换一题、失败自动刷新)
- 人品值:0–100 随机 + 评语,每天不限次数
- 二选一:两个输入框随机选一个
- 主题色:8 个预置色 + 自定义色取色(十六进制 + 预览),积分不足上锁
- 应用主题色时同步覆盖全局强调色
2026-11-21 20:26:02 +08:00
Morris e7c1429889 feat(ci): 新增 @build-release-bot build <版本号>
编译 macOS + Windows(amd64/arm64),发布 tag = 版本号的正式 Release(非预发布)。

- prepare 解析版本号(必须 主.次.修订),tag 已存在则拒绝并回帖说明
- 两个平台都成功才发 Release,附 SHA256SUMS.txt
- 独立的 report job:任何一步失败都会回帖,列出各平台与发布状态
- 不动 version.json(需 SAVEDOG 签名,CI 无私钥),文档里注明走本地 ./build.sh stamp
- mac job 增加环境自检(sw_vers / xcodebuild -version / flutter --version)
2026-11-21 20:18:28 +08:00
Morris 5b82a885f9 fix(build-bot): report job 加 GH_REPO;已合并 PR 改为编默认分支
- report job 不 checkout,gh 没有 git 上下文会报
  'fatal: not a git repository' → 补 GH_REPO 环境变量
- 只有 state=open 的 PR 才编它的 head.sha;
  已合并/已关闭的 PR 编译默认分支,避免编到过期代码
- 回执里提示「PR 已 merged,改为编译默认分支」
2026-11-21 19:56:13 +08:00
Morris 936ef8333e fix: macOS 构建去掉 --no-codesign;build-bot 失败也回帖结果
- flutter build macos 不支持 --no-codesign(那是 iOS 的选项),
  传了会直接报 'Could not find an option named no-codesign' 导致编译失败。
  macOS 模板本身用 ad-hoc 签名,CI 无证书也能构建。
- 删除 workflow 里的 GC_NO_CODESIGN 环境变量
- build-bot 新增独立 report job(always):
  编译/发布任何一步失败都会回帖,列出各平台结果与日志链接,
  不再因为 publish 被跳过而静默
2026-11-21 19:47:57 +08:00
Morris ab0cee8b40 ci: build-bot 增加「开始编译」回执;macOS runner 改用 macos-latest
- 收到 @build-bot build <目标> 后立即回帖「开始编译」,附来源提交、目标、日志链接
- 编译完成仍走原来的结果回帖(成功给 release 链接,失败给日志链接)
- runs-on: macos-14 → macos-latest:
  macos-14 在本仓库被判为 'macos-14-arm64-us-default' 不受支持,job 在启动前即被取消
2026-11-21 19:44:32 +08:00
Morris b51ebd1a3d Merge pull request #3 from Morris-morris-cloud/feat/github-source-and-ci
feat: 全面迁移到 Flutter + 新增 GitHub 源与 CI 流水线
2026-11-21 19:40:26 +08:00
Morris c08206e7db Merge pull request #1 from Morris-morris-cloud/feat/github-source-and-ci
feat: 全面迁移到 Flutter + 新增 GitHub 源与 CI 流水线
2026-11-21 19:33:42 +08:00
Morris 2b036d2226 Merge pull request 'feat: 全面迁移到 Flutter + 新增 GitHub 源与 CI 流水线' (#38) from feat/github-source-and-ci into main
Reviewed-on: #38
2026-11-21 11:25:32 +00:00
425 changed files with 27520 additions and 21096 deletions

No files matched your search

+26 -2
View File
@@ -6,9 +6,11 @@
| --- | --- | --- |
| `nightly-prerelease.yml` | 每天 21:00(Asia/Shanghai),或手动 | 编译 macOS + Windows(amd64/arm64),发布 **`nightly`** 预发布 |
| `build-bot.yml` | Issue / PR 评论里 `@build-bot build <目标>` | 只编译指定平台,发布 **`ip-prerelease`** 预发布 |
| `build-release.yml` | Issue / PR 评论里 `@build-release-bot build <版本号>` | 编译三平台,发布 **tag = 版本号** 的正式 Release |
| `pr-review.yml` | 向 main 提 PR(新建 / 有新提交 / 重新打开) | 检查能否编译、是否有错、是否冲突、是否落后 main |
两个预发布用**不同的 tag**,互不覆盖:夜间构建发 `nightly`,手动触发的发 `ip-prerelease`。
预发布用**不同的 tag**,互不覆盖:夜间构建发 `nightly`,`@build-bot` 发 `ip-prerelease`;
`@build-release-bot` 发的是正式版本(tag 就是版本号,会更新 latest)。
## 每夜构建
@@ -59,5 +61,27 @@
- `Settings → Actions → General → Workflow permissions` 给 **Read and write**,
否则 `gh release` / 评论接口会 403(工作流里已声明 `permissions:`,但组织策略可能覆盖)。
- Secrets 不需要额外配置,统一用内置的 `GITHUB_TOKEN`。
- macOS 产物是 **未签名** 的(`GC_NO_CODESIGN=1`)。下载后首次打开需右键 →「打开」,
- macOS 产物是 **ad-hoc 签名**(无开发者证书)。下载后首次打开需右键 →「打开」,
或在「系统设置 → 隐私与安全性」里放行。
## build-release 用法
在 Issue 或 PR 里评论:
```
@build-release-bot build 1.1.3
```
规则:
- 版本号必须是 `主.次.修订`(如 `1.1.3`),其它写法会被忽略
- tag 已存在时不会触发,会回帖说明「请换一个版本号」——同一个 tag 发两次会让客户端拿到两份不同内容
- 只有 `OWNER` / `MEMBER` / `COLLABORATOR` 能触发
- 编 macOS + Windows(amd64/arm64),**两个平台都成功**才发 Release,否则只回帖失败原因
- Release 附带 `SHA256SUMS.txt`
- **不会**改动仓库里的 `version.json`:它由 GC-SAVEDOG 签名,CI 没有签名私钥。清单更新请在本地跑 `./build.sh stamp`
## macOS runner
统一用 `macos-latest`。`macos-14` 在本账号会被判为 `macos-14-arm64-us-default` 不受支持,
job 在启动前就变成 cancelled。runner 自带多个版本的 Xcode 和 CocoaPods,不需要额外安装。
+123 -21
View File
@@ -1,10 +1,11 @@
name: build-bot
# 在 Issue / PR 里评论触发编译:
# @build-bot build mac 编译 macOS
# @build-bot build win-amd 编译 Windows amd64
# @build-bot build win-arm 编译 Windows arm64
# @build-bot build all 三个平台全编
# @build-bot build mac 编译 macOS(大小写均可:Mac / MAC)
# @build-bot build mac version=1.1.3 编译 macOS 1.1.3(不写 version= 则用仓库当前版本)
# @build-bot build win-amd 编译 Windows amd64
# @build-bot build win-arm 编译 Windows arm64
# @build-bot build all 三个平台全编
# 产物发布到 ip-prerelease 预发布(同一 tag 滚动更新,不删别的平台资产)。
on:
@@ -69,8 +70,18 @@ jobs:
echo "ok=true" >> "$GITHUB_OUTPUT"
echo "target=$TARGET" >> "$GITHUB_OUTPUT"
VERSION=$(sed -n 's:.*<Version>\(.*\)</Version>.*:\1:p' Directory.Build.props | head -1)
[ -n "$VERSION" ] || VERSION=1.0.0
# 版本号:评论里的 version=x.y.z 优先(大小写不敏感),没有则用仓库当前版本。
CLI_VERSION=$(printf '%s' "$BODY" \
| grep -oiE 'version[[:space:]]*=[[:space:]]*[0-9]+\.[0-9]+\.[0-9]+' \
| head -1 \
| sed -E 's/.*=[[:space:]]*//' || true)
if [ -n "$CLI_VERSION" ]; then
VERSION="$CLI_VERSION"
echo "使用评论指定版本:$VERSION"
else
VERSION=$(sed -n 's:.*<Version>\(.*\)</Version>.*:\1:p' Directory.Build.props | head -1)
[ -n "$VERSION" ] || VERSION=1.0.0
fi
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
# Issue 评论挂在 PR 上时,用 PR 的 head 提交;否则用默认分支最新
@@ -79,13 +90,52 @@ jobs:
echo "is_pr=$IS_PR" >> "$GITHUB_OUTPUT"
if [ "$IS_PR" = "true" ]; then
REF=$(gh api "repos/${{ github.repository }}/pulls/${ISSUE_NUMBER}" --jq '.head.sha')
# 只有「还开着」的 PR 才编它的 head;已合并/已关闭的 PR 编默认分支,
# 否则会编到一份过期的代码。
PR_STATE=$(gh api "repos/${{ github.repository }}/pulls/${ISSUE_NUMBER}" --jq '.state')
if [ "$PR_STATE" = "open" ]; then
REF=$(gh api "repos/${{ github.repository }}/pulls/${ISSUE_NUMBER}" --jq '.head.sha')
else
REF="${{ github.event.repository.default_branch }}"
echo "PR 已 $PR_STATE,改为编译默认分支"
fi
else
REF="${{ github.event.repository.default_branch }}"
fi
echo "ref=$REF" >> "$GITHUB_OUTPUT"
echo "目标=$TARGET 提交=$REF 是否PR=$IS_PR"
- name: 回复「开始编译」
if: steps.parse.outputs.ok == 'true'
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
ISSUE: ${{ github.event.issue.number }}
TARGET: ${{ steps.parse.outputs.target }}
REF: ${{ steps.parse.outputs.ref }}
VERSION: ${{ steps.parse.outputs.version }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
run: |
set -e
case "$TARGET" in
mac) PLATFORMS="macOS" ;;
win-amd) PLATFORMS="Windows amd64" ;;
win-arm) PLATFORMS="Windows arm64" ;;
*) PLATFORMS="macOS + Windows amd64 + Windows arm64" ;;
esac
cat > ack.md <<EOF
🔨 **开始编译**:${PLATFORMS}
- 来源提交:\`${REF:0:7}\`
- 目标:\`${TARGET}\`
- 版本:\`${VERSION}\`
- 实时日志:${RUN_URL}
编译完成后会在这里回复结果。
EOF
gh issue comment "$ISSUE" --body-file ack.md
build-mac:
needs: prepare
if: needs.prepare.outputs.ok == 'true' && (needs.prepare.outputs.target == 'mac' || needs.prepare.outputs.target == 'all')
@@ -99,17 +149,33 @@ jobs:
with:
dotnet-version: ${{ env.DOTNET_VERSION }}
# NuGet 包缓存:Avalonia / CommunityToolkit 等依赖每次冷下载要几分钟,
# 依赖没变时直接命中缓存。key 基于所有 csproj + .props。
- uses: actions/cache@v4
with:
path: ~/.nuget/packages
key: ${{ runner.os }}-nuget-${{ hashFiles('**/*.csproj', '**/*.props', '**/packages.lock.json') }}
restore-keys: ${{ runner.os }}-nuget-
- uses: subosito/flutter-action@v2
with:
flutter-version: ${{ env.FLUTTER_VERSION }}
channel: stable
cache: true
# CocoaPods:Pods/ 被 gitignore,Podfile.lock 没变时复用,省掉每次 pod install
- uses: actions/cache@v4
with:
path: |
GC-UI/frontend/macos/Pods
~/Library/Caches/CocoaPods
key: ${{ runner.os }}-pods-${{ hashFiles('GC-UI/frontend/macos/Podfile.lock') }}
restore-keys: ${{ runner.os }}-pods-
- name: 编译 macOS
env:
GC_NO_CODESIGN: '1'
GC_NO_PROGRESS: '1'
run: ./build.sh build --targets=mac
run: ./build.sh build --targets=mac -version=${{ needs.prepare.outputs.version }}
- uses: actions/upload-artifact@v4
with:
@@ -141,7 +207,7 @@ jobs:
cache: true
- name: 编译 Windows
run: ./build.ps1 build
run: ./build.ps1 build -Version ${{ needs.prepare.outputs.version }}
- uses: actions/upload-artifact@v4
with:
@@ -200,7 +266,7 @@ jobs:
run: |
set -e
cat > notes.md <<EOF
手动触发构建(\`@build-bot build ${TARGET}\`)。
手动触发构建(\`@build-bot build ${TARGET} version=${VERSION}\`)。
触发人:@${ACTOR}
来源:#${ISSUE}
@@ -223,18 +289,54 @@ jobs:
echo "https://github.com/${{ github.repository }}/releases/tag/$TAG" >> "$GITHUB_STEP_SUMMARY"
- name: 回帖
if: always()
# 结果回帖独立成一个 job:编译失败 / 发布失败也要有回音,
# 不能因为 publish 被跳过就静默。
report:
needs: [prepare, build-mac, build-win, publish]
if: always() && needs.prepare.outputs.ok == 'true'
runs-on: ubuntu-latest
steps:
- name: 回帖结果
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TARGET: ${{ needs.prepare.outputs.target }}
# 本 job 不 checkout(省时间),gh 需要显式指定仓库
GH_REPO: ${{ github.repository }}
ISSUE: ${{ github.event.issue.number }}
STATE: ${{ steps.publish_step.outcome }}
TARGET: ${{ needs.prepare.outputs.target }}
REF: ${{ needs.prepare.outputs.ref }}
MAC: ${{ needs.build-mac.result }}
WIN: ${{ needs.build-win.result }}
PUB: ${{ needs.publish.result }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
run: |
if [ "$STATE" = "success" ]; then
MSG="已编译 **${TARGET}** 并发布到预发布:https://github.com/${{ github.repository }}/releases/tag/ip-prerelease"
else
MSG="编译 **${TARGET}** 失败,见日志:${RUN_URL}"
fi
gh issue comment "$ISSUE" --body "$MSG"
set -e
REPO="${{ github.repository }}"
line() {
case "$2" in
success) echo "- $1:✅ 成功" ;;
skipped) echo "- $1:⏭ 未请求(跳过)" ;;
cancelled) echo "- $1:⛔ 已取消" ;;
*) echo "- $1:❌ 失败" ;;
esac
}
{
if [ "$PUB" = "success" ]; then
echo "✅ **编译完成**:\`${TARGET}\`"
else
echo "❌ **编译未完成**:\`${TARGET}\`"
fi
echo
line "macOS" "$MAC"
line "Windows" "$WIN"
echo
echo "- 来源提交:\`${REF:0:7}\`"
if [ "$PUB" = "success" ]; then
echo "- 产物:https://github.com/${REPO}/releases/tag/ip-prerelease"
else
echo "- 日志:${RUN_URL}"
fi
} > result.md
gh issue comment "$ISSUE" --body-file result.md
+309
View File
@@ -0,0 +1,309 @@
name: build-release
# 在 Issue / PR 里评论触发「编译 + 发布正式版本」:
# @build-release-bot build 1.1.3
#
# 与 build-bot 的区别:
# build-bot 只编译,产物丢进 ip-prerelease(预发布,反复覆盖)
# build-release 编译三平台,发一个 tag = 版本号的正式 Release(会更新 latest)
#
# 不会改动仓库里的 version.json:它由 GC-SAVEDOG 签名,CI 里没有签名私钥,
# 重新 stamp 会产出一份客户端拒绝接受的清单。清单更新请走本地 ./build.sh stamp。
on:
issue_comment:
types: [created]
concurrency:
group: release-manual
cancel-in-progress: false
permissions:
contents: write
issues: write
pull-requests: write
env:
TZ: Asia/Shanghai
DOTNET_VERSION: '8.0.x'
FLUTTER_VERSION: '3.24.5'
jobs:
prepare:
if: |
contains(github.event.comment.body, '@build-release-bot') &&
(github.event.comment.author_association == 'OWNER' ||
github.event.comment.author_association == 'MEMBER' ||
github.event.comment.author_association == 'COLLABORATOR')
runs-on: ubuntu-latest
outputs:
ok: ${{ steps.parse.outputs.ok }}
version: ${{ steps.parse.outputs.version }}
ref: ${{ steps.parse.outputs.ref }}
reason: ${{ steps.parse.outputs.reason }}
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- id: parse
name: 解析版本号并预检
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
BODY: ${{ github.event.comment.body }}
run: |
set -e
# 只认 主.次.修订,其它写法直接忽略
VER=$(printf '%s' "$BODY" \
| grep -oiE '@build-release-bot[[:space:]]+build[[:space:]]+[0-9]+\.[0-9]+\.[0-9]+' \
| head -1 \
| awk '{print $NF}' || true)
if [ -z "$VER" ]; then
echo "ok=false" >> "$GITHUB_OUTPUT"
echo "reason=没有匹配到合法版本号(格式:@build-release-bot build 1.2.3)" >> "$GITHUB_OUTPUT"
echo "未匹配到版本号,忽略"
exit 0
fi
echo "version=$VER" >> "$GITHUB_OUTPUT"
echo "ref=${{ github.event.repository.default_branch }}" >> "$GITHUB_OUTPUT"
echo "版本号=$VER"
# tag 已存在就不能再发:重复 tag 会让客户端拿到两份不同内容
if gh api "repos/${{ github.repository }}/git/ref/tags/${VER}" >/dev/null 2>&1; then
echo "ok=false" >> "$GITHUB_OUTPUT"
echo "reason=tag ${VER} 已存在,请换一个版本号" >> "$GITHUB_OUTPUT"
echo "tag ${VER} 已存在"
exit 0
fi
echo "ok=true" >> "$GITHUB_OUTPUT"
echo "reason=" >> "$GITHUB_OUTPUT"
- name: 回复「开始编译并发布」
if: steps.parse.outputs.ok == 'true'
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GH_REPO: ${{ github.repository }}
ISSUE: ${{ github.event.issue.number }}
VER: ${{ steps.parse.outputs.version }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
run: |
set -e
cat > ack.md <<EOF
🔨 **开始编译并发布 \`${VER}\`**
平台:macOS (arm64) + Windows (amd64 / arm64)
- 实时日志:${RUN_URL}
编译完成后会在这里回复结果。
EOF
gh issue comment "$ISSUE" --body-file ack.md
- name: 回复「忽略原因」
if: steps.parse.outputs.ok != 'true'
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GH_REPO: ${{ github.repository }}
ISSUE: ${{ github.event.issue.number }}
REASON: ${{ steps.parse.outputs.reason }}
run: |
set -e
gh issue comment "$ISSUE" --body "⏭ 未触发:${REASON}"
build-mac:
needs: prepare
if: needs.prepare.outputs.ok == 'true'
runs-on: macos-14
steps:
- uses: actions/checkout@v4
with:
ref: ${{ needs.prepare.outputs.ref }}
- uses: actions/setup-dotnet@v4
with:
dotnet-version: ${{ env.DOTNET_VERSION }}
# NuGet 包缓存:依赖没变时省去冷下载
- uses: actions/cache@v4
with:
path: ~/.nuget/packages
key: ${{ runner.os }}-nuget-${{ hashFiles('**/*.csproj', '**/*.props', '**/packages.lock.json') }}
restore-keys: ${{ runner.os }}-nuget-
- uses: subosito/flutter-action@v2
with:
flutter-version: ${{ env.FLUTTER_VERSION }}
channel: stable
cache: true
# CocoaPods:Pods/ 被 gitignore,Podfile.lock 没变时复用,省掉 pod install
- uses: actions/cache@v4
with:
path: |
GC-UI/frontend/macos/Pods
~/Library/Caches/CocoaPods
key: ${{ runner.os }}-pods-${{ hashFiles('GC-UI/frontend/macos/Podfile.lock') }}
restore-keys: ${{ runner.os }}-pods-
- name: 环境信息
run: |
sw_vers
xcodebuild -version
flutter --version
- name: 编译 macOS
env:
GC_NO_PROGRESS: '1'
run: ./build.sh build --targets=mac -version=${{ needs.prepare.outputs.version }}
- uses: actions/upload-artifact@v4
with:
name: mac-zip
path: dist/mac-arm64/*.zip
if-no-files-found: error
retention-days: 5
build-win:
needs: prepare
if: needs.prepare.outputs.ok == 'true'
runs-on: windows-latest
defaults:
run:
shell: pwsh
steps:
- uses: actions/checkout@v4
with:
ref: ${{ needs.prepare.outputs.ref }}
- uses: actions/setup-dotnet@v4
with:
dotnet-version: ${{ env.DOTNET_VERSION }}
- uses: subosito/flutter-action@v2
with:
flutter-version: ${{ env.FLUTTER_VERSION }}
channel: stable
cache: true
- name: 编译 Windows(amd64 + arm64)
run: ./build.ps1 build -Version ${{ needs.prepare.outputs.version }}
- uses: actions/upload-artifact@v4
with:
name: win-zip
path: |
dist/win-amd64/*.zip
dist/win-arm64/*.zip
if-no-files-found: error
retention-days: 5
publish:
needs: [prepare, build-mac, build-win]
if: needs.prepare.outputs.ok == 'true' && needs.build-mac.result == 'success' && needs.build-win.result == 'success'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/download-artifact@v4
with:
path: artifacts
- name: 汇总产物
run: |
set -e
mkdir -p out
find artifacts -name '*.zip' -exec cp {} out/ \;
ls -lh out
- name: 生成 sha256 清单
working-directory: out
run: |
set -e
shasum -a 256 *.zip > SHA256SUMS.txt 2>/dev/null || sha256sum *.zip > SHA256SUMS.txt
cat SHA256SUMS.txt
- name: 发布 Release
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GH_REPO: ${{ github.repository }}
VER: ${{ needs.prepare.outputs.version }}
REF: ${{ needs.prepare.outputs.ref }}
ACTOR: ${{ github.event.comment.user.login }}
ISSUE: ${{ github.event.issue.number }}
run: |
set -e
cat > notes.md <<EOF
GC ${VER}
- macOS(arm64)
- Windows(amd64 / arm64)
触发人:@${ACTOR}(#${ISSUE})
构建来源:\`${REF}\`
各包 sha256 见 \`SHA256SUMS.txt\`。
> macOS 包为 ad-hoc 签名,首次打开需右键 →「打开」,或在「系统设置 → 隐私与安全性」里放行。
EOF
gh release create "$VER" out/* \
--target "$REF" \
--title "GC ${VER}" \
--notes-file notes.md
echo "https://github.com/${{ github.repository }}/releases/tag/$VER" >> "$GITHUB_STEP_SUMMARY"
report:
needs: [prepare, build-mac, build-win, publish]
if: always() && needs.prepare.outputs.ok == 'true'
runs-on: ubuntu-latest
steps:
- name: 回帖结果
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GH_REPO: ${{ github.repository }}
ISSUE: ${{ github.event.issue.number }}
VER: ${{ needs.prepare.outputs.version }}
MAC: ${{ needs.build-mac.result }}
WIN: ${{ needs.build-win.result }}
PUB: ${{ needs.publish.result }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
run: |
set -e
REPO="${{ github.repository }}"
line() {
case "$2" in
success) echo "- $1:✅ 成功" ;;
skipped) echo "- $1:⏭ 跳过" ;;
cancelled) echo "- $1:⛔ 已取消" ;;
*) echo "- $1:❌ 失败" ;;
esac
}
if [ "$PUB" = "success" ]; then
HEADLINE="✅ **已发布 \`${VER}\`**"
elif [ "$MAC" = "success" ] || [ "$WIN" = "success" ]; then
HEADLINE="⚠️ **编译完成但未发布 \`${VER}\`**(需要两个平台都成功才会发 Release)"
else
HEADLINE="❌ **\`${VER}\` 编译失败**"
fi
{
echo "$HEADLINE"
echo
line "macOS" "$MAC"
line "Windows" "$WIN"
line "发布" "$PUB"
echo
if [ "$PUB" = "success" ]; then
echo "- Release:https://github.com/${REPO}/releases/tag/${VER}"
else
echo "- 日志:${RUN_URL}"
fi
} > result.md
gh issue comment "$ISSUE" --body-file result.md
+1 -2
View File
@@ -42,7 +42,7 @@ jobs:
build-mac:
needs: meta
runs-on: macos-14
runs-on: macos-latest
steps:
- uses: actions/checkout@v4
@@ -59,7 +59,6 @@ jobs:
- name: 编译 macOS
env:
GC_TARGETS: mac
GC_NO_CODESIGN: '1'
GC_NO_PROGRESS: '1'
run: ./build.sh build --targets=mac
+3
View File
@@ -68,3 +68,6 @@ courseware/
# 工具链临时备份
buildsh/cross/*.cmake.bak
# Gradle 全局缓存(不是项目文件)
.gradle-home/
+72
View File
@@ -264,3 +264,75 @@ mingw-w64 14.0.0_3 携带 GCC 16.2,与 Flutter 插件(flutter_inappwebview_w
### 修正(19:17)
- 夜间构建 tag 改为 **`nightly`**(concurrency 组 `release-nightly`);
`@build-bot` 手动触发仍是 **`ip-prerelease`**(组 `release-ip-prerelease`)。两个 tag 互不覆盖。
## 用户系统重做(20:30)
分支 `feat/user-system`,提交 ecb71ad。GitHub 直接推 main,XHGit 开 PR #39。
### 存储
- `.GC/user/<用户名>/pw.yaml`:username / pw_hash(sha512+salt) / points / last_sign_in / consecutive_days / theme_color / theme_paid / theme_paid_at
- `.GC/user/user.yaml`:username + session_token,后端启动自动登录(前端不需要自己找 .GC)
- 旧 `.GC/user/<用户名>.yaml` 启动时自动迁移
### 关键实现
- 验证码:`_captchas` 内存字典,算术题 5 分钟、一次性(TryRemove)
- 签到奖励:1-6:10 / 7:30 / 8-13:15 / 14:40 / 15-20:20 / 21:50 / 22-27:25 / 28:60 / 29:40 / 30:100
- 主题色:ThemeCost() 服务端算价(默认蓝 0 / 预置 50 / 其它 150);1 小时内换色退 floor(theme_paid*0.8)
- 前端:GcPalette.apply('#hex') 应用用户主题色;人品值纯客户端随机,不限次
### 踩坑
- `flutter build macos` 没有 --no-codesign(iOS 才有),已从 flutter.sh 与两个 workflow 移除
- `GcColors.appBg` 是 getter,不能放进 const Widget
- CaptchaInfo 在 api_client.dart,user_page 需要单独 import
## 删百宝箱 + 设置页去主题色(20:47,提交 38781c9)
- 删除 `pages/treasure.dart`、侧栏 `nav.treasure` 入口、`pages.dart` 导出、i18n 的 treasure.* 键
- 侧栏索引变化:user 从 6 → 5(download=2 / settings=3 不受影响,home.dart 里的 goTo 无需改)
- `settings.dart`:删掉主题色色板、自定义颜色对话、`_accentSwatch` / `_customAccentChip` / `_pickCustomAccent` / `_applyAccent`,以及 i18n 的 set.accent.*
- 强调色唯一来源改为用户账号:`controller._applySettings` 不再用 `settings.accentColor`;
启动 `_applyUserTheme()` 拉 `/api/user/me` 上色;退出登录回落 `GcPalette.defaultAccent`
- 注意:后端 SettingsInfo 仍保留 accentColor 字段(未删,避免破坏旧配置与 API 兼容)
## 模型回退 Avalonia + 积分计费改造(21:05–21:35)
### 1. 模型从 Flutter 回退 Avalonia(方案 B)
- 恢复源:5b62897(Flutter 重写前最后的 Avalonia 模型版本)→ `model/_sdk`、5 个模型的 `src/`、`GC-DRAW/PlayerWindow.cs`、`ModelHost.cs`、`AvaloniaHost.cs`
- `FlutterShell.cs`:主线程跑 Avalonia 事件循环(`uiHost.RunOnCurrentThread()`),修复 1.1.1 的 AppKit 主线程崩溃
- `BackendServer.cs`:`/api/models/{id}/launch` 走 `host.LaunchAsync(package)` 开 Avalonia 窗口
- `GC.Core.csproj` 重新引用 Avalonia/MVVM/GC.ModelSdk;`Directory.Build.props` 加 AvaloniaVersion
- 前端清理死代码:删 `pages/model_view.dart` + `lib/models/` 12 个 Flutter 模型文件(保留 user.dart),controller 删 `activeModelId/openModel/closeModel`
- GC.sln 全量编译通过;flutter analyze 0 error
### 2. 积分精确到 0.01
- `UserRecord.Points/ThemePaid`:int → decimal;pw.yaml 用 `ToString("0.##")` 写,decimal.TryParse 读(兼容旧整数)
- 主题色退款改 `Math.Floor(paid * 0.8 * 100) / 100` 保 2 位
- 前端 `points/themePaid` int → double,新增顶层 `formatPoints()`(整数不带小数、去尾零)
### 3. 人品值 / 二选一 后端计费(原先前端本地随机免费)
- pw.yaml 新增 `fortune_date/fortune_count/pick_date/pick_count`(UTC 日期跨天清零)
- 阶梯(按当日已付费次数):免费1次 → 0.1×5 → 0.2×5 → 0.5×15 → 1.0 起;二选一免费1次 → 0.5/次
- 端点 `POST /api/user/fortune`、`POST /api/user/pick`(服务端随机数);FortuneComment 评语后端生成
- 前端 `_rollFortune/_pickRandom` 改走 API,需登录,toast 显示本次消耗
### 端到端验证(GC_UI_PORT=18999)
- 注册→签到(10分)→连摇27次:费用 0/0.1×5/0.2×5/0.5×15/1.0,余额始终精确到 0.01,10 分花到 0
- 二选一首免、余额不足报「积分不足,本次需要 0.5 积分」(400)
- 重启进程后 user.yaml 自动登录 + 当日计数持久化生效;测试账号 billtest 已删
### 提交与推送(21:50,cfd6809)
- 单提交 57 文件(含 RELEASE-1.1.2.md 与工作日志),同时推:github → main、origin2(xhmcl) → feat/user-system(PR #39)
## 连接稳定性 + 签到日历日修复(11-22 07:30,用户反馈两项)
1. 「有时无法连接后端」根因:_send 连接失败直接抛错,运行中从不 rediscover/重试(睡眠唤醒断连、后端换端口后必现)
- 修:GET 连接失败自动 rediscover + 重试 1 次;POST 不自动重试(防签到/扣积分重复提交)
- 启动重试 5 次(31s) → 10 次、间隔封顶 8s(约 70s)
2. 签到用 DateTime.UtcNow.Date → 东八区早上 8 点才算新一天,7 点前可同日签到两次
- 修:UserService 4 处 + UserPayload 1 处改 DateTime.Today(本地日历日);人品值/二选一跨天计数一并修
- 实测(本地 07:33 / UTC 07-21):last_sign_in=2026-11-22,重复签到被拒,人品值按本地日重置
## build-bot version 参数 + macOS 提速 + XHGit PR #40(11-22 08:00)
- 需求:`@build-bot build mac version=1.1.3` 编指定版本;mac 大小写不敏感;提速 Mac 编译
- build-bot.yml:prepare 解析 `version=x.y.z`(grep -oiE,大小写不敏感)→ 覆盖 props 版本 → 透传给 build.sh/build.ps1;回帖和 Release notes 显示版本
- 提速:两个工作流 mac job 都加 actions/cache(NuGet packages + CocoaPods Pods/Caches),runner 从 macos-latest 固定 macos-14 原生 arm64
- 脚本层已有并行(Flutter ‖ dotnet publish)+ dt_tool 缓存 + _trash,未重复改
- 提交 8b4cabb(分支 ci/buildbot-mac-speed),推 origin2 后经 Gitea API 创建 PR #40 → main(mergeable=true)
- PR 创建方式:git credential fill 拿账号密码 → curl -u basic auth POST /api/v1/repos/Morris/GC/pulls(token 方式 401,basic auth 201)
@@ -14,6 +14,10 @@
<Nullable>enable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
<MvvmVersion>8.2.2</MvvmVersion>
<!-- 模型窗口仍由 Avalonia 承载(模型契约返回 Avalonia Control),
所有界面由 Avalonia 承载。Avalonia.BuildServices 的遥测会向用户目录写日志,
在只读目录 / CI 里会直接让编译失败,build.sh / build.ps1 已默认关闭。 -->
<AvaloniaVersion>11.3.9</AvaloniaVersion>
<Version>1.1.2</Version>
<Company>Morris</Company>
<Product>GC</Product>
File renamed without changes.
@@ -20,7 +20,6 @@
<ItemGroup>
<ProjectReference Include="..\GC\src\GC.Core.csproj" />
<ProjectReference Include="..\GC-DOWNLOAD\GC-DOWNLOAD.csproj" />
<ProjectReference Include="..\GC-UI\backend\GC.UI.Server\GC.UI.Server.csproj" />
</ItemGroup>
</Project>
+10 -6
View File
@@ -1,4 +1,6 @@
using System;
using Avalonia;
using Avalonia.WebView.Desktop;
using GC.Services;
using GC.Download;
@@ -20,11 +22,13 @@ internal static class Program
// 上次下载的启动器新版,到这次启动才应用
if (DownloadModuleHost.Factory.TryApplyPending(paths)) return;
// 界面只有 Flutter 一套(内置 Avalonia 界面已移除)。
if (FlutterShell.TryRun(args)) return;
// 找不到前端:给出明确提示后退出,不要静默启动一个没有界面的后端进程。
FlutterShell.ReportMissingUi();
Environment.Exit(1);
// 所有界面统一由 Avalonia 承载(主窗口 / 模型窗口 / 课件),不再依赖 Flutter。
BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
}
public static AppBuilder BuildAvaloniaApp()
=> AppBuilder.Configure<App>()
.UsePlatformDetect()
.UseDesktopWebView()
.LogToTrace();
}
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
+642
View File
@@ -0,0 +1,642 @@
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using Avalonia;
using Avalonia.Animation;
using Avalonia.Animation.Easings;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Layout;
using Avalonia.Media;
using Shapes = Avalonia.Controls.Shapes;
using Avalonia.VisualTree;
using GC.Models;
using GC.Services;
namespace GC.Views;
/// <summary>
/// 模型窗口:**只做窗口宿主**。
/// 内容完全来自模型程序集(<see cref="LoadedModel.View"/>),启动器不渲染任何东西。
/// 快捷键:Esc 关闭窗口,F11 全屏。
/// </summary>
public sealed class PlayerWindow : Window
{
private LoadedModel? _model;
private bool _closing;
private Button? _maximizeButton;
private Border? _frame;
private TextBlock? _titleText;
private Border? _titleBar;
private readonly List<Button> _titleButtons = new();
private readonly List<Shapes.Path> _titleGlyphs = new();
private Shapes.Path? _maximizeGlyph;
private Shapes.Path? _restoreGlyph;
private string _maxMaxPath = "";
private string _maxRestorePath = "";
private Button? _helpButton;
/// <summary>基准尺寸(1240×820 时的标题栏高度与按钮尺寸)。</summary>
private const double BaseWidth = 1240;
private const double BaseTitleBarHeight = 34;
private const double BaseButtonWidth = 38;
private const double BaseButtonHeight = 28;
private const double BaseTitleFont = 11.5;
private const double BaseHelpFont = 11.5;
public PlayerWindow(ModelPackage package, LoadedModel model)
{
_model = model;
Title = package.LocalizedName;
Width = 1240;
Height = 820;
MinWidth = 1000;
MinHeight = 680;
Background = Brushes.Transparent;
TransparencyLevelHint = new[] { WindowTransparencyLevel.Transparent };
WindowStartupLocation = WindowStartupLocation.CenterOwner;
// 与启动器一致:去掉系统标题栏,自己做一个极简顶栏(否则 Esc 之外无法关闭)
SystemDecorations = Avalonia.Controls.SystemDecorations.None;
// 标题栏配色来自模型清单,跟随模型自己的界面风格:
// 地球模型是深色舞台,比例尺计算器是浅色卡片,两者不能共用一套深色。
var chrome = package.Manifest.Chrome;
var barBg = ParseColor(chrome?.TitleBar, "#0C1828");
var barBorder = ParseColor(chrome?.TitleBorder, "#1B2740");
var barText = ParseColor(chrome?.TitleText, "#EAF2FF");
var btnText = ParseColor(chrome?.Button, "#9FB4D4");
var frameBg = ParseColor(chrome?.Frame, "#0A1524");
var titleText = new TextBlock
{
Text = package.LocalizedName,
Foreground = new SolidColorBrush(barText),
FontSize = 11.5,
Margin = new Thickness(14, 0, 0, 0),
VerticalAlignment = VerticalAlignment.Center,
[Grid.ColumnProperty] = 0
};
_titleText = titleText;
var helpButton = new Button
{
Content = IsEnglish() ? "How to use?" : "如何使用?",
Height = 26,
Padding = new Thickness(12, 0),
Background = Brushes.Transparent,
Foreground = new SolidColorBrush(btnText),
BorderThickness = new Thickness(0),
FontSize = 11.5,
CornerRadius = new CornerRadius(7),
Margin = new Thickness(0, 0, 6, 0),
HorizontalContentAlignment = HorizontalAlignment.Center,
VerticalContentAlignment = VerticalAlignment.Center,
Cursor = new Cursor(StandardCursorType.Hand),
[Grid.ColumnProperty] = 1
};
helpButton.Click += (_, _) => ShowHelp(package, barBg, barBorder, barText, btnText, frameBg);
// 标题栏三键:最小化 / 最大化 / 关闭 —— 卡通画风。
// 每颗按钮 = 彩色实心圆底 + 粗圆头描边图标,像一颗小糖豆。
(Button Btn, Shapes.Path Icon) MakeBadge(int column, string iconPath)
{
// 纯矢量图标,没有彩色圆圈
var icon = new Shapes.Path
{
Data = Geometry.Parse(iconPath),
Stroke = new SolidColorBrush(btnText),
StrokeThickness = 1.5,
StrokeLineCap = PenLineCap.Round,
StrokeJoin = PenLineJoin.Round,
Fill = null,
Stretch = Stretch.None,
Width = 10,
Height = 10,
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center
};
var layer = new Grid
{
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center
};
layer.Children.Add(icon);
var b = new Button
{
Width = 38,
Height = 28,
Background = Brushes.Transparent,
BorderThickness = new Thickness(0),
CornerRadius = new CornerRadius(9),
Padding = new Thickness(0),
Margin = new Thickness(2, 0, 0, 0),
Content = layer,
HorizontalContentAlignment = HorizontalAlignment.Center,
VerticalContentAlignment = VerticalAlignment.Center,
Cursor = new Cursor(StandardCursorType.Hand),
[Grid.ColumnProperty] = column
};
var hoverBg = IsLight(barBg)
? new SolidColorBrush(Color.Parse("#EEF1F7"))
: new SolidColorBrush(Color.Parse("#1E2C46"));
var isCloseBtn = column == 4;
b.PointerEntered += (_, _) =>
{
b.Background = hoverBg;
icon.Stroke = new SolidColorBrush(isCloseBtn ? Colors.White
: IsLight(barBg) ? Color.Parse("#111A2E") : Colors.White);
};
b.PointerExited += (_, _) =>
{
b.Background = Brushes.Transparent;
icon.Stroke = new SolidColorBrush(btnText);
};
b.Classes.Add("model-titlebtn");
_titleButtons.Add(b);
_titleGlyphs.Add(icon);
return (b, icon);
}
// 卡通配色:暖黄 / 薄荷绿 / 珊瑚红
var minBadge = MakeBadge(2, "M1.5,5 L8.5,5");
var maxBadge = MakeBadge(3, "M2.2,2.2 L7.8,2.2 L7.8,7.8 L2.2,7.8 Z");
var closeBadge = MakeBadge(4, "M2,2 L8,8 M8,2 L2,8");
var minimizeButton = minBadge.Btn;
var maximizeButton = maxBadge.Btn;
var closeButton = closeBadge.Btn;
minimizeButton.Click += (_, _) => WindowState = WindowState.Minimized;
maximizeButton.Click += (_, _) => ToggleMaximize();
closeButton.Click += (_, _) => _ = CloseWithAnimationAsync();
_maximizeGlyph = maxBadge.Icon;
_restoreGlyph = maxBadge.Icon;
_maxRestorePath = "M2.6,3.6 L7.4,3.6 L7.4,8.4 L2.6,8.4 Z M2.6,3.6 L2.6,1.6 L7.4,1.6 L7.4,6.4";
_maxMaxPath = "M2.2,2.2 L7.8,2.2 L7.8,7.8 L2.2,7.8 Z";
var titleBar = new Border
{
Height = 34,
Background = new SolidColorBrush(barBg),
BorderBrush = new SolidColorBrush(barBorder),
BorderThickness = new Thickness(0, 0, 0, 1),
Child = new Grid
{
ColumnDefinitions = new ColumnDefinitions("*,Auto,Auto,Auto,Auto,Auto"),
Margin = new Thickness(0, 0, 10, 0),
Children = { titleText, helpButton, minimizeButton, maximizeButton, closeButton }
}
};
titleBar.PointerPressed += OnTitleBarPointerPressed;
// 双击标题栏 = 最大化 / 还原(与系统标题栏一致)
titleBar.DoubleTapped += (_, e) =>
{
if (e.Source is Button) return;
ToggleMaximize();
};
_maximizeButton = maximizeButton;
_titleBar = titleBar;
_helpButton = helpButton;
_titleButtons.Add(minimizeButton);
_titleButtons.Add(maximizeButton);
_titleButtons.Add(closeButton);
var dock = new DockPanel { LastChildFill = true };
DockPanel.SetDock(titleBar, Dock.Top);
dock.Children.Add(titleBar);
dock.Children.Add(model.View);
Content = new Border
{
CornerRadius = new CornerRadius(16),
Background = new SolidColorBrush(frameBg),
ClipToBounds = true,
Child = dock
};
_frame = (Border)Content;
// 最大化 / 还原时同步圆角与按钮图标
PropertyChanged += (_, e) =>
{
if (e.Property == WindowStateProperty) UpdateMaximizeVisual();
};
// 窗口随心拉大 / 拉小时,标题栏文字与按钮同比缩放。
// 同时监听 Bounds 属性(不只是 SizeChanged),保证最大化/还原也立刻生效。
SizeChanged += (_, _) => ApplyChromeScale();
PropertyChanged += (_, e) =>
{
if (e.Property == BoundsProperty) ApplyChromeScale();
};
ApplyChromeScale();
KeyDown += OnKeyDown;
Closed += OnClosed;
}
/// <summary>
/// 让标题栏的文字与按钮尺寸跟随窗口大小。
/// 以 1240px 宽为基准线性缩放,限制在 0.85–1.9 倍,
/// 避免最大化到 4K 时按钮大得离谱、缩到最小又点不中。
/// </summary>
private void ApplyChromeScale()
{
if (Bounds.Width < 100) return;
var scale = Math.Clamp(Bounds.Width / BaseWidth, 0.85, 1.9);
if (_titleBar != null) _titleBar.Height = Math.Round(BaseTitleBarHeight * scale);
foreach (var b in _titleButtons)
{
b.Width = Math.Round(BaseButtonWidth * scale);
b.Height = Math.Round(BaseButtonHeight * scale);
b.FontSize = Math.Round(13 * scale, 1);
b.CornerRadius = new CornerRadius(Math.Round(7 * scale, 1));
}
if (_helpButton != null)
{
_helpButton.Height = Math.Round(26 * scale);
_helpButton.FontSize = Math.Round(BaseHelpFont * scale, 1);
_helpButton.Padding = new Thickness(Math.Round(12 * scale), 0);
_helpButton.CornerRadius = new CornerRadius(Math.Round(7 * scale, 1));
}
foreach (var g in _titleGlyphs)
{
g.Width = Math.Round(10 * scale, 1);
g.Height = Math.Round(10 * scale, 1);
g.StrokeThickness = Math.Round(1.5 * scale, 2);
}
if (_titleText != null)
{
_titleText.FontSize = Math.Round(BaseTitleFont * scale, 1);
_titleText.Margin = new Thickness(Math.Round(14 * scale), 0, 0, 0);
}
}
/// <summary>判断颜色是否属于浅色系(用于决定悬停用深色还是浅色)。</summary>
private static bool IsLight(Color c)
{
// 相对亮度(sRGB 近似)
var lum = (0.299 * c.R + 0.587 * c.G + 0.114 * c.B) / 255.0;
return lum > 0.6;
}
private void ToggleMaximize()
{
WindowState = WindowState == WindowState.Maximized
? WindowState.Normal
: WindowState.Maximized;
}
private void UpdateMaximizeVisual()
{
var max = WindowState == WindowState.Maximized || WindowState == WindowState.FullScreen;
if (_maximizeGlyph != null)
{
// 只换 Data,不换控件对象(换对象会触发 "already has a parent")
_maximizeGlyph.Data = Geometry.Parse(max ? _maxRestorePath : _maxMaxPath);
}
if (_maximizeButton != null)
{
Avalonia.Controls.ToolTip.SetTip(_maximizeButton, max
? (IsEnglish() ? "Restore" : "还原")
: (IsEnglish() ? "Maximize" : "最大化"));
}
// 最大化后同样保留圆角(用户要求:任何状态都要圆角)
if (_frame != null) _frame.CornerRadius = new CornerRadius(16);
}
private static Color ParseColor(string? hex, string fallback)
{
if (!string.IsNullOrWhiteSpace(hex))
{
try { return Color.Parse(hex!); }
catch { /* 模型写错颜色时退回默认 */ }
}
return Color.Parse(fallback);
}
private static bool IsEnglish() => L.I.Language.StartsWith("en", StringComparison.OrdinalIgnoreCase);
/// <summary>
/// 「如何使用?」:读取模型自带数据目录里的 help.json(中英双语),
/// 用与标题栏一致的配色弹出一个独立小窗。说明内容完全由模型提供,启动器不内置文案。
/// </summary>
private void ShowHelp(ModelPackage package, Color barBg, Color barBorder, Color barText,
Color btnText, Color frameBg)
{
var lang = IsEnglish() ? "en" : "zh-CN";
var file = Path.Combine(package.DataDirectory, "help.json");
string title = IsEnglish() ? "How to use" : "如何使用";
// 分节内容:每节一个标题 + 若干条说明;兼容旧的扁平 lines 格式
var sections = new List<(string Heading, List<string> Lines)>();
if (File.Exists(file))
{
try
{
using var doc = JsonDocument.Parse(File.ReadAllText(file));
var root = doc.RootElement;
var node = root.TryGetProperty(lang, out var exact) ? exact
: root.TryGetProperty("zh-CN", out var zh) ? zh : root;
if (node.TryGetProperty("title", out var t)) title = t.GetString() ?? title;
if (node.TryGetProperty("sections", out var arr) && arr.ValueKind == JsonValueKind.Array)
{
foreach (var sec in arr.EnumerateArray())
{
var heading = sec.TryGetProperty("h", out var h) ? h.GetString() ?? "" : "";
var items = new List<string>();
if (sec.TryGetProperty("lines", out var ls) && ls.ValueKind == JsonValueKind.Array)
foreach (var item in ls.EnumerateArray())
if (item.ValueKind == JsonValueKind.String) items.Add(item.GetString() ?? "");
if (items.Count > 0) sections.Add((heading, items));
}
}
else if (node.TryGetProperty("lines", out var flat) && flat.ValueKind == JsonValueKind.Array)
{
var items = new List<string>();
foreach (var item in flat.EnumerateArray())
if (item.ValueKind == JsonValueKind.String) items.Add(item.GetString() ?? "");
if (items.Count > 0) sections.Add(("", items));
}
}
catch (Exception ex)
{
Console.Error.WriteLine($"读取模型帮助失败 {file}: {ex.Message}");
}
}
if (sections.Count == 0)
sections.Add(("", new List<string>
{
IsEnglish() ? "This model has no usage notes yet." : "该模型暂未提供使用说明。"
}));
var body = new StackPanel { Spacing = 6 };
foreach (var (heading, items) in sections)
{
if (!string.IsNullOrWhiteSpace(heading))
body.Children.Add(new TextBlock
{
Text = heading,
Foreground = new SolidColorBrush(barText),
FontSize = 13.5,
FontWeight = FontWeight.SemiBold,
Margin = new Thickness(0, 12, 0, 2)
});
foreach (var line in items)
body.Children.Add(new TextBlock
{
Text = "• " + line,
Foreground = new SolidColorBrush(btnText),
FontSize = 12.5,
TextWrapping = TextWrapping.Wrap,
LineHeight = 19
});
}
// ── 帮助窗口自建标题栏(带 ✕),与模型窗口同款配色 ──
// 纯矢量图标,无彩色圆底(与三个窗口按钮保持一致)
var helpCross = new Shapes.Path
{
Data = Geometry.Parse("M2,2 L8,8 M8,2 L2,8"),
Stroke = new SolidColorBrush(btnText),
StrokeThickness = 1.5,
StrokeLineCap = PenLineCap.Round,
Fill = null,
Stretch = Stretch.None,
Width = 10, Height = 10,
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center
};
var helpClose = new Button
{
Content = helpCross,
Width = 34,
Height = 26,
Background = Brushes.Transparent,
BorderThickness = new Thickness(0),
CornerRadius = new CornerRadius(9),
Padding = new Thickness(0),
Margin = new Thickness(6, 0, 0, 0),
HorizontalContentAlignment = HorizontalAlignment.Center,
VerticalContentAlignment = VerticalAlignment.Center,
Cursor = new Cursor(StandardCursorType.Hand)
};
helpClose.PointerEntered += (_, _) =>
{
helpClose.Background = new SolidColorBrush(IsLight(frameBg)
? Color.Parse("#EEF1F7") : Color.Parse("#1E2C46"));
helpCross.Stroke = new SolidColorBrush(Colors.White);
};
helpClose.PointerExited += (_, _) =>
{
helpClose.Background = Brushes.Transparent;
helpCross.Stroke = new SolidColorBrush(btnText);
};
var helpTitle = new TextBlock
{
Text = title,
Foreground = new SolidColorBrush(barText),
FontSize = 16,
FontWeight = FontWeight.SemiBold,
VerticalAlignment = VerticalAlignment.Center
};
var helpBarGrid = new Grid
{
ColumnDefinitions = new ColumnDefinitions("*,Auto"),
Margin = new Thickness(22, 0, 14, 0)
};
helpBarGrid.Children.Add(helpTitle);
Grid.SetColumn(helpClose, 1);
helpBarGrid.Children.Add(helpClose);
var helpTitleBar = new Border
{
Height = 48,
Background = new SolidColorBrush(barBg),
BorderBrush = new SolidColorBrush(barBorder),
BorderThickness = new Thickness(0, 0, 0, 1),
Child = helpBarGrid
};
helpTitleBar.PointerPressed += (_, e) =>
{
if (e.GetCurrentPoint(helpTitleBar).Properties.IsLeftButtonPressed)
helpClose.FindAncestorOfType<Window>()?.BeginMoveDrag(e);
};
// ── 底部固定操作条:无论正文多长,「知道了」始终可见 ──
var ok = new Button
{
Content = IsEnglish() ? "Got it" : "知道了",
HorizontalAlignment = HorizontalAlignment.Right,
Padding = new Thickness(20, 8),
Background = new SolidColorBrush(Color.Parse("#2F6BFF")),
Foreground = new SolidColorBrush(Colors.White),
BorderThickness = new Thickness(0),
CornerRadius = new CornerRadius(8),
Cursor = new Cursor(StandardCursorType.Hand)
};
var footer = new Border
{
Padding = new Thickness(24, 10, 24, 14),
BorderBrush = new SolidColorBrush(barBorder),
BorderThickness = new Thickness(0, 1, 0, 0),
Child = ok
};
// 标题栏(顶) + 正文(中,滚动) + 操作条(底,固定)
var rootPanel = new DockPanel { LastChildFill = true };
DockPanel.SetDock(helpTitleBar, Dock.Top);
rootPanel.Children.Add(helpTitleBar);
DockPanel.SetDock(footer, Dock.Bottom);
rootPanel.Children.Add(footer);
var scroll = new ScrollViewer
{
Content = new Border
{
Margin = new Thickness(24, 14, 24, 10),
Child = body
},
VerticalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto,
HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Disabled
};
rootPanel.Children.Add(scroll);
var win = new Window
{
Title = title,
Width = 660,
Height = Math.Min(760, 230 + sections.Sum(s => s.Lines.Count * 24 + 40)),
MinWidth = 480,
MinHeight = 320,
Background = Brushes.Transparent,
TransparencyLevelHint = new[] { WindowTransparencyLevel.Transparent },
SystemDecorations = SystemDecorations.None,
WindowStartupLocation = WindowStartupLocation.CenterOwner,
Content = new Border
{
CornerRadius = new CornerRadius(16),
Background = new SolidColorBrush(frameBg),
BorderBrush = new SolidColorBrush(barBorder),
BorderThickness = new Thickness(1),
ClipToBounds = true,
Child = rootPanel
}
};
ok.Click += (_, _) => win.Close();
helpClose.Click += (_, _) => win.Close();
win.Show(this);
}
private void OnTitleBarPointerPressed(object? sender, PointerPressedEventArgs e)
{
if (e.GetCurrentPoint(this).Properties.IsLeftButtonPressed)
BeginMoveDrag(e);
}
private void OnKeyDown(object? sender, KeyEventArgs e)
{
switch (e.Key)
{
case Key.Escape:
_ = CloseWithAnimationAsync();
e.Handled = true;
break;
case Key.F11:
WindowState = WindowState == WindowState.FullScreen
? WindowState.Normal
: WindowState.FullScreen;
e.Handled = true;
break;
}
}
/// <summary>
/// 关闭动画:淡出 + 轻微缩小,动画结束后再真正关闭窗口。
/// 与主窗口的关闭动画保持同一节奏(180ms)。
/// </summary>
private async Task CloseWithAnimationAsync()
{
if (_closing) return;
_closing = true;
Transitions = new Transitions
{
new DoubleTransition
{
Property = OpacityProperty,
Duration = TimeSpan.FromMilliseconds(180),
Easing = new CubicEaseIn()
}
};
Opacity = 0;
await Task.Delay(190);
Close();
}
private void OnClosed(object? sender, EventArgs e)
{
Content = null;
_model?.Dispose();
_model = null;
}
}
/// <summary>模型加载失败时显示的提示窗口(不含任何渲染逻辑)。</summary>
public sealed class ModelErrorWindow : Window
{
public ModelErrorWindow(string title, string message)
{
Title = title;
Width = 560;
Height = 340;
Background = Brushes.Transparent;
TransparencyLevelHint = new[] { WindowTransparencyLevel.Transparent };
WindowStartupLocation = WindowStartupLocation.CenterOwner;
var lines = new List<Control>
{
new TextBlock
{
Text = title,
Foreground = new SolidColorBrush(Color.Parse("#F2F6FF")),
FontSize = 16,
FontWeight = FontWeight.SemiBold
},
new TextBlock
{
Text = message,
Foreground = new SolidColorBrush(Color.Parse("#8CA0C4")),
FontSize = 12,
TextWrapping = TextWrapping.Wrap
},
new Button
{
Content = "确定",
HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Right,
Padding = new Thickness(18, 6)
}
};
var panel = new StackPanel
{
Margin = new Thickness(24),
Spacing = 14
};
foreach (var line in lines) panel.Children.Add(line);
if (lines[^1] is Button ok) ok.Click += (_, _) => Close();
Content = new Border
{
CornerRadius = new CornerRadius(12),
Background = new SolidColorBrush(Color.Parse("#0B1226")),
Child = panel
};
}
}
@@ -502,7 +502,7 @@ internal sealed class Applier
/// <summary>
/// 把 <paramref name="stage"/> 的内容替换进 <paramref name="installDir"/>。
///
/// 发布包是「整目录」(启动器 + 后端运行时 + Flutter 前端资源),只搬一个 exe 会留下
/// 发布包是「整目录」(启动器 + 后端运行时 + 课件资源),只搬一个 exe 会留下
/// 旧后端 / 旧界面,所以这里按目录整体替换:
/// 1. 安装目录里「新版没有」的条目 → 移到 backup(旧版本残留,如上一版的旧文件名);
/// 2. 与新版同名的条目 → 先移到 backup,再把新版放进来(覆盖正在被占用的文件会失败,
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
+200
View File
@@ -0,0 +1,200 @@
# GC 多语言完整版统一规范
本文件定义 6 种语言重写版必须遵守的**结构**、**功能**、**模型算法**契约。
源码仓库根目录的 `GC/`、`GC-DOWNLOAD/`、`GC-SAVEDOG/`、`model/` 保持不动。
## 1. 目录结构(6 语言一致)
```
GC-<语言>/
README.md 说明 + 构建方式 + 与原仓库的对应关系
build.sh 一键编译脚本,产出 gcctl 可执行文件
src/
core/ 启动器核心(路径/设置/哈希/JSON/版本/模型扫描/安全/日志)
models/ 5 个教学模型(与 model/ 下模型一一对应)
main.<ext> 统一 CLI 入口,单进程承载全部功能(禁止前后端分离)
gcctl 编译产物(可执行文件)
```
语言与扩展名:C++ → `.cpp`,Rust → `.rs`,Go → `.go`,Java → `.java`,Zig → `.zig`,C → `.c`。
## 2. 功能清单(6 语言一致)
### 2.1 启动器核心 core
| 功能 | 命令 | 行为契约 |
|---|---|---|
| 文件哈希 | `hash-file <path>` | SHA-256 小写十六进制 |
| 目录指纹 | `hash-dir <path>` | 相对路径 `/` 分隔,按 ordinal 升序,拼接 `<path>\0<sha256>\n` 后取 SHA-256;跳过隐藏文件、`bin/`、`obj/`、`*.user` |
| 规范化 JSON | `canonical <file\|->` | 对象键递归升序、无空白、UTF-8、非 ASCII 不转义、移除根级 `signature` |
| 版本规整 | `version-normalize <tag>` | 去 `GCL-/GC-/release-/v/V` 前缀,只留开头数字与点 |
| 版本比较 | `version-compare <a> <b>` | 输出 -1 / 0 / 1 |
| 路径布局 | `paths [root]` | 打印 `.GC/{bin,config,model,cache,update,safedog,logs}` 与 `config/settings.json` |
| 默认设置 | `settings-default` | 输出默认 `settings.json`(language=auto, theme=light, fps=120, mem=2048, source=xhmcl) |
| 模型扫描 | `model-scan <root>` | 扫描 `<root>/<id>/<id>.json`,按 id 排序,输出 `id\tversion\tname\tsize\tdir` |
| 安全路径 | `safezip-name <name>` | 拒绝绝对路径、`../`、盘符、UNC、空名,输出 OK/REJECT |
| 人类体积 | `human-size <bytes>` | B/KB/MB/GB,`1536 → 1.5 KB` |
| 自检 | `selftest` | 运行所有内置断言,全部 PASS 退出码 0 |
### 2.2 教学模型 models(功能一致,下载可不一致)
| 模型 | 对应原仓库 | 必须实现的功能(命令) |
|---|---|---|
| 比例尺 | `model/scale-calculator` | `model scale solve <mode> <mapCm> <realCm> <N>`(mode=real/map/scale)、`model scale human <cm>`、`model scale segment <N> <pxPerCm> <targetPx>`、`model scale grade <N>`、`model scale spectrum <N>`、`model scale quiz <seed>`、`model scale check <answer> <expect>` |
| 等高线 | `model/contour-map` | `model contour build <kind\|landform> [size]`(生成高度场)、`model contour sample <kind> <u> <v>`、`model contour levels <kind>`、`model contour extract <kind> <level>`(Marching Squares 折线数)、`model contour classify <kind> <u> <v>`、`model contour color <height>`、`model contour slope <kind> <u> <v>` |
| 地球自转 | `model/earth-rotation` | `model rotation subsolar <orbitDeg> <tiltDeg>`(太阳直射纬度)、`model rotation date <orbitDeg>`、`model rotation angle <spinDeg> <orbitDeg>` |
| 地球公转 | `model/earth-revolution` | `model revolution subsolar <orbitDeg>`、`model revolution season <orbitDeg>`(最近节气)、`model revolution step <spinDeg> <orbitDeg> <dt> <speed>` |
| 地理 | `model/earth-geography` | `model geo zones`(五带边界)、`model geo declination <lat>`(五带判定)、`model geo latlon <lat> <lon>`(单位向量) |
**模型算法必须与 C# 源码逐字等价**(见 SPEC 附录的公式)。
## 3. 一致性硬性要求
1. **结构一致**:6 个目录的 `src/core`、`src/models`、`main`、`build.sh` 一一对应。
2. **功能一致**:所有 CLI 命令在 6 语言都实现;同一输入必须给出同一输出(允许浮点末位差异)。
3. **禁止前后端分离**:单进程 CLI,无 HTTP 服务、无 Flutter 前端;模型功能直接链接进主程序。
4. **下载可不一致**:`model download` 允许各语言用各自 HTTP 实现,不作为一致性校验项。
5. **模型功能一致**:5 个模型的算法与输出在 6 语言完全一致。
## 4. 统一自检向量(必须全部 PASS)
```
hash-file("hello") = 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
hash-dir(a.txt="hello") = ed54360a4d7244bfcde6dca611fd00dbfbdf508c47ad104b711f8429a6d2604d
version-normalize("GCL-v1.0.6-beta") = 1.0.6
version-compare(v1.0.6, 1.0.7) = -1
canonical({"b":1,"a":"中文"}) = {"a":"中文","b":1}
safezip-name("../x") = REJECT;safezip-name("a/b.txt") = OK
human-size(1536) = 1.5 KB
scale solve(real, 3, 0, 100000) → realCm = 300000
scale human(300000) → 3 km
scale grade(100000) = large;grade(500000) = medium;grade(10000000) = small
contour levels(mountain) 含 100 的倍数;extract 返回折线数 > 0
rotation subsolar(90, 23.5) = 23.5;subsolar(0, 23.5) = 0
revolution season(90) = summerSolstice
geo declination(40) = northTemperate;declination(0) = tropics
```
## 5. 附录:模型核心公式(源自 C# 源码)
### 比例尺 ScaleMath
- `Solve`: real = mapCm*N;map = realCm/N;scale N = realCm/mapCm
- `HumanReal(cm)`: <100 → cm;<100000 → 米(cm/100);否则公里(cm/100000)
- `PickSegment`: 在 `1/2/5×10^k (k=-3..9)` 里选 `|log10(cand)-log10(ideal)|` 最小,`ideal=targetPx*N/(100*pxPerCm)`
- `Grade`: N≤100000 large;≤1000000 medium;else small
- `SpectrumPosition`: clamp((log10(N)-3)/6, 0, 1)
### 等高线 TerrainField / TerrainAnalyzer
- 山峰高度场:`h = 120 + Σ H_i*exp(-d²*1.15)`,d=((u-U)/RU,(v-V)/RV)
- 等高距:plain=5, hill=10, 其他=100
- Marching Squares:角点 h00,h10,h11,h01 组成 4bit 索引,10 种情形连线段,再按端点连通性串折线
- `Classify`: 先查 Tags 标注区,再按 slope>8.5=cliff、局部最大=peak、鞍部、横切曲率 <−0.55=ridge />0.55=valley
- `ColorForHeight`: 200m 一档,9 级固定 RGB
### 地球 CelestialView
- `SubsolarLatitude(revolution) = asin(sin(tilt°)*sin(orbit°)) * 180/π`(tilt 默认 23.5)
- 角度推进:`spin = (spin + dt*speed*60) % 360`;`orbit = (orbit + dt*speed*12) % 360`
- `DateForAngle(deg)`: `2025-01-01 + (79 + deg/360*365.2422) 天`
- 节气:0°春分 / 90°夏至 / 180°秋分 / 270°冬至
- `LatLonToUnit`: `(cosLat*sinLon, sinLat, cosLat*cosLon)`
### 地理 GeoModels
- 五带:热带 |lat|<23.5、温带 23.5≤|lat|<66.5、寒带 |lat|≥66.5
---
## 6. GUI 层规范(追加,用户要求完整图形界面)
所有 6 个语言版本必须提供**真原生图形界面**,单进程、不前后端分离。SDL2 统一图形层(用户选定)。
### 6.1 运行方式
```
./gcctl # 无参数 = 启动 GUI 主窗口(替代原 CLI 的默认 help 行为)
./gcctl gui # 显式启动 GUI
./gcctl <cli命令> # 保留全部 CLI 命令(自检、批处理仍可用)
./gcctl selftest # 自检仍为纯命令行
```
**注意**:为保持与已完成的 20 项 CLI 自检一致,`selftest` 不启动 GUI。GUI 有独立的 `gui-selftest`(可选)。
### 6.2 GUI 窗口结构(6 语言一致)
单窗口、顶部标签页切换 5 个模型 + 启动器首页:
```
┌──────────────────────────────────────────────┐
│ GC 天文教学模型 [首页][比例尺][等高线][自转][公转][地理] │ ← 标签栏
├──────────────────────────────────────────────┤
│ │
│ 模型画布 / 内容区 │ ← 用 SDL2 绘制
│ │
├──────────────────────────────────────────────┤
│ [◀][⏸/▶][▶] 速度:1x 状态栏 │ ← 控制栏(动画模型)
└──────────────────────────────────────────────┘
```
### 6.3 五个模型的 GUI 交互(完整交互,与原仓库对等)
| 标签 | 画面 | 交互 | 调用的 core/models 函数 |
|---|---|---|---|
| 首页 | 模型卡片列表 + 状态 | 点击卡片切换标签 | `ScanModels` |
| 比例尺 | 线段比例尺 + 数字/文字式 | 输入 mapCm/realCm/N,切换求解模式,实时重绘 | `ScaleSolve`, `PickSegment`, `Grade` |
| 等高线 | 高度场分层设色 + 等高线 | 切换 5 种地形/5 种地貌,鼠标悬停显示海拔与判读结果 | `TerrainField`, `ExtractContour`, `Classify` |
| 自转 | 地球球体 + 晨昏线 + 直射点 | 播放/暂停、拖动旋转、速度调节、显示赤纬 | `StepAngles`, `SubsolarLatitude` |
| 公转 | 轨道 + 四季标记 + 地球 | 播放/暂停、跳到节气、显示直射纬度 | `SubsolarLatitude`, `NearestSeason`, `DateForAngle` |
| 地理 | 经纬网 + 五带 | 鼠标悬停经纬度 → 高亮所属温度带 | `LatLonToUnit`, `Declination` |
### 6.4 各语言的 SDL2 接入
SDL2 framework 已安装到 `~/Library/Frameworks/SDL2.framework`(用户目录,未写 Homebrew)。
| 语言 | 接入方式 | 编译参数 |
|---|---|---|
| C | 直接 include | `-F "$HOME/Library/Frameworks" -framework SDL2` |
| C++ | 直接 include | 同 C |
| Zig | `@cImport` | `-F ... -framework SDL2` |
| Rust | `sdl2` crate(link framework) | `SDL2_FRAMEWORK` 环境变量 + build.rs |
| Go | cgo 直接调 SDL2 C API | `#cgo CFLAGS: -F.../Frameworks` `#cgo LDFLAGS: -framework SDL2` |
| Java | Swing(JDK 标准库,SDL2 通过 JNI 可选) | 无需 SDL2,用 Swing 实现同等 GUI |
Java 例外说明:Java 生态原生 GUI 是 Swing/AWT(JDK 自带、跨平台、零依赖),比 JNI 包 SDL2 更稳定,GUI 行为与 SDL2 版一致。
### 6.5 GUI 与 CLI 共享同一套模型算法
GUI 只负责绘制和交互,**所有计算调用 `src/models` 和 `src/core` 的同一函数**,保证 GUI 与 CLI 输出一致(例如 GUI 比例尺窗口显示的数值 == `gcctl model scale solve` 的输出)。禁止在 GUI 里另写一套算法。
### 6.6 动画
- 自转/公转用 SDL2 定时器(约 60 FPS)驱动 `StepAngles`,每帧重绘
- 播放/暂停/速度按钮控制 `speed` 参数
- 全局变量帧计数器显示在状态栏(便于自检)
### 6.7 SDL2 关键编译配置(已验证,直接复用)
SDL2 framework 已装到 `~/Library/Frameworks/SDL2.framework`,头文件软链已建:`~/.local/sdl2inc/SDL2 -> ~/Library/Frameworks/SDL2.framework/Headers`。
**已验证的 Go cgo 配置**(`sdl_probe` 通过,`SDL_Init(VIDEO)=0`):
```go
/*
#cgo CFLAGS: -I/Users/mmm/.local/sdl2inc
#cgo LDFLAGS: -F/Users/mmm/Library/Frameworks -framework SDL2 -Wl,-rpath,/Users/mmm/Library/Frameworks
#include <SDL2/SDL.h>
*/
import "C"
```
要点:
1. framework 内部头用 `SDL2/xxx.h` 互相引用,所以 include 路径必须是 `~/.local/sdl2inc`(其下有 `SDL2/` 软链),不能用 `SDL2.framework/Headers` 直接作为 `-I`。
2. 运行时必须加 `-Wl,-rpath,/Users/mmm/Library/Frameworks`,否则 dyld 报 `Library not loaded: @rpath/SDL2.framework`。
3. C/C++/Zig 编译同样加 `-I/Users/mmm/.local/sdl2inc -F/Users/mmm/Library/Frameworks -framework SDL2 -Wl,-rpath,/Users/mmm/Library/Frameworks`。
4. Rust `sdl2` crate 若走 framework,需设 `SDL2_FRAMEWORK=/Users/mmm/Library/Frameworks/SDL2.framework`,并保证 rpath。若 crate 链接困难,改用 `std::process::Command` 调用一个极简 C shim(但优先 crate)。
### 6.8 macOS 主线程要求(重要)
macOS Cocoa 要求所有 UI 调用发生在主线程,否则崩溃:
`NSInternalInconsistencyException: nextEventMatchingMask should only be called from the Main Thread!`
- **Go**:`RunGUI()` 开头必须 `runtime.LockOSThread()`(已验证)
- **C/C++/Zig/Rust/Java**:原生程序主线程天然是 UI 线程,无此问题
- 冒烟测试:`./gcctl gui` 后台运行 3 秒后 kill,无异常输出即通过
View File
File renamed without changes.
File renamed without changes.
@@ -4,7 +4,7 @@ namespace GC.UI.Server;
// ---------------------------------------------------------------------------
// 前后端之间的数据契约(HTTP + JSON,camelCase)。
// 前端(Flutter)只认这些字段,不认 .NET 类型;后端换实现不影响前端。
// HTTP 客户端只认这些字段,不认 .NET 类型;后端换实现不影响契约。
// ---------------------------------------------------------------------------
public sealed record HealthDto(
@@ -124,9 +124,21 @@ public sealed record UpdateCheckDto(
public sealed record ContributorDto(string Name, int Contributions, string? AvatarUrl);
// ---- 用户 API DTO ----
public sealed record RegisterRequest(string Username, string Password);
public sealed record RegisterRequest(
string Username,
string Password,
string? CaptchaId = null,
string? Captcha = null);
public sealed record LoginRequest(string Username, string Password);
public sealed record ThemeRequest(string Color, int Cost);
/// <summary>换主题色:只传颜色,价格由服务端按预置/自定义判定。</summary>
public sealed record ThemeRequest(string Color, int? Cost = null);
/// <summary>二选一:两个候选选项,服务端随机挑一个并计费。</summary>
public sealed record PickRequest(string OptionA, string OptionB);
public sealed record CaptchaDto(string Id, string Question);
/// <summary>「重新下载启动器」结果:State = Ready / UpToDate / Failed。</summary>
@@ -0,0 +1,180 @@
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Threading;
using GC.Models;
using GC.Services;
using GC.Views;
namespace GC.UI.Server;
/// <summary>
/// 模型窗口宿主。
///
/// 为什么渲染这一层留在 .NET:模型 dll 通过 <c>IModelRuntime.CreateView</c> 返回的是
/// Avalonia <see cref="Control"/>,这是模型契约的一部分。换掉渲染栈等于换掉契约,
/// 所有已发布模型都会失效。所以前后端分离的切法是:
/// · 界面(首页 / 下载 / 设置 / 关于)→ Avalonia 主窗口
/// · 模型窗口(模型自带界面)→ 仍由 .NET 承载,前端只发一条「启动模型」的指令
///
/// 这里惰性启动一个没有主窗口的 Avalonia 桌面生命周期,之后所有模型窗口都在它的 UI 线程上创建。
/// 无桌面会话(CI / 无头环境)时启动会失败,此时只有「启动模型」不可用,其余接口照常工作。
/// </summary>
public sealed class AvaloniaHost
{
private readonly AppServices _services;
private readonly object _gate = new();
private readonly Dictionary<string, PlayerWindow> _windows = new(StringComparer.OrdinalIgnoreCase);
private readonly TaskCompletionSource<bool> _ready =
new(TaskCreationOptions.RunContinuationsAsynchronously);
private int _started;
public AvaloniaHost(AppServices services) => _services = services;
public bool IsAvailable { get; private set; }
public string? LastError { get; private set; }
/// <summary>
/// 后端线程调用:等待「主线程已把 Avalonia 事件循环跑起来」。
///
/// 关键点:macOS 的 AppKit 要求 NSApplication 在**主线程**。以前这里把
/// <c>StartWithClassicDesktopLifetime</c> 丢到一个新建的后台线程里跑,在 macOS 上
/// 会直接崩掉整个后端进程(表现为点「启动模型」界面无反应、随后后端消失)。
/// 现在改为由启动器在主线程调用 <see cref="RunOnCurrentThread"/>,
/// 这里只等待就绪信号。
/// </summary>
public Task<bool> EnsureStartedAsync() => _ready.Task;
/// <summary>
/// 必须在 UI 主线程调用。启动 Avalonia 桌面生命周期并阻塞,直到 <see cref="Shutdown"/>。
/// 返回后(或初始化失败后)调用方负责收尾。
/// </summary>
public void RunOnCurrentThread()
{
if (Interlocked.Exchange(ref _started, 1) == 1) return;
try
{
AppBuilder.Configure<HostApp>()
.UsePlatformDetect()
.AfterSetup(_ =>
{
IsAvailable = true;
_ready.TrySetResult(true);
})
.StartWithClassicDesktopLifetime(Array.Empty<string>());
}
catch (Exception ex)
{
// 无桌面会话(CI / 无头环境):模型窗口不可用,但后端其余接口照常。
LastError = ex.Message;
_ready.TrySetResult(false);
}
}
/// <summary>从任意线程请求结束事件循环,使 <see cref="RunOnCurrentThread"/> 返回。</summary>
public void Shutdown()
{
if (_started == 0) return;
try
{
Dispatcher.UIThread.Post(() =>
{
if (Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
desktop.Shutdown();
});
}
catch
{
// 事件循环尚未建立或已退出:无需处理
}
}
/// <summary>在 Avalonia UI 线程上加载模型并打开它自己的窗口。</summary>
public async Task<string> LaunchAsync(ModelPackage package)
{
if (!await EnsureStartedAsync().ConfigureAwait(false))
throw new InvalidOperationException(
LastError ?? "无法初始化图形环境(当前会话没有桌面?)");
return await Dispatcher.UIThread.InvokeAsync<string>(async () =>
{
// 同一个模型已经在运行:把已有窗口提到前台,不再加载第二份实例
// (连点「启动模型」会各占一份内存与显存,低配机器直接卡死)。
lock (_gate)
{
if (_windows.TryGetValue(package.Id, out var existing))
{
try
{
if (existing.WindowState == WindowState.Minimized)
existing.WindowState = WindowState.Normal;
existing.Activate();
return $"模型 {package.Id} 已在运行";
}
catch
{
// 窗口已失效:清掉记录,按新窗口重新打开
_windows.Remove(package.Id);
}
}
}
PlayerWindow? window = null;
LoadedModel? loaded = null;
try
{
Action requestClose = () => Dispatcher.UIThread.Post(() =>
{
try { window?.Close(); } catch { /* 已关闭 */ }
});
loaded = await _services.ModelHost.LoadAsync(package, requestClose, null);
window = new PlayerWindow(package, loaded);
var captured = loaded;
var id = package.Id;
window.Closed += (_, _) =>
{
try { captured.Dispose(); } catch { /* 释放失败不影响退出 */ }
lock (_gate)
{
if (_windows.TryGetValue(id, out var current) && ReferenceEquals(current, window))
_windows.Remove(id);
}
};
lock (_gate) _windows[id] = window;
window.Show();
return $"已启动模型 {package.Id}";
}
catch
{
try { loaded?.Dispose(); } catch { /* 忽略 */ }
throw;
}
});
}
}
/// <summary>后端自己的 Avalonia 应用:没有主窗口,只用来承载模型窗口。</summary>
internal sealed class HostApp : Application
{
public override void Initialize() { }
public override void OnFrameworkInitializationCompleted()
{
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{
desktop.ShutdownMode = ShutdownMode.OnExplicitShutdown;
desktop.MainWindow = null;
}
base.OnFrameworkInitializationCompleted();
}
}
@@ -36,15 +36,26 @@ public static class BackendServer
/// 构建后端。返回的 <see cref="WebApplication"/> 尚未启动:
/// 独立进程直接 <c>Run()</c>,启动器用 <c>StartAsync()</c> 之后继续拉起界面。
///
/// 模型渲染已全部交给 Flutter,本进程只提供 HTTP API,不再有窗口宿主。
/// 主界面已是 Avalonia;本后端仅用于独立 HTTP 部署场景。
/// </summary>
public static WebApplication Start(string[] args, int port)
=> Start(args, port, out _);
/// <summary>
/// 构建后端,并通过 <paramref name="uiHost"/> 交出模型窗口宿主。
///
/// 调用方(启动器)必须在**主线程**调用 <see cref="AvaloniaHost.RunOnCurrentThread"/>:
/// macOS 的 AppKit 要求 NSApplication 运行在主线程,否则打开模型窗口时整个进程会崩溃。
/// </summary>
public static WebApplication Start(string[] args, int port, out AvaloniaHost uiHost)
{
// 下载模块(GC-DOWNLOAD)通过宿主钩子注入,和 GC-BOOT 的做法一致。
DownloadModuleHost.Factory = new DownloadModuleFactory();
var services = AppServices.Create();
var userService = new UserService(services.Paths.HomeRoot);
var host = new AvaloniaHost(services);
uiHost = host;
var builder = WebApplication.CreateBuilder(new WebApplicationOptions { Args = args });
builder.Logging.ClearProviders();
@@ -62,7 +73,7 @@ public static class BackendServer
});
// 桌面端(Windows/macOS)走原生 HTTP,不需要 CORS;
// 这里放开本机回环来源,方便用 `flutter run -d chrome` 调试界面。
// 这里放开本机回环来源,方便本地调试客户端。
builder.Services.AddCors(options => options.AddDefaultPolicy(policy => policy
.SetIsOriginAllowed(origin =>
Uri.TryCreate(origin, UriKind.Absolute, out var uri) &&
@@ -193,7 +204,7 @@ public static class BackendServer
// 简单 session 存储:key = username(lower), value = session token
var userSessions = new System.Collections.Concurrent.ConcurrentDictionary<string, string>();
// 中间件:从 header 提取当前用户
// 中间件:从 header 提取当前用户;没有 token 时回退到 user.yaml 记住的用户(自动登录)
app.Use(async (context, next) =>
{
context.Items["user"] = null as string;
@@ -209,14 +220,67 @@ public static class BackendServer
}
}
}
if (context.Items["user"] is not string u || string.IsNullOrEmpty(u))
context.Items["user"] = userService.RestoredUser;
await next();
});
// 人品值评语(与前端 FortuneResult.commentFor 保持一致)
static string FortuneComment(int value)
{
if (value >= 96) return "欧皇附体,今天买彩票吧";
if (value >= 90) return "运气爆棚,适合干大事";
if (value >= 80) return "手气不错,稳";
if (value >= 65) return "中上水平,稍微努一下";
if (value >= 50) return "普普通通,够用";
if (value >= 35) return "有点背,低调点";
if (value >= 20) return "今天别赌任何东西";
if (value >= 8) return "极差,建议躺平";
return "非酋之王,明天再来";
}
// 统一的用户响应体:前端一次拿齐签到 / 主题色需要的所有字段
object UserPayload(UserRecord r)
{
// 与 UserService 保持一致:本地日历日,不能用 UTC
var today = DateTime.Today;
int nextConsecutive;
if (!r.LastSignIn.HasValue) nextConsecutive = 1;
else
{
var diff = (today - r.LastSignIn.Value.Date).Days;
nextConsecutive = diff <= 1 ? r.ConsecutiveDays + 1 : 1;
}
var refund = UserService.RefundRemaining(r);
return new
{
username = r.Username,
points = r.Points,
consecutive_days = r.ConsecutiveDays,
cycle_day = UserService.CycleDay(r.ConsecutiveDays),
cycle_days = UserService.SignInCycleDays,
today_signed = r.LastSignIn.HasValue && r.LastSignIn.Value.Date == today,
next_reward = UserService.GetSignInReward(UserService.CycleDay(nextConsecutive)),
last_sign_in = r.LastSignIn?.ToString("yyyy-MM-dd") ?? "",
theme_color = r.ThemeColor ?? UserService.DefaultThemeColor,
theme_paid = r.ThemePaid,
refund_seconds = refund.HasValue ? (int)refund.Value.TotalSeconds : 0
};
}
// 人机验证:算术题,5 分钟有效、一次性
app.MapGet("/api/user/captcha", () =>
{
var (id, question) = userService.IssueCaptcha();
return Results.Ok(new CaptchaDto(id, question));
});
app.MapPost("/api/user/register", (RegisterRequest? req) => {
if (req == null) return Results.BadRequest(new { error = "请求体为空" });
if (string.IsNullOrWhiteSpace(req.Username)) return Results.BadRequest(new { error = "用户名不能为空" });
if (string.IsNullOrWhiteSpace(req.Password)) return Results.BadRequest(new { error = "密码不能为空" });
var ok = userService.Register(req.Username, req.Password, out var err);
var ok = userService.Register(req.Username, req.Password, req.CaptchaId, req.Captcha, out var err);
return ok ? Results.Ok(new { message = "注册成功" }) : Results.BadRequest(new { error = err });
});
@@ -226,7 +290,9 @@ public static class BackendServer
if (!ok) return Results.BadRequest(new { error = err });
// 生成 session token
var sessionToken = Convert.ToBase64String(System.Security.Cryptography.RandomNumberGenerator.GetBytes(32)).Replace("/", "_").Replace("+", "-").Substring(0, 32);
userSessions[rec!.Username.ToLower()] = sessionToken;
userSessions[rec!.Username.ToLowerInvariant()] = sessionToken;
// 记住登录:写 .GC/user/user.yaml,下次启动自动登录
userService.SaveSession(rec.Username, sessionToken);
return Results.Ok(new {
username = rec.Username,
points = rec.Points,
@@ -237,18 +303,19 @@ public static class BackendServer
});
});
app.MapPost("/api/user/logout", (HttpContext ctx) => {
var username = ctx.Items["user"] as string;
if (!string.IsNullOrEmpty(username)) userSessions.TryRemove(username, out _);
userService.ClearSession();
return Results.Ok(new { message = "已退出登录" });
});
app.MapGet("/api/user/me", (HttpContext ctx) =>
{
var username = ctx.Items["user"] as string;
if (string.IsNullOrEmpty(username) || !userService.TryGetUser(username, out var rec))
return Results.Json(new { error = "未登录" }, statusCode: 401);
return Results.Ok(new {
username = rec.Username,
points = rec.Points,
consecutive_days = rec.ConsecutiveDays,
last_sign_in = rec.LastSignIn?.ToString("yyyy-MM-dd") ?? "",
theme_color = rec.ThemeColor ?? ""
});
return Results.Ok(UserPayload(rec));
});
app.MapPost("/api/user/signin", (HttpContext ctx) =>
@@ -256,18 +323,52 @@ public static class BackendServer
var username = ctx.Items["user"] as string;
if (string.IsNullOrEmpty(username) || !userService.TryGetUser(username, out var rec))
return Results.Json(new { error = "未登录" }, statusCode: 401);
var ok = userService.UpdateSignIn(username, out var err);
var ok = userService.UpdateSignIn(username, out var err, out var reward);
if (!ok)
{
if (err == "今日已签到")
return Results.Ok(new { message = err, points = rec.Points, consecutive_days = rec.ConsecutiveDays });
return Results.Ok(new { message = err, user = UserPayload(rec) });
return Results.BadRequest(new { error = err });
}
return Results.Ok(new {
points = rec.Points,
consecutive_days = rec.ConsecutiveDays,
reward = userService.GetSignInReward(rec.ConsecutiveDays),
last_sign_in = rec.LastSignIn?.ToString("yyyy-MM-dd") ?? ""
reward,
user = UserPayload(rec)
});
});
app.MapPost("/api/user/fortune", (HttpContext ctx) =>
{
var username = ctx.Items["user"] as string;
if (string.IsNullOrEmpty(username))
return Results.Json(new { error = "未登录" }, statusCode: 401);
var ok = userService.RollFortune(username, out var err, out var value,
out var cost, out var rec);
if (!ok) return Results.BadRequest(new { error = err });
return Results.Ok(new {
value,
cost,
comment = FortuneComment(value),
user = UserPayload(rec!)
});
});
app.MapPost("/api/user/pick", (HttpContext ctx, PickRequest? req) =>
{
var username = ctx.Items["user"] as string;
if (string.IsNullOrEmpty(username))
return Results.Json(new { error = "未登录" }, statusCode: 401);
if (req == null) return Results.BadRequest(new { error = "请求体为空" });
var ok = userService.PickOne(username, req.OptionA, req.OptionB, out var err,
out var choice, out var cost, out var rec);
if (!ok) return Results.BadRequest(new { error = err });
return Results.Ok(new {
choice,
cost,
user = UserPayload(rec!)
});
});
@@ -277,8 +378,15 @@ public static class BackendServer
if (string.IsNullOrEmpty(username) || !userService.TryGetUser(username, out var rec))
return Results.Json(new { error = "未登录" }, statusCode: 401);
if (req == null) return Results.BadRequest(new { error = "请求体为空" });
var ok = userService.ChangeThemeColor(username, req.Color, req.Cost, out var err);
return ok ? Results.Ok(new { message = "主题已更新", points = rec.Points, theme_color = rec.ThemeColor }) : Results.BadRequest(new { error = err });
var ok = userService.ChangeThemeColor(username, req.Color, out var err, out var refunded);
if (!ok) return Results.BadRequest(new { error = err });
return Results.Ok(new {
message = "主题已更新",
refunded,
user = UserPayload(rec)
});
});
app.MapGet("/api/health", () => Results.Ok(new HealthDto(
@@ -307,15 +415,25 @@ app.MapGet("/api/health", () => Results.Ok(new HealthDto(
return Results.File(package.PreviewPath, GuessImageContentType(package.PreviewPath));
});
// 模型改为客户端内渲染(Flutter):这里只确认模型存在并把 id 交回去,
// 模型由客户端渲染:这里只确认模型存在并把 id 交回去,
// 不再拉起 Avalonia 窗口。保留接口是为了老客户端不至于 404。
app.MapPost("/api/models/{id}/launch", (string id) =>
app.MapPost("/api/models/{id}/launch", async (string id) =>
{
if (!IsSafeId(id)) return Results.BadRequest(new LaunchResultDto(false, "模型标识无效"));
var package = services.Models.Find(id);
if (package == null) return Results.NotFound(new LaunchResultDto(false, $"没有找到模型 {id}"));
return Results.Ok(new LaunchResultDto(true, $"在应用内打开 {package.Manifest.Name}"));
try
{
services.Memory.Refresh();
var message = await host.LaunchAsync(package);
return Results.Ok(new LaunchResultDto(true, message));
}
catch (Exception ex)
{
Console.Error.WriteLine($"[launch] 启动模型 {id} 失败: {ex}");
return Results.Json(new LaunchResultDto(false, "模型启动失败,请查看后端日志"), statusCode: 503);
}
});
app.MapDelete("/api/models/{id}", (string id) =>
@@ -571,7 +689,7 @@ app.MapGet("/api/health", () => Results.Ok(new HealthDto(
contributors,
// 「关于」页展示的技术栈信息:源码语言与前端框架。
SourceLanguage: "C#",
Frontend: "Flutter"));
Frontend: "Avalonia"));
});
// ---- 系统集成 -------------------------------------------------------------
@@ -3,9 +3,9 @@
<!--
GC-UI 后端:把原来「启动器 = UI + 服务」的一体式结构拆成
· 后端(本工程):模型扫描 / 下载 / 更新 / 设置 / 模型窗口宿主,只暴露本地 HTTP API
· 前端(GC-UI/frontend,Flutter):只做界面,通过 HTTP 调后端
· HTTP 客户端:通过 HTTP 调用本后端(可选部署)
模型渲染也已并入 Flutter(lib/models/):模型不再返回 Avalonia Control,
模型渲染由客户端负责:模型不再返回 Avalonia Control,
后端只剩纯 HTTP API,不再依赖任何 UI 框架。
-->
<PropertyGroup>
@@ -4,5 +4,5 @@ using GC.UI.Server;
// 启动器在进程内直接调用 BackendServer.Start,不会走到这里。
var app = BackendServer.StartFromCommandLine(args);
// 纯 HTTP 后端(模型渲染在 Flutter 客户端里),跑起来常驻即可。
// 纯 HTTP 后端(供独立部署 / 外部客户端使用),跑起来常驻即可。
app.Run();
@@ -0,0 +1,696 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
namespace GC.UI.Server;
/// <summary>
/// 本地用户系统:注册 / 登录 / 签到 / 积分 / 主题色。
///
/// 目录结构(都在 .GC/user 下):
/// .GC/user/user.yaml 本地登录信息(当前用户 + session token)
/// .GC/user/&lt;用户名&gt;/pw.yaml 该用户的账号数据(用户名、积分、密码 sha512)
///
/// 密码只存 sha512(密码 + ":" + 随机盐),不存明文;盐单独一行保存。
/// </summary>
public sealed class UserService
{
/// <summary>默认主题色(蓝色):免费。</summary>
public const string DefaultThemeColor = "4A90D9";
/// <summary>预置颜色单价。</summary>
public const int PresetColorCost = 50;
/// <summary>自定义颜色单价。</summary>
public const int CustomColorCost = 150;
/// <summary>退款窗口:购买后 1 小时内换色可退 80%。</summary>
public static readonly TimeSpan RefundWindow = TimeSpan.FromHours(1);
/// <summary>退款比例。</summary>
public const double RefundRate = 0.8;
/// <summary>签到周期长度(天)。</summary>
public const int SignInCycleDays = 30;
private static readonly string[] PresetColors =
{
"4A90D9", "E74C3C", "27AE60", "9B59B6",
"F39C12", "1ABC9C", "E91E63", "2C3E50"
};
private readonly string _userDir;
private readonly string _sessionFile;
public readonly ConcurrentDictionary<string, UserRecord> _users = new();
/// <summary>验证码:id → (答案, 过期时间)。一次性,用后即删。</summary>
private readonly ConcurrentDictionary<string, (int Answer, DateTime Expires)> _captchas = new();
/// <summary>记住的登录用户(来自 user.yaml),没有显式 token 时用它。</summary>
private string? _restoredUser;
public UserService(string homeRoot)
{
_userDir = Path.Combine(homeRoot, "user");
_sessionFile = Path.Combine(_userDir, "user.yaml");
Directory.CreateDirectory(_userDir);
LoadAll();
LoadSession();
}
// ---------------------------------------------------------------- 读写磁盘
private void LoadAll()
{
foreach (var dir in Directory.GetDirectories(_userDir))
{
try
{
var file = Path.Combine(dir, "pw.yaml");
if (!File.Exists(file)) continue;
var rec = DeserializeUser(Path.GetFileName(dir), File.ReadAllText(file));
if (rec != null) _users[rec.Username.ToLowerInvariant()] = rec;
}
catch { /* 单个用户文件损坏不影响其他用户 */ }
}
// 兼容旧布局:.GC/user/<用户名>.yaml 直接放在根下(迁移到 <用户名>/pw.yaml)
foreach (var legacy in Directory.GetFiles(_userDir, "*.yaml"))
{
if (string.Equals(legacy, _sessionFile, StringComparison.OrdinalIgnoreCase)) continue;
try
{
var name = Path.GetFileNameWithoutExtension(legacy);
var rec = DeserializeUser(name, File.ReadAllText(legacy));
if (rec == null) continue;
_users[rec.Username.ToLowerInvariant()] = rec;
SaveUser(rec);
File.Delete(legacy);
}
catch { /* 忽略 */ }
}
}
private static UserRecord? DeserializeUser(string fallbackName, string yaml)
{
var lines = yaml.Split('\n', StringSplitOptions.RemoveEmptyEntries);
string? username = null, pwHash = null, pwSalt = null, themeColor = null;
decimal points = 0, themePaid = 0;
int consecutiveDays = 0, fortuneCount = 0, pickCount = 0;
DateTime? lastSignIn = null, themePaidAt = null, fortuneDate = null, pickDate = null;
foreach (var line in lines)
{
var parts = line.Split(':', 2);
if (parts.Length != 2) continue;
var key = parts[0].Trim();
var val = parts[1].Trim();
switch (key)
{
case "username": username = val; break;
case "pw_hash": pwHash = val; break;
case "pw_salt": pwSalt = val; break;
// 旧文件里积分是整数;decimal.TryParse 兼容读取
case "points": decimal.TryParse(val, out var p); points = p; break;
case "last_sign_in":
if (DateTime.TryParse(val, out var ls)) lastSignIn = ls;
break;
case "consecutive_days": int.TryParse(val, out var d); consecutiveDays = d; break;
case "theme_color": themeColor = val; break;
case "theme_paid": decimal.TryParse(val, out var tp); themePaid = tp; break;
case "theme_paid_at":
if (DateTime.TryParse(val, out var ta)) themePaidAt = ta;
break;
case "fortune_date":
if (DateTime.TryParse(val, out var fd)) fortuneDate = fd;
break;
case "fortune_count": int.TryParse(val, out var fc); fortuneCount = fc; break;
case "pick_date":
if (DateTime.TryParse(val, out var pd)) pickDate = pd;
break;
case "pick_count": int.TryParse(val, out var pc); pickCount = pc; break;
}
}
if (string.IsNullOrWhiteSpace(username)) username = fallbackName;
if (pwHash == null || pwSalt == null) return null;
return new UserRecord(username!, pwHash, pwSalt, points, lastSignIn, consecutiveDays,
string.IsNullOrWhiteSpace(themeColor) ? DefaultThemeColor : themeColor,
themePaid, themePaidAt)
{
FortuneDate = fortuneDate,
FortuneCount = fortuneCount,
PickDate = pickDate,
PickCount = pickCount
};
}
private void SaveUser(UserRecord rec)
{
try
{
var dir = Path.Combine(_userDir, SafeDirName(rec.Username));
Directory.CreateDirectory(dir);
var yaml = new StringBuilder()
.AppendLine($"username: {rec.Username}")
.AppendLine($"pw_hash: {rec.PwHash}")
.AppendLine($"pw_salt: {rec.PwSalt}")
.AppendLine($"points: {rec.Points.ToString("0.##")}")
.AppendLine($"last_sign_in: {rec.LastSignIn?.ToString("yyyy-MM-dd") ?? ""}")
.AppendLine($"consecutive_days: {rec.ConsecutiveDays}")
.AppendLine($"theme_color: {rec.ThemeColor ?? DefaultThemeColor}")
.AppendLine($"theme_paid: {rec.ThemePaid.ToString("0.##")}")
.AppendLine($"theme_paid_at: {rec.ThemePaidAt?.ToString("o") ?? ""}")
.AppendLine($"fortune_date: {rec.FortuneDate?.ToString("yyyy-MM-dd") ?? ""}")
.AppendLine($"fortune_count: {rec.FortuneCount}")
.AppendLine($"pick_date: {rec.PickDate?.ToString("yyyy-MM-dd") ?? ""}")
.AppendLine($"pick_count: {rec.PickCount}")
.ToString();
File.WriteAllText(Path.Combine(dir, "pw.yaml"), yaml);
}
catch { /* 写盘失败不影响内存状态 */ }
}
/// <summary>用户名做目录名时过滤掉路径分隔符与 Windows 保留字符。</summary>
private static string SafeDirName(string username)
{
var invalid = Path.GetInvalidFileNameChars();
var chars = username.Select(c => invalid.Contains(c) || c == '.' ? '_' : c).ToArray();
var name = new string(chars).Trim();
return string.IsNullOrEmpty(name) ? "_" : name;
}
// ---------------------------------------------------------------- 登录态
private void LoadSession()
{
try
{
if (!File.Exists(_sessionFile)) return;
foreach (var line in File.ReadAllLines(_sessionFile))
{
var parts = line.Split(':', 2);
if (parts.Length == 2 && parts[0].Trim() == "username")
{
var name = parts[1].Trim();
if (!string.IsNullOrEmpty(name) && _users.ContainsKey(name.ToLowerInvariant()))
_restoredUser = name.ToLowerInvariant();
}
}
}
catch { /* 忽略 */ }
}
public void SaveSession(string username, string token)
{
try
{
var lower = username.ToLowerInvariant();
_restoredUser = lower;
Directory.CreateDirectory(_userDir);
File.WriteAllText(_sessionFile,
$"username: {username}\nsession_token: {token}\n");
}
catch { /* 忽略 */ }
}
public void ClearSession()
{
_restoredUser = null;
try { if (File.Exists(_sessionFile)) File.Delete(_sessionFile); } catch { /* 忽略 */ }
}
/// <summary>没有携带 token 时,回退到 user.yaml 里记住的用户(自动登录)。</summary>
public string? RestoredUser => _restoredUser;
// ---------------------------------------------------------------- 验证码
/// <summary>签发一个算术验证码,5 分钟内有效,用后即焚。</summary>
public (string Id, string Question) IssueCaptcha()
{
var now = DateTime.UtcNow;
// 顺手清理过期项,避免长时间运行后字典无限增长
if (_captchas.Count > 128)
{
foreach (var kv in _captchas)
if (kv.Value.Expires < now) _captchas.TryRemove(kv.Key, out _);
}
var a = RandomNumberGenerator.GetInt32(2, 10);
var b = RandomNumberGenerator.GetInt32(2, 10);
var plus = RandomNumberGenerator.GetInt32(0, 2) == 0;
var answer = plus ? a + b : Math.Max(a, b) - Math.Min(a, b);
var id = Convert.ToHexString(RandomNumberGenerator.GetBytes(12)).ToLowerInvariant();
_captchas[id] = (answer, now.AddMinutes(5));
var question = plus ? $"{a} + {b} = ?" : $"{Math.Max(a, b)} - {Math.Min(a, b)} = ?";
return (id, question);
}
public bool VerifyCaptcha(string? id, string? answer, out string error)
{
error = "";
if (string.IsNullOrWhiteSpace(id) || string.IsNullOrWhiteSpace(answer))
{
error = "请先完成人机验证";
return false;
}
if (!_captchas.TryRemove(id, out var entry))
{
error = "验证码已失效,请重新获取";
return false;
}
if (entry.Expires < DateTime.UtcNow)
{
error = "验证码已过期,请重新获取";
return false;
}
if (!int.TryParse(answer.Trim(), out var value) || value != entry.Answer)
{
error = "验证码答案错误";
return false;
}
return true;
}
// ---------------------------------------------------------------- 账号
public bool Register(string username, string password, string? captchaId, string? captcha,
out string error)
{
if (!VerifyCaptcha(captchaId, captcha, out error)) return false;
if (string.IsNullOrWhiteSpace(username) || username.Length > 20)
{
error = "用户名需为 1–20 个字符";
return false;
}
if (username.Any(char.IsWhiteSpace))
{
error = "用户名不能包含空格";
return false;
}
if (_users.ContainsKey(username.Trim().ToLowerInvariant()))
{
error = "用户名已存在,请换一个";
return false;
}
if (string.IsNullOrWhiteSpace(password) || password.Length < 6)
{
error = "密码至少 6 位";
return false;
}
var name = username.Trim();
var salt = GenerateSalt();
var rec = new UserRecord(name, HashPassword(password, salt), salt,
0, null, 0, DefaultThemeColor, 0, null);
_users[name.ToLowerInvariant()] = rec;
SaveUser(rec);
return true;
}
public bool Login(string username, string password, out string error, out UserRecord? record)
{
error = "";
record = null;
if (!_users.TryGetValue(username.Trim().ToLowerInvariant(), out var rec))
{
error = "用户名或密码错误";
return false;
}
if (HashPassword(password, rec.PwSalt) != rec.PwHash)
{
error = "用户名或密码错误";
return false;
}
record = rec;
return true;
}
public bool TryGetUser(string username, out UserRecord? record)
=> _users.TryGetValue(username.Trim().ToLowerInvariant(), out record);
public UserRecord? GetFirstUser() => _users.Values.FirstOrDefault();
public bool UpdatePoints(string username, decimal deltaPoints, out string error)
{
error = "";
if (!_users.TryGetValue(username.Trim().ToLowerInvariant(), out var rec))
{
error = "用户不存在";
return false;
}
rec.Points = Math.Max(0, rec.Points + deltaPoints);
SaveUser(rec);
return true;
}
// ---------------------------------------------------------------- 签到
/// <summary>
/// 30 天一循环的签到奖励。第 7/14/21/28 天给「周奖励」,第 30 天给满月奖励。
/// </summary>
public static int GetSignInReward(int cycleDay)
{
if (cycleDay < 1) cycleDay = 1;
if (cycleDay > SignInCycleDays) cycleDay = ((cycleDay - 1) % SignInCycleDays) + 1;
return cycleDay switch
{
7 => 30,
14 => 40,
21 => 50,
28 => 60,
30 => 100,
<= 6 => 10,
<= 13 => 15,
<= 20 => 20,
<= 27 => 25,
_ => 40
};
}
public static int CycleDay(int consecutiveDays)
{
if (consecutiveDays < 1) return 1;
return ((consecutiveDays - 1) % SignInCycleDays) + 1;
}
public bool UpdateSignIn(string username, out string error, out int reward)
{
error = "";
reward = 0;
if (!_users.TryGetValue(username.Trim().ToLowerInvariant(), out var rec))
{
error = "用户不存在";
return false;
}
// 本地日历日:签到按用户机器上的「今天」算(0 点翻篇),不能用 UTC——
// 否则东八区用户要到早上 8 点才算新的一天,会出现同一天签到两次。
var today = DateTime.Today;
if (rec.LastSignIn.HasValue)
{
var diff = (today - rec.LastSignIn.Value.Date).Days;
if (diff == 0)
{
error = "今日已签到";
return false;
}
// 断签超过一天:连续天数重置(但 30 天周期按新的连续天数重新算)
rec.ConsecutiveDays = diff == 1 ? rec.ConsecutiveDays + 1 : 1;
}
else
{
rec.ConsecutiveDays = 1;
}
rec.LastSignIn = today;
reward = GetSignInReward(CycleDay(rec.ConsecutiveDays));
rec.Points += reward;
SaveUser(rec);
return true;
}
// ---------------------------------------------------------------- 主题色
/// <summary>某个颜色的价格:默认蓝免费,预置色 50,其它(自定义)150。</summary>
public static int ThemeCost(string hex)
{
var h = NormalizeHex(hex);
if (string.IsNullOrEmpty(h)) return -1;
if (string.Equals(h, DefaultThemeColor, StringComparison.OrdinalIgnoreCase)) return 0;
return PresetColors.Contains(h, StringComparer.OrdinalIgnoreCase)
? PresetColorCost
: CustomColorCost;
}
public static string NormalizeHex(string? hex)
{
if (string.IsNullOrWhiteSpace(hex)) return "";
var h = hex.Trim().TrimStart('#');
if (h.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) h = h[2..];
if (h.Length != 6) return "";
return h.All(Uri.IsHexDigit) ? h.ToUpperInvariant() : "";
}
/// <summary>
/// 换主题色。服务端自己算价,不信客户端传的 cost。
/// 上次购买在 1 小时内,先按 80% 退还上次花费。
/// </summary>
public bool ChangeThemeColor(string username, string colorHex, out string error, out decimal refunded)
{
error = "";
refunded = 0;
if (!_users.TryGetValue(username.Trim().ToLowerInvariant(), out var rec))
{
error = "用户不存在";
return false;
}
var hex = NormalizeHex(colorHex);
if (string.IsNullOrEmpty(hex))
{
error = "颜色格式应为 #RRGGBB";
return false;
}
var cost = ThemeCost(hex);
if (cost < 0)
{
error = "颜色格式应为 #RRGGBB";
return false;
}
if (string.Equals(NormalizeHex(rec.ThemeColor), hex, StringComparison.OrdinalIgnoreCase))
{
error = "当前已经是这个颜色";
return false;
}
// 1 小时内换色:退回上次花费的 80%(保留 2 位小数)
var available = rec.Points;
if (rec.ThemePaid > 0 && rec.ThemePaidAt.HasValue &&
DateTime.UtcNow - rec.ThemePaidAt.Value <= RefundWindow)
{
refunded = Math.Floor(rec.ThemePaid * (decimal)RefundRate * 100) / 100;
available += refunded;
}
if (available < cost)
{
error = refunded > 0
? $"积分不足(含可退 {refunded},需 {cost})"
: $"积分不足,需要 {cost} 积分";
return false;
}
rec.Points = available - cost;
rec.ThemeColor = hex;
rec.ThemePaid = cost;
rec.ThemePaidAt = cost > 0 ? DateTime.UtcNow : null;
SaveUser(rec);
return true;
}
/// <summary>距离退款窗口关闭还剩多久;没有可退的就返回 null。</summary>
public static TimeSpan? RefundRemaining(UserRecord rec)
{
if (rec.ThemePaid <= 0 || !rec.ThemePaidAt.HasValue) return null;
var left = RefundWindow - (DateTime.UtcNow - rec.ThemePaidAt.Value);
return left > TimeSpan.Zero ? left : null;
}
// ---------------------------------------------------------------- 人品值 / 二选一
/// <summary>
/// 人品值当日费用。第一次免费;之后按当日已付费次数阶梯计费:
/// 第 1–5 次 0.1 / 第 6–10 次 0.2 / 第 11–25 次 0.5 / 第 26 次起 1。
/// </summary>
public static decimal FortuneCost(int paidIndexToday)
{
if (paidIndexToday <= 0) return 0m;
if (paidIndexToday <= 5) return 0.1m;
if (paidIndexToday <= 10) return 0.2m;
if (paidIndexToday <= 25) return 0.5m;
return 1m;
}
/// <summary>二选一当日费用:第一次免费,之后每次 0.5。</summary>
public static decimal PickCost(int paidIndexToday)
=> paidIndexToday <= 0 ? 0m : 0.5m;
/// <summary>算出当日费用并扣费;积分不足返回 false。成功后计数 +1。</summary>
private bool ChargeDailyFeature(UserRecord rec, Func<int, decimal> costFn,
DateTime? featureDate, int featureCount, out decimal cost, out string error)
{
error = "";
cost = 0;
// 本地日历日:签到按用户机器上的「今天」算(0 点翻篇),不能用 UTC——
// 否则东八区用户要到早上 8 点才算新的一天,会出现同一天签到两次。
var today = DateTime.Today;
// 跨天了先重置计数
if (featureDate.HasValue && featureDate.Value.Date != today)
featureCount = 0;
cost = costFn(featureCount);
if (rec.Points < cost)
{
error = cost > 0
? $"积分不足,本次需要 {cost.ToString("0.##")} 积分"
: "积分不足";
return false;
}
rec.Points = Math.Round(rec.Points - cost, 2);
return true;
}
/// <summary>
/// 摇一次人品值(服务端算随机数,客户端不信自己传的值)。
/// 当天第一次免费,之后按阶梯扣积分。
/// </summary>
public bool RollFortune(string username, out string error, out int value,
out decimal cost, out UserRecord? record)
{
error = "";
value = 0;
cost = 0;
record = null;
if (!_users.TryGetValue(username.Trim().ToLowerInvariant(), out var rec))
{
error = "用户不存在";
return false;
}
// 本地日历日:签到按用户机器上的「今天」算(0 点翻篇),不能用 UTC——
// 否则东八区用户要到早上 8 点才算新的一天,会出现同一天签到两次。
var today = DateTime.Today;
var count = rec.FortuneDate.HasValue && rec.FortuneDate.Value.Date == today
? rec.FortuneCount : 0;
if (!ChargeDailyFeature(rec, FortuneCost, rec.FortuneDate, count, out cost, out error))
return false;
rec.FortuneDate = today;
rec.FortuneCount = count + 1;
value = RandomNumberGenerator.GetInt32(0, 101);
record = rec;
SaveUser(rec);
return true;
}
/// <summary>二选一:服务端随机挑一个。当天第一次免费,之后每次 0.5。</summary>
public bool PickOne(string username, string optionA, string optionB, out string error,
out string choice, out decimal cost, out UserRecord? record)
{
error = "";
choice = "";
cost = 0;
record = null;
if (string.IsNullOrWhiteSpace(optionA) || string.IsNullOrWhiteSpace(optionB))
{
error = "两个选项都不能为空";
return false;
}
if (!_users.TryGetValue(username.Trim().ToLowerInvariant(), out var rec))
{
error = "用户不存在";
return false;
}
// 本地日历日:签到按用户机器上的「今天」算(0 点翻篇),不能用 UTC——
// 否则东八区用户要到早上 8 点才算新的一天,会出现同一天签到两次。
var today = DateTime.Today;
var count = rec.PickDate.HasValue && rec.PickDate.Value.Date == today
? rec.PickCount : 0;
if (!ChargeDailyFeature(rec, PickCost, rec.PickDate, count, out cost, out error))
return false;
rec.PickDate = today;
rec.PickCount = count + 1;
choice = RandomNumberGenerator.GetInt32(0, 2) == 0 ? optionA : optionB;
record = rec;
SaveUser(rec);
return true;
}
// ---------------------------------------------------------------- 散列
private static string GenerateSalt()
{
var bytes = new byte[16];
using var rng = RandomNumberGenerator.Create();
rng.GetBytes(bytes);
return Convert.ToBase64String(bytes);
}
private static string HashPassword(string password, string salt)
{
using var sha512 = SHA512.Create();
var hash = sha512.ComputeHash(Encoding.UTF8.GetBytes(password + ":" + salt));
return Convert.ToBase64String(hash);
}
}
public class UserRecord
{
public string Username { get; init; } = "";
public string PwHash { get; init; } = "";
public string PwSalt { get; init; } = "";
/// <summary>积分,精确到 0.01。</summary>
public decimal Points { get; set; }
public DateTime? LastSignIn { get; set; }
public int ConsecutiveDays { get; set; }
public string? ThemeColor { get; set; }
/// <summary>当前这个颜色实际花了多少分(用于 1 小时内退款)。</summary>
public decimal ThemePaid { get; set; }
/// <summary>购买该颜色的时间(UTC)。</summary>
public DateTime? ThemePaidAt { get; set; }
/// <summary>人品值当日最后计算日期(UTC),跨天计数清零。</summary>
public DateTime? FortuneDate { get; set; }
/// <summary>人品值当日已计算次数(含免费的那次)。</summary>
public int FortuneCount { get; set; }
/// <summary>二选一当日最后使用日期(UTC)。</summary>
public DateTime? PickDate { get; set; }
/// <summary>二选一当日已使用次数(含免费的那次)。</summary>
public int PickCount { get; set; }
public UserRecord(string username, string pwHash, string pwSalt, decimal points,
DateTime? lastSignIn, int consecutiveDays, string? themeColor = null,
decimal themePaid = 0, DateTime? themePaidAt = null)
{
Username = username;
PwHash = pwHash;
PwSalt = pwSalt;
Points = points;
LastSignIn = lastSignIn;
ConsecutiveDays = consecutiveDays;
ThemeColor = themeColor;
ThemePaid = themePaid;
ThemePaidAt = themePaidAt;
}
}
View File
File renamed without changes.
+48
View File
@@ -0,0 +1,48 @@
<Application xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="using:GC.ViewModels"
xmlns:views="using:GC.Views"
x:Class="GC.App"
RequestedThemeVariant="Light">
<Application.DataTemplates>
<DataTemplate DataType="{x:Type vm:HomeViewModel}">
<views:HomeView />
</DataTemplate>
<DataTemplate DataType="{x:Type vm:DownloadViewModel}">
<views:DownloadView />
</DataTemplate>
<DataTemplate DataType="{x:Type vm:SettingsViewModel}">
<views:SettingsView />
</DataTemplate>
<DataTemplate DataType="{x:Type vm:AboutViewModel}">
<views:AboutView />
</DataTemplate>
</Application.DataTemplates>
<Application.Resources>
<Color x:Key="SystemAccentColor">#2F6BFF</Color>
<!--
FluentTheme 的按钮模板在 :pointerover / :pressed 时会用这些主题资源
覆盖 ContentPresenter 的画刷。若与 AppTheme.axaml 里通过 Button 属性
设置的 hover 颜色不一致,两套机制会互相覆盖,导致光标移动时渲染错乱。
这里把它们统一指向与按钮样式相同的颜色。
-->
<SolidColorBrush x:Key="ButtonBackgroundPointerOver">#EDF2FC</SolidColorBrush>
<SolidColorBrush x:Key="ButtonBackgroundPressed">#DDE7F8</SolidColorBrush>
<SolidColorBrush x:Key="ButtonBorderBrushPointerOver">#BAC9E6</SolidColorBrush>
<SolidColorBrush x:Key="ButtonBorderBrushPressed">#9FB4DD</SolidColorBrush>
<SolidColorBrush x:Key="ButtonForegroundPointerOver">#111A2E</SolidColorBrush>
<SolidColorBrush x:Key="ButtonForegroundPressed">#111A2E</SolidColorBrush>
<SolidColorBrush x:Key="AccentButtonBackground">#2F6BFF</SolidColorBrush>
<SolidColorBrush x:Key="AccentButtonBackgroundPointerOver">#1F4FD0</SolidColorBrush>
<SolidColorBrush x:Key="AccentButtonBackgroundPressed">#183FA8</SolidColorBrush>
</Application.Resources>
<Application.Styles>
<FluentTheme />
<StyleInclude Source="avares://GC.Core/Styles/AppTheme.axaml" />
</Application.Styles>
</Application>
+141
View File
@@ -0,0 +1,141 @@
using System;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Markup.Xaml;
using GC.Services;
using GC.ViewModels;
using GC.Views;
namespace GC;
public partial class App : Application
{
public override void Initialize() => AvaloniaXamlLoader.Load(this);
/// <summary>初始化课件 WebView(macOS WKWebView / Windows WebView2 / Linux WebKitGTK)。</summary>
public override void RegisterServices()
{
base.RegisterServices();
AvaloniaWebView.AvaloniaWebViewBuilder.Initialize(default!);
}
public override void OnFrameworkInitializationCompleted()
{
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{
var services = AppServices.Create();
// 诊断模式:只验证模型程序集能否加载(发布包里也用它做冒烟测试)
if (Environment.GetEnvironmentVariable("EMS_SELFTEST") == "1")
{
var code = SelfTest(services);
Avalonia.Threading.Dispatcher.UIThread.Post(
() => desktop.Shutdown(code), Avalonia.Threading.DispatcherPriority.Background);
return;
}
// 启动加速:先建空窗口并显示,再在首帧之后构造 ViewModel。
// MainViewModel 会扫描模型、加载封面、读设置,同步做会让
// 「双击到看见窗口」明显变慢;先出窗口,内容随后填充。
var window = new MainWindow();
window.Show();
// 健康标记:GC-SAVEDOG 正在等这个文件。主窗口能显示出来,
// 就说明「新版本确实能启动」,它据此决定保留新版还是回滚。
StartupHealth.MarkHealthy(services.Paths.UpdateRoot,
LauncherRuntimeInfo.CurrentLauncherVersion);
// 首帧之后再构造 ViewModel:Post 而非依赖 Opened,
// 因为 Opened 在某些情况下不触发(headless / 部分平台),
// 会导致 DataContext 一直是 null、主页面白屏。
// 扫描模型 / 加载封面在后台线程做,UI 线程只负责赋值,
// 这样窗口能立刻响应,不会卡在白屏。
MainViewModel vm = null!;
Task.Run(() => new MainViewModel(services))
.ContinueWith(t =>
{
vm = t.Result;
Avalonia.Threading.Dispatcher.UIThread.Post(() =>
{
window.DataContext = vm;
WireMainViewModel(vm, window, services, desktop);
}, Avalonia.Threading.DispatcherPriority.Background);
}, System.Threading.Tasks.TaskScheduler.Default);
// 应用图标不依赖 ViewModel,先设好让窗口一出现就有图标
try
{
using var iconStream = Avalonia.Platform.AssetLoader.Open(
new Uri("avares://GC.Core/Assets/icon.png"));
window.Icon = new Avalonia.Controls.WindowIcon(iconStream);
}
catch { /* 图标缺失不影响启动 */ }
desktop.MainWindow = window;
desktop.ShutdownMode = ShutdownMode.OnMainWindowClose;
}
base.OnFrameworkInitializationCompleted();
}
/// <summary>
/// 主窗口显示后再接上 ViewModel:绑定对话框、启动后台更新检查。
/// 拆出来是为了让窗口先出现,模型扫描不影响「双击到出窗口」。
/// </summary>
private static void WireMainViewModel(MainViewModel vm, MainWindow window,
AppServices services, IClassicDesktopStyleApplicationLifetime desktop)
{
_ = desktop;
vm.ConfirmHandler = async message =>
{
var dialog = new ConfirmWindow(message);
return await dialog.ShowDialog<bool>(window);
};
// 发现启动器新版本:弹窗询问,用户选「更新」才下载并安排替换
vm.LauncherUpdateHandler = async newVersion =>
{
var dialog = new ConfirmWindow(
title: "发现新版本",
message: $"启动器有新版本 v{newVersion},是否立即更新?\n\n" +
"更新会下载新版程序,下次启动时自动替换当前版本;" +
"选择取消则继续使用当前版本,但模型仍会更新到最新。",
confirmText: "更新",
cancelText: "取消");
return await dialog.ShowDialog<bool>(window);
};
// 主窗口已显示,后台检查模型 / 启动器更新,不阻塞界面
if (Environment.GetEnvironmentVariable("EMS_NO_UPDATE") != "1")
{
Avalonia.Threading.Dispatcher.UIThread.Post(
() => _ = vm.RunStartupUpdateAsync(),
Avalonia.Threading.DispatcherPriority.Background);
}
}
/// <summary>逐个加载模型,打印结果;返回退出码(0 = 全部成功)。</summary>
private static int SelfTest(AppServices services)
{
var packages = services.Models.Scan();
Console.WriteLine($"模型库: {services.Paths.ModelRoot}");
Console.WriteLine($"模型数: {packages.Count}");
var failed = 0;
foreach (var package in packages)
{
try
{
using var loaded = services.ModelHost.Load(package, () => { });
Console.WriteLine($"OK {package.Id} -> {loaded.View.GetType().FullName}");
}
catch (Exception ex)
{
failed++;
Console.WriteLine($"FAIL {package.Id}: {ex.Message}");
}
}
return failed == 0 ? 0 : 1;
}
}
@@ -7,6 +7,7 @@
"nav.download": "Download",
"nav.settings": "Settings",
"nav.about": "About",
"nav.courseware": "Contour Course",
"home.title": "Model library",
"home.subtitle": "Pick a model and explain rotation, revolution and the seasons with an interactive 3D scene.",
"home.launch": "Launch model",
@@ -7,6 +7,7 @@
"nav.download": "下载",
"nav.settings": "设置",
"nav.about": "关于",
"nav.courseware": "等高线课件",
"home.title": "模型库",
"home.subtitle": "选择模型,用可交互的三维演示讲清自转、公转与四季成因。",
"home.launch": "启动模型",
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
+34
View File
@@ -0,0 +1,34 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<RootNamespace>GC</RootNamespace>
<AssemblyName>GC.Core</AssemblyName>
<InvariantGlobalization>false</InvariantGlobalization>
</PropertyGroup>
<ItemGroup>
<!-- 所有界面由 Avalonia 承载(主窗口 / 模型窗口 / 课件 WebView),
核心库包含 UI + 模型 SDK,并把 GC-DRAW 的播放器窗口一起编译进来。 -->
<Compile Include="..\..\GC-DRAW\PlayerWindow.cs" />
<Compile Remove="test\**\*.cs" />
<AvaloniaResource Include="Assets\**" />
<!-- 多语言表原先通过 Avalonia 的 avares:// 读取,改为嵌入资源 -->
<EmbeddedResource Include="Assets\i18n\*.json" LogicalName="GC.Core.Assets.i18n.%(Filename)%(Extension)" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="Avalonia.Desktop" Version="$(AvaloniaVersion)" />
<PackageReference Include="Avalonia.Themes.Fluent" Version="$(AvaloniaVersion)" />
<PackageReference Include="CommunityToolkit.Mvvm" Version="$(MvvmVersion)" />
<PackageReference Include="WebView.Avalonia" Version="11.0.0.1" />
<PackageReference Include="WebView.Avalonia.Desktop" Version="11.0.0.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\model\_sdk\GC.ModelSdk\GC.ModelSdk.csproj" />
</ItemGroup>
</Project>
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -13,6 +13,8 @@ public sealed class AppServices
public IDownloadCenter Downloads { get; }
public MemoryBudget Memory { get; }
public IModelSourceClient Sources { get; }
/// <summary>模型加载器:只负责把模型程序集跑起来,不渲染(渲染在 Avalonia PlayerWindow)。</summary>
public ModelHost ModelHost { get; }
/// <summary>启动时检查模型 / 启动器更新。</summary>
public IUpdateService Updates { get; }
/// <summary>双源测速选择器(Xhmcl / GitCode 取最快)。</summary>
@@ -32,6 +34,7 @@ public sealed class AppServices
Sources = DownloadModule.Sources;
Downloads = DownloadModule.Downloads;
Memory = new MemoryBudget();
ModelHost = new ModelHost(paths, Settings, Memory);
Selector = DownloadModule.Selector;
Updates = DownloadModule.Updates;
LauncherUpdates = DownloadModule.LauncherUpdates;
+158
View File
@@ -0,0 +1,158 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace GC.Services;
/// <summary>
/// 等高线课件本地静态服务器。
///
/// 课件是 HTML+CSS+JS+视频,直接用 file:// 加载会被 WebView 的同源策略拦住
/// (视频 Range 请求、fetch 本地资源都会失败),所以起一个只监听回环地址的
/// 微型 HTTP 服务器,端口自动分配,支持 Range 以便视频拖动。
///
/// 资源根目录优先取「可执行文件旁 courseware/」(发布布局),
/// 回退到用户目录下的 .GC/courseware/,开发时也能用。
/// </summary>
public sealed class CoursewareServer : IDisposable
{
private readonly HttpListener _listener = new();
private readonly string _root;
private bool _disposed;
public int Port { get; }
public string BaseUrl => $"http://127.0.0.1:{Port}/";
public CoursewareServer()
{
_root = FindRoot() ?? throw new DirectoryNotFoundException("找不到课件目录 courseware/");
// 端口 0 = 系统自动分配,避免与用户程序或后端冲突
Port = PickFreePort();
_listener.Prefixes.Add($"http://127.0.0.1:{Port}/");
_listener.Start();
_ = Task.Run(ServeLoop);
}
private static int PickFreePort()
{
var probe = new System.Net.Sockets.TcpListener(IPAddress.Loopback, 0);
probe.Start();
var port = ((IPEndPoint)probe.LocalEndpoint).Port;
probe.Stop();
return port;
}
private static string? FindRoot()
{
var candidates = new List<string>
{
Environment.GetEnvironmentVariable("GC_COURSEWARE_DIR") ?? "",
Path.Combine(AppContext.BaseDirectory, "courseware"),
Path.Combine(Directory.GetCurrentDirectory(), "courseware"),
};
try
{
var home = AppPaths.Discover().HomeRoot;
candidates.Add(Path.Combine(home, "courseware"));
}
catch { /* 目录探测失败时只看前两个候选 */ }
foreach (var dir in candidates)
if (File.Exists(Path.Combine(dir, "index.html"))) return dir;
return null;
}
private async Task ServeLoop()
{
while (!_disposed)
{
HttpListenerContext ctx;
try { ctx = await _listener.GetContextAsync(); }
catch { break; }
_ = Task.Run(() => Handle(ctx));
}
}
private void Handle(HttpListenerContext ctx)
{
try
{
var rel = Uri.UnescapeDataString(ctx.Request.Url!.AbsolutePath.TrimStart('/'));
if (string.IsNullOrEmpty(rel)) rel = "index.html";
rel = rel.Replace('/', Path.DirectorySeparatorChar);
// 规范化 + 越界检查:只允许读课件目录内的文件
var full = Path.GetFullPath(Path.Combine(_root, rel));
var rootFull = Path.GetFullPath(_root) + Path.DirectorySeparatorChar;
if (!full.StartsWith(rootFull, StringComparison.OrdinalIgnoreCase) ||
!File.Exists(full))
{
ctx.Response.StatusCode = 404;
ctx.Response.Close();
return;
}
var bytes = File.ReadAllBytes(full);
ctx.Response.ContentType = GuessMime(full);
ctx.Response.Headers.Add("Accept-Ranges", "bytes");
var range = ctx.Request.Headers["Range"];
if (!string.IsNullOrEmpty(range) &&
range.StartsWith("bytes=", StringComparison.OrdinalIgnoreCase) &&
range.Contains('-'))
{
var parts = range[6..].Split('-', 2);
long start = 0;
long end = bytes.Length - 1;
if (!string.IsNullOrEmpty(parts[0])) long.TryParse(parts[0], out start);
if (parts.Length > 1 && !string.IsNullOrEmpty(parts[1])) long.TryParse(parts[1], out end);
if (start >= 0 && start <= end && start < bytes.Length)
{
if (end >= bytes.Length) end = bytes.Length - 1;
var len = (int)(end - start + 1);
ctx.Response.StatusCode = 206;
ctx.Response.Headers.Add("Content-Range", $"bytes {start}-{end}/{bytes.Length}");
ctx.Response.ContentLength64 = len;
ctx.Response.OutputStream.Write(bytes, (int)start, len);
ctx.Response.Close();
return;
}
}
ctx.Response.ContentLength64 = bytes.Length;
ctx.Response.OutputStream.Write(bytes, 0, bytes.Length);
ctx.Response.Close();
}
catch
{
try { ctx.Response.Close(); } catch { /* 客户端已断开 */ }
}
}
private static string GuessMime(string path) => Path.GetExtension(path).ToLowerInvariant() switch
{
".html" or ".htm" => "text/html; charset=utf-8",
".css" => "text/css; charset=utf-8",
".js" => "application/javascript; charset=utf-8",
".json" => "application/json; charset=utf-8",
".jpg" or ".jpeg" => "image/jpeg",
".png" => "image/png",
".webp" => "image/webp",
".gif" => "image/gif",
".mp4" => "video/mp4",
_ => "application/octet-stream"
};
public void Dispose()
{
if (_disposed) return;
_disposed = true;
try { _listener.Stop(); _listener.Close(); } catch { /* 已关闭 */ }
}
}
@@ -156,10 +156,9 @@ public static class LauncherRuntimeInfo
}
/// <summary>
/// 界面(Flutter)与后端(GC.UI.Server)之间的约定:端口、环境变量名。
/// HTTP 后端(GC.UI.Server)的端口与令牌约定,供独立部署 / 外部客户端使用。
///
/// 之前这个端口在 GC-BOOT、后端、Flutter 前端各写了一遍 17890,改一处就断链;
/// 现在统一由这里定义,启动器选好端口后通过环境变量传给另外两边。
/// 主界面已改为进程内 Avalonia,不经过 HTTP;这些常量仅用于可选的独立后端进程。
/// </summary>
public static class GcUiContract
{
@@ -174,9 +173,9 @@ public static class GcUiContract
public const string PortEnvVar = "GC_UI_PORT";
/// <summary>
/// 启动器为本次会话生成的一次性令牌,经环境变量同时传给进程内后端与 Flutter 前端。
/// 前端每个请求都要带该令牌,后端据此确认对方是自己拉起的那个前端;
/// 同机伪装进程即便占了端口,也没有令牌,无法被前端当成后端复用。
/// 独立后端进程的一次性令牌,经环境变量传给 HTTP 客户端。
/// 客户端每个请求都要带该令牌,后端据此确认对方是自己拉起的;
/// 同机伪装进程即便占了端口,也没有令牌,无法被当成后端复用。
/// </summary>
public const string TokenEnvVar = "GC_UI_TOKEN";
File renamed without changes.
File renamed without changes.
+124
View File
@@ -0,0 +1,124 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Threading;
using GC.Views;
namespace GC.Services;
/// <summary>
/// 启动器更新的完整交互流程(「检查更新」与「重新下载启动器」共用):
/// 1. 关闭主窗口与所有模型窗口;
/// 2. 弹出圆角进度窗;
/// 3. 下载最新版到当前目录(与旧版并列);
/// 4. 安排替换脚本、关进度窗、退出进程。
/// 失败时恢复主窗口,继续使用当前版本。
/// </summary>
public static class LauncherUpdateFlow
{
private static bool _running;
public static bool IsRunning => _running;
public static async Task RunAsync(AppServices services, string title)
{
if (_running) return;
_running = true;
var desktop = Application.Current?.ApplicationLifetime
as IClassicDesktopStyleApplicationLifetime;
var mainWindow = desktop?.MainWindow;
var progressWindow = new UpdaterWindow(title);
try
{
// 1. 关闭所有窗口
if (desktop != null) desktop.MainWindow = null;
try { mainWindow?.Close(); } catch { }
foreach (var w in OpenWindows().ToList())
{
try { w.Close(); } catch { }
}
// 2. 进度窗
progressWindow.Show();
progressWindow.Report(0, "准备更新…");
await Dispatcher.UIThread.InvokeAsync(() => { }, DispatcherPriority.Render);
// 3. 下载
var progress = new Progress<UpdateProgressInfo>(p =>
progressWindow.Report(p.Value, p.Stage));
var result = await services.LauncherUpdates.DownloadAsync(
services.Paths, services.Updates.Remote, progress);
if (result.State == UpdateRunState.Failed)
{
progressWindow.Report(0, "更新失败", result.Message);
await Task.Delay(2200);
_running = false;
progressWindow.Close();
RestoreMainWindow(desktop, mainWindow);
return;
}
progressWindow.Report(1, $"v{result.Version} 下载完成,正在重启…");
// 4. 安排替换(下次启动生效 / 脚本接管重启)
var scheduled = services.LauncherUpdates.ScheduleApply(
services.Paths, result.PackageName ?? "");
if (!scheduled)
{
progressWindow.Report(0, "无法安排更新", "请检查安装目录是否可写");
await Task.Delay(2200);
_running = false;
progressWindow.Close();
RestoreMainWindow(desktop, mainWindow);
return;
}
await Task.Delay(400);
progressWindow.Close();
desktop?.Shutdown();
}
catch (Exception ex)
{
Console.Error.WriteLine($"更新流程异常: {ex}");
_running = false;
try { progressWindow.Close(); } catch { }
RestoreMainWindow(desktop, mainWindow);
}
}
private static void RestoreMainWindow(
IClassicDesktopStyleApplicationLifetime? desktop, Window? mainWindow)
{
if (desktop == null || mainWindow == null) return;
try
{
desktop.MainWindow = mainWindow;
mainWindow.Show();
mainWindow.Activate();
}
catch (Exception ex)
{
Console.Error.WriteLine($"恢复主窗口失败: {ex.Message}");
}
}
private static IEnumerable<Window> OpenWindows()
{
if (Application.Current?.ApplicationLifetime
is not IClassicDesktopStyleApplicationLifetime d)
yield break;
foreach (var w in d.Windows)
{
if (w is UpdaterWindow) continue;
yield return w;
}
}
}
@@ -4,6 +4,8 @@ using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Text.Json;
using Avalonia.Data;
using Avalonia.Markup.Xaml;
namespace GC.Services;
@@ -72,7 +74,7 @@ public sealed class L : INotifyPropertyChanged
{
try
{
// 界面已迁到 Flutter,这里不能再依赖 Avalonia 的 avares:// 资源加载
// 多语言表以嵌入资源方式加载(不依赖 avares:// 的外部文件)
var asm = typeof(L).Assembly;
using var stream = asm.GetManifestResourceStream($"GC.Core.Assets.i18n.{code}.json");
if (stream == null) return null;
@@ -130,3 +132,14 @@ public sealed class LocalizedString : INotifyPropertyChanged
internal void Refresh() => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Value)));
}
/// <summary>XAML 用法:Text="{loc:Loc nav.home}"</summary>
public sealed class LocExtension : MarkupExtension
{
public LocExtension() { }
public LocExtension(string key) => Key = key;
public string Key { get; set; } = "";
public override object ProvideValue(IServiceProvider serviceProvider)
=> new Binding(nameof(LocalizedString.Value)) { Source = L.I.For(Key) };
}
File renamed without changes.
+300
View File
@@ -0,0 +1,300 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Runtime.Loader;
using System.Threading.Tasks;
using Avalonia.Controls;
using GC.Models;
using GC.ModelSdk;
namespace GC.Services;
/// <summary>
/// 模型宿主:按清单加载模型自己的程序集,拿到模型自带的界面。
/// 启动器对“场景 / 行星 / 节气”一无所知,只认契约。
/// </summary>
public sealed class ModelHost
{
public const int SupportedApiVersion = 1;
private readonly AppPaths _paths;
private readonly SettingsService _settings;
private readonly MemoryBudget _memory;
public ModelHost(AppPaths paths, SettingsService settings, MemoryBudget memory)
{
_paths = paths;
_settings = settings;
_memory = memory;
}
/// <summary>同步加载(全部在 UI 线程,用于自检 / 命令行)。</summary>
public LoadedModel Load(ModelPackage package, Action requestClose, Action<double, string?>? progress = null)
{
var session = CreateSession(package, requestClose, progress);
try
{
session.Runtime.Prepare(session.Context);
var view = session.Runtime.CreateView(session.Context)
?? throw new InvalidOperationException("模型没有返回界面");
return session.Complete(view);
}
catch
{
session.Dispose();
throw;
}
}
/// <summary>
/// 异步加载:数据准备放在后台线程(<see cref="IModelRuntime.Prepare"/>),
/// 界面构建回到 UI 线程,进度通过 <paramref name="progress"/> 实时汇报。
/// </summary>
public async Task<LoadedModel> LoadAsync(ModelPackage package, Action requestClose,
Action<double, string?>? progress = null)
{
var session = CreateSession(package, requestClose, progress);
try
{
await Task.Run(() => session.Runtime.Prepare(session.Context)).ConfigureAwait(true);
var view = session.Runtime.CreateView(session.Context)
?? throw new InvalidOperationException("模型没有返回界面");
return session.Complete(view);
}
catch
{
session.Dispose();
throw;
}
}
private Session CreateSession(ModelPackage package, Action requestClose, Action<double, string?>? progress)
{
// ---- 契约协商 -------------------------------------------------------
// 先做廉价检查:不满足就直接拒绝,避免加载了才发现不兼容。
var declaredApi = package.Manifest.ApiVersion;
if (declaredApi < 1)
throw new InvalidOperationException($"模型清单的 apiVersion 非法: {declaredApi}");
if (declaredApi > SupportedApiVersion)
throw new InvalidOperationException(
$"该模型需要更新的启动器(模型契约 v{declaredApi},当前支持 v{SupportedApiVersion})。" +
"请先更新启动器,或让模型作者发布兼容版本。");
var minApp = package.Manifest.MinAppVersion;
if (!string.IsNullOrWhiteSpace(minApp) &&
CompareVersions(LauncherRuntimeInfo.CurrentLauncherVersion, minApp!) < 0)
throw new InvalidOperationException(
$"该模型要求启动器 ≥ v{minApp},当前为 v{LauncherRuntimeInfo.CurrentLauncherVersion}");
// ---- 完整性:dll 会被直接执行,加载前必须确认它没被改过 ----------------
var integrity = ModelIntegrity.VerifyForLoad(package.Directory, package.Id);
if (!integrity.Ok)
{
var message = $"模型完整性校验失败({package.Id}):{integrity.Message}。" +
"请删除该模型目录让启动器重新下载。";
if (Environment.GetEnvironmentVariable("GC_ALLOW_TAMPERED_MODELS") == "1")
Console.Error.WriteLine("[warn] " + message + "(已按 GC_ALLOW_TAMPERED_MODELS 放行)");
else
throw new InvalidOperationException(message);
}
else if (!integrity.Present && Environment.GetEnvironmentVariable("GC_STRICT_MODELS") == "1")
{
throw new InvalidOperationException(
$"模型缺少完整性记录({package.Id}),严格模式下拒绝加载");
}
var assemblyPath = package.AssemblyPath;
if (!File.Exists(assemblyPath))
throw new FileNotFoundException($"模型缺少功能程序集:{assemblyPath}", assemblyPath);
var directory = Path.GetDirectoryName(assemblyPath)!;
var context = new ModelLoadContext(directory);
try
{
var assembly = context.LoadFromAssemblyPath(assemblyPath);
var type = ResolveFactoryType(assembly, package.Manifest.Type);
if (type == null)
throw new InvalidOperationException("模型程序集里没有找到 IModelFactory 实现");
if (Activator.CreateInstance(type) is not IModelFactory factory)
throw new InvalidOperationException($"无法创建模型入口:{type.FullName}");
if (factory.ApiVersion != SupportedApiVersion)
throw new InvalidOperationException(
$"模型程序集的契约版本为 v{factory.ApiVersion},启动器支持 v{SupportedApiVersion};" +
"请更新到匹配的版本");
var runtime = factory.Create();
var modelContext = new ModelContext(package, L.I.Language, _memory.BudgetMb, requestClose, progress);
return new Session(context, runtime, modelContext);
}
catch
{
context.Unload();
throw;
}
}
private static Type? ResolveFactoryType(Assembly assembly, string? typeName)
{
if (!string.IsNullOrWhiteSpace(typeName))
{
var exact = assembly.GetType(typeName!, throwOnError: false);
if (exact != null) return exact;
}
foreach (var type in assembly.GetTypes())
{
if (type.IsAbstract || type.IsInterface) continue;
if (typeof(IModelFactory).IsAssignableFrom(type)) return type;
}
return null;
}
/// <summary>比较 1.0.10 与 1.0.9 这类版本号(按数字段比较,不按字符串)。</summary>
private static int CompareVersions(string left, string right)
{
static int[] Parts(string value)
{
var text = value.Trim().TrimStart('v', 'V');
var pieces = text.Split('.');
var numbers = new int[Math.Max(4, pieces.Length)];
for (var i = 0; i < pieces.Length; i++)
{
var digits = new string(Array.FindAll(pieces[i].ToCharArray(), char.IsDigit));
if (digits.Length > 6) digits = digits[..6];
numbers[i] = int.TryParse(digits, out var n) ? n : 0;
}
return numbers;
}
var a = Parts(left);
var b = Parts(right);
for (var i = 0; i < Math.Max(a.Length, b.Length); i++)
{
var x = i < a.Length ? a[i] : 0;
var y = i < b.Length ? b[i] : 0;
if (x != y) return x < y ? -1 : 1;
}
return 0;
}
private sealed class Session : IDisposable
{
private readonly ModelLoadContext _context;
public Session(ModelLoadContext context, IModelRuntime runtime, ModelContext modelContext)
{
_context = context;
Runtime = runtime;
Context = modelContext;
}
public IModelRuntime Runtime { get; }
public ModelContext Context { get; }
public LoadedModel Complete(Control view) => new(_context, Runtime, view);
public void Dispose()
{
try { Runtime.Dispose(); } catch (Exception ex) { Console.Error.WriteLine($"释放模型失败: {ex.Message}"); }
try { _context.Unload(); } catch (Exception ex) { Console.Error.WriteLine($"卸载模型程序集失败: {ex.Message}"); }
}
}
}
/// <summary>一次性模型实例:窗口关闭后释放视图、卸载程序集。</summary>
public sealed class LoadedModel : IDisposable
{
private readonly ModelLoadContext _context;
private readonly IModelRuntime _runtime;
private bool _disposed;
public LoadedModel(ModelLoadContext context, IModelRuntime runtime, Control view)
{
_context = context;
_runtime = runtime;
View = view;
}
public Control View { get; }
public void Dispose()
{
if (_disposed) return;
_disposed = true;
// 顺序:先释放视图(停计时器/Dispose 位图),再释放运行时,最后卸载程序集。
// 否则视图里的事件订阅会继续持有 ALC 内的类型,collectible 上下文无法回收。
try { (View as IDisposable)?.Dispose(); }
catch (Exception ex) { Console.Error.WriteLine($"释放模型视图失败: {ex.Message}"); }
try { _runtime.Dispose(); } catch (Exception ex) { Console.Error.WriteLine($"释放模型失败: {ex.Message}"); }
try { _context.Unload(); } catch (Exception ex) { Console.Error.WriteLine($"卸载模型程序集失败: {ex.Message}"); }
}
}
/// <summary>模型程序集加载上下文:契约与 Avalonia 一律回到默认上下文,保证类型一致。</summary>
public sealed class ModelLoadContext : AssemblyLoadContext
{
private static readonly HashSet<string> Shared = new(StringComparer.OrdinalIgnoreCase)
{
"GC.ModelSdk",
"Avalonia",
"Avalonia.Base",
"Avalonia.Controls",
"Avalonia.Desktop",
"Avalonia.Skia",
"Avalonia.Themes.Fluent",
"SkiaSharp",
"HarfBuzzSharp"
};
private readonly string _directory;
public ModelLoadContext(string directory) : base("model:" + Path.GetFileName(directory), isCollectible: true)
=> _directory = directory;
protected override Assembly? Load(AssemblyName assemblyName)
{
var name = assemblyName.Name;
if (string.IsNullOrEmpty(name)) return null;
if (Shared.Contains(name)) return null; // 用启动器已加载的那份
if (name.StartsWith("System.", StringComparison.OrdinalIgnoreCase)) return null;
if (name is "System" or "netstandard" or "mscorlib") return null;
var candidate = Path.Combine(_directory, name + ".dll");
return File.Exists(candidate) ? LoadFromAssemblyPath(candidate) : null;
}
}
/// <summary>启动器提供给模型的环境。</summary>
public sealed class ModelContext : IModelContext
{
private readonly Action _requestClose;
private readonly Action<double, string?>? _progress;
public ModelContext(ModelPackage package, string language, int memoryMb, Action requestClose,
Action<double, string?>? progress)
{
_progress = progress;
ModelId = package.Id;
ModelDirectory = package.Directory;
DataDirectory = package.DataDirectory;
Language = language;
MemoryBudgetMb = memoryMb;
_requestClose = requestClose;
}
public string ModelId { get; }
public string ModelDirectory { get; }
public string DataDirectory { get; }
public string Language { get; }
public int MemoryBudgetMb { get; }
public void RequestClose() => _requestClose();
public void ReportProgress(double value, string? message = null) => _progress?.Invoke(value, message);
public void Log(string message) => Console.WriteLine(message);
}
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
+325
View File
@@ -0,0 +1,325 @@
<Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Styles.Resources>
<SolidColorBrush x:Key="AppBg" Color="#F4F6FB" />
<SolidColorBrush x:Key="Surface" Color="#FFFFFF" />
<SolidColorBrush x:Key="SurfaceAlt" Color="#F7F9FE" />
<SolidColorBrush x:Key="Line" Color="#E3E8F3" />
<SolidColorBrush x:Key="LineStrong" Color="#D2DAEA" />
<SolidColorBrush x:Key="Ink" Color="#111A2E" />
<SolidColorBrush x:Key="InkDim" Color="#5B6A86" />
<SolidColorBrush x:Key="InkFaint" Color="#8A97B1" />
<SolidColorBrush x:Key="Accent" Color="#2F6BFF" />
<SolidColorBrush x:Key="AccentDark" Color="#1F4FD0" />
<SolidColorBrush x:Key="AccentSoft" Color="#EAF1FF" />
<SolidColorBrush x:Key="SideBg" Color="#0D1526" />
<SolidColorBrush x:Key="SideLine" Color="#1B2740" />
<SolidColorBrush x:Key="SideInk" Color="#A9B8D4" />
<SolidColorBrush x:Key="Success" Color="#1F9D6B" />
<SolidColorBrush x:Key="Danger" Color="#D64545" />
<SolidColorBrush x:Key="Warn" Color="#D98613" />
<LinearGradientBrush x:Key="HeroBg" StartPoint="0%,0%" EndPoint="100%,100%">
<GradientStop Color="#12203C" Offset="0" />
<GradientStop Color="#1A3057" Offset="0.55" />
<GradientStop Color="#0E1A31" Offset="1" />
</LinearGradientBrush>
<LinearGradientBrush x:Key="TitleBarBg" StartPoint="0%,0%" EndPoint="100%,100%">
<GradientStop Color="#101C33" Offset="0" />
<GradientStop Color="#0B1322" Offset="1" />
</LinearGradientBrush>
<LinearGradientBrush x:Key="SideBgBrush" StartPoint="0%,0%" EndPoint="0%,100%">
<GradientStop Color="#0E1729" Offset="0" />
<GradientStop Color="#0A1120" Offset="1" />
</LinearGradientBrush>
</Styles.Resources>
<Style Selector="Window">
<Setter Property="FontSize" Value="13" />
<Setter Property="Foreground" Value="{DynamicResource Ink}" />
</Style>
<!-- 文本 -->
<Style Selector="TextBlock.h1">
<Setter Property="FontSize" Value="26" />
<Setter Property="FontWeight" Value="SemiBold" />
<Setter Property="Foreground" Value="{DynamicResource Ink}" />
</Style>
<Style Selector="TextBlock.h2">
<Setter Property="FontSize" Value="16" />
<Setter Property="FontWeight" Value="SemiBold" />
<Setter Property="Foreground" Value="{DynamicResource Ink}" />
</Style>
<Style Selector="TextBlock.h3">
<Setter Property="FontSize" Value="13.5" />
<Setter Property="FontWeight" Value="SemiBold" />
<Setter Property="Foreground" Value="{DynamicResource Ink}" />
</Style>
<Style Selector="TextBlock.muted">
<Setter Property="FontSize" Value="12" />
<Setter Property="Foreground" Value="{DynamicResource InkDim}" />
</Style>
<Style Selector="TextBlock.faint">
<Setter Property="FontSize" Value="11.5" />
<Setter Property="Foreground" Value="{DynamicResource InkFaint}" />
</Style>
<Style Selector="TextBlock.eyebrow">
<Setter Property="FontSize" Value="11" />
<Setter Property="FontWeight" Value="SemiBold" />
<Setter Property="Foreground" Value="{DynamicResource InkFaint}" />
</Style>
<Style Selector="TextBlock.onDark">
<Setter Property="Foreground" Value="#EAF1FF" />
</Style>
<Style Selector="TextBlock.onDarkDim">
<Setter Property="Foreground" Value="#9DB0D0" />
</Style>
<!-- 容器 -->
<!-- 容器:卡片悬停浮起,阴影与位移都有过渡 -->
<Style Selector="Border.card">
<Setter Property="Background" Value="{DynamicResource Surface}" />
<Setter Property="BorderBrush" Value="{DynamicResource Line}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="CornerRadius" Value="16" />
<Setter Property="Transitions">
<Transitions>
<BoxShadowsTransition Property="BoxShadow" Duration="0:0:0.2" />
<BrushTransition Property="BorderBrush" Duration="0:0:0.2" />
<TransformOperationsTransition Property="RenderTransform" Duration="0:0:0.2" />
</Transitions>
</Setter>
</Style>
<Style Selector="Border.card:pointerover">
<Setter Property="BoxShadow" Value="0 10 26 0 #1A213C70" />
<Setter Property="BorderBrush" Value="{DynamicResource LineStrong}" />
<Setter Property="RenderTransform" Value="translateY(-2px)" />
</Style>
<Style Selector="Border.panel">
<Setter Property="Background" Value="{DynamicResource SurfaceAlt}" />
<Setter Property="BorderBrush" Value="{DynamicResource Line}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="CornerRadius" Value="12" />
</Style>
<Style Selector="Border.hero">
<Setter Property="Background" Value="{DynamicResource HeroBg}" />
<Setter Property="CornerRadius" Value="20" />
<Setter Property="BoxShadow" Value="0 12 32 0 #1A0B1A3A" />
</Style>
<Style Selector="Border.chip">
<Setter Property="Background" Value="{DynamicResource AccentSoft}" />
<Setter Property="CornerRadius" Value="999" />
<Setter Property="Padding" Value="8,2" />
</Style>
<Style Selector="Border.tag">
<Setter Property="Background" Value="#F0F3FA" />
<Setter Property="CornerRadius" Value="6" />
<Setter Property="Padding" Value="7,2" />
</Style>
<!-- ===================================================================
按钮(重写版)
原则:只通过 Button 自身的 Background/Foreground/BorderBrush + 伪类
设置来换色,一律不覆盖 /template/ ContentPresenter 的属性,也不使用
RenderTransform 动画。FluentTheme 的按钮模板通过 TemplateBinding 读取
这些属性,混用「Button 属性」与「模板内部元素属性」会在 hover 状态
切换时互相覆盖,造成光标移动时的渲染错乱。
所有过渡都是纯画刷过渡(BrushTransition),类型固定,不会转换失败。
=================================================================== -->
<Style Selector="Button">
<Setter Property="FontSize" Value="13" />
<Setter Property="Padding" Value="14,7" />
<Setter Property="MinHeight" Value="34" />
<Setter Property="CornerRadius" Value="9" />
<Setter Property="Background" Value="{DynamicResource Surface}" />
<Setter Property="BorderBrush" Value="{DynamicResource LineStrong}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="Foreground" Value="{DynamicResource Ink}" />
<Setter Property="HorizontalContentAlignment" Value="Center" />
<Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="Cursor" Value="Hand" />
<Setter Property="Transitions">
<Transitions>
<BrushTransition Property="Background" Duration="0:0:0.13" />
<BrushTransition Property="BorderBrush" Duration="0:0:0.13" />
<BrushTransition Property="Foreground" Duration="0:0:0.13" />
</Transitions>
</Setter>
</Style>
<!-- 通用 hover / pressed(纯色,无变换) -->
<Style Selector="Button:pointerover">
<Setter Property="Background" Value="#EDF2FC" />
<Setter Property="BorderBrush" Value="#BAC9E6" />
</Style>
<Style Selector="Button:pressed">
<Setter Property="Background" Value="#DDE7F8" />
<Setter Property="BorderBrush" Value="#9FB4DD" />
</Style>
<!-- 主要按钮 -->
<Style Selector="Button.primary">
<Setter Property="Background" Value="{DynamicResource Accent}" />
<Setter Property="BorderBrush" Value="{DynamicResource Accent}" />
<Setter Property="Foreground" Value="White" />
</Style>
<Style Selector="Button.primary:pointerover">
<Setter Property="Background" Value="{DynamicResource AccentDark}" />
<Setter Property="BorderBrush" Value="{DynamicResource AccentDark}" />
<Setter Property="Foreground" Value="White" />
</Style>
<Style Selector="Button.primary:pressed">
<Setter Property="Background" Value="#183FA8" />
<Setter Property="BorderBrush" Value="#183FA8" />
<Setter Property="Foreground" Value="White" />
</Style>
<!-- 幽灵按钮 -->
<Style Selector="Button.ghost">
<Setter Property="Background" Value="Transparent" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="BorderBrush" Value="Transparent" />
<Setter Property="Foreground" Value="{DynamicResource InkDim}" />
</Style>
<Style Selector="Button.ghost:pointerover">
<Setter Property="Background" Value="#EEF2FA" />
<Setter Property="Foreground" Value="{DynamicResource Ink}" />
</Style>
<Style Selector="Button.ghost:pressed">
<Setter Property="Background" Value="#E2E9F6" />
</Style>
<!-- 危险按钮 -->
<Style Selector="Button.danger">
<Setter Property="Foreground" Value="{DynamicResource Danger}" />
</Style>
<Style Selector="Button.danger:pointerover">
<Setter Property="Background" Value="#FDECEC" />
<Setter Property="Foreground" Value="{DynamicResource Danger}" />
</Style>
<Style Selector="Button.danger:pressed">
<Setter Property="Background" Value="#F8DADA" />
</Style>
<!-- 深色背景上的按钮 -->
<Style Selector="Button.onDark">
<Setter Property="Background" Value="#1B2740" />
<Setter Property="BorderBrush" Value="#2A3A57" />
<Setter Property="Foreground" Value="#DCE7FA" />
</Style>
<Style Selector="Button.onDark:pointerover">
<Setter Property="Background" Value="#233351" />
<Setter Property="BorderBrush" Value="#3A4E75" />
</Style>
<Style Selector="Button.onDark:pressed">
<Setter Property="Background" Value="#2B3D60" />
</Style>
<Style Selector="Button.onDark.active">
<Setter Property="Background" Value="{DynamicResource Accent}" />
<Setter Property="BorderBrush" Value="{DynamicResource Accent}" />
<Setter Property="Foreground" Value="White" />
</Style>
<Style Selector="Button.small">
<Setter Property="FontSize" Value="12" />
<Setter Property="Padding" Value="10,4" />
<Setter Property="MinHeight" Value="28" />
<Setter Property="CornerRadius" Value="8" />
</Style>
<!-- 侧栏导航(主页 / 下载 / 设置) -->
<Style Selector="Button.nav">
<Setter Property="HorizontalAlignment" Value="Stretch" />
<Setter Property="HorizontalContentAlignment" Value="Left" />
<Setter Property="Background" Value="Transparent" />
<Setter Property="BorderBrush" Value="Transparent" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="Foreground" Value="{DynamicResource SideInk}" />
<Setter Property="Padding" Value="14,10" />
<Setter Property="CornerRadius" Value="10" />
<Setter Property="FontSize" Value="13.5" />
<Setter Property="MinHeight" Value="40" />
</Style>
<Style Selector="Button.nav:pointerover">
<Setter Property="Background" Value="#16213A" />
<Setter Property="Foreground" Value="#E8EFFF" />
</Style>
<Style Selector="Button.nav:pressed">
<Setter Property="Background" Value="#1E2C49" />
</Style>
<Style Selector="Button.nav.active">
<Setter Property="Background" Value="#1C2C4C" />
<Setter Property="Foreground" Value="#FFFFFF" />
<Setter Property="BorderBrush" Value="{DynamicResource Accent}" />
<Setter Property="BorderThickness" Value="3,0,0,0" />
</Style>
<Style Selector="Button.nav.active:pointerover">
<Setter Property="Background" Value="#22355A" />
<Setter Property="Foreground" Value="#FFFFFF" />
</Style>
<!-- 输入 -->
<Style Selector="TextBox">
<Setter Property="CornerRadius" Value="9" />
<Setter Property="Padding" Value="11,8" />
<Setter Property="MinHeight" Value="36" />
<Setter Property="FontSize" Value="12.5" />
<Setter Property="Background" Value="{DynamicResource Surface}" />
<Setter Property="BorderBrush" Value="{DynamicResource LineStrong}" />
</Style>
<Style Selector="ComboBox">
<Setter Property="CornerRadius" Value="9" />
<Setter Property="MinHeight" Value="34" />
<Setter Property="FontSize" Value="12.5" />
<Setter Property="Padding" Value="10,4" />
</Style>
<Style Selector="ProgressBar">
<Setter Property="Height" Value="5" />
<Setter Property="CornerRadius" Value="3" />
<Setter Property="MinHeight" Value="5" />
</Style>
<Style Selector="CheckBox">
<Setter Property="FontSize" Value="12.5" />
</Style>
<!-- ===================================================================
自建标题栏按钮(最小化 − / 关闭 ✕)
同样只用纯画刷换色,绝不设置 RenderTransform;
且用更高优先级覆盖上面通用的 :pointerover / :pressed,
避免深色标题栏上出现浅色 hover 背景。
=================================================================== -->
<Style Selector="Button.titlebtn">
<Setter Property="Width" Value="38" />
<Setter Property="Height" Value="30" />
<Setter Property="Background" Value="Transparent" />
<Setter Property="Foreground" Value="#A9B8D4" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="BorderBrush" Value="Transparent" />
<Setter Property="FontSize" Value="13" />
<Setter Property="HorizontalContentAlignment" Value="Center" />
<Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="CornerRadius" Value="7" />
<Setter Property="Margin" Value="2,0" />
</Style>
<Style Selector="Button.titlebtn:pointerover">
<Setter Property="Background" Value="#223252" />
<Setter Property="BorderBrush" Value="Transparent" />
<Setter Property="Foreground" Value="#FFFFFF" />
</Style>
<Style Selector="Button.titlebtn:pressed">
<Setter Property="Background" Value="#2C4270" />
<Setter Property="Foreground" Value="#FFFFFF" />
</Style>
<Style Selector="Button.titlebtn.close:pointerover">
<Setter Property="Background" Value="#D64545" />
<Setter Property="Foreground" Value="#FFFFFF" />
</Style>
<Style Selector="Button.titlebtn.close:pressed">
<Setter Property="Background" Value="#B93737" />
<Setter Property="Foreground" Value="#FFFFFF" />
</Style>
</Styles>
+104
View File
@@ -0,0 +1,104 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using GC.Services;
namespace GC.ViewModels;
/// <summary>「关于」页面:版本号 + 开发者(读取仓库 contributors)。</summary>
public partial class AboutViewModel : ObservableObject
{
private readonly AppServices _services;
private bool _loaded;
public ObservableCollection<ContributorItem> Contributors { get; } = new();
[ObservableProperty] private bool _isLoading = true;
[ObservableProperty] private string _statusText = "";
[ObservableProperty] private bool _hasContributors;
public AboutViewModel(AppServices services)
{
_services = services;
LoadCommand = new AsyncRelayCommand(() => LoadAsync(force: true));
}
public string AppName => "Morris GC";
/// <summary>启动器版本号,如 v1.0.2。</summary>
public string VersionText => "v" + LauncherRuntimeInfo.CurrentLauncherVersion;
/// <summary>当前平台标识,如 win-x64 / osx-arm64。</summary>
public string PlatformText => LauncherRuntimeInfo.CurrentRid;
public string RepositoryText => _services.Settings.Current.UpdateRepository;
public string ContributorsTitle => "开发者";
public IAsyncRelayCommand LoadCommand { get; }
/// <summary>每次进入页面时调用(首次才真正联网拉取)。</summary>
public void OnShown()
{
if (_loaded) return;
_ = LoadAsync(force: false);
}
private async Task LoadAsync(bool force)
{
if (_loaded && !force) return;
_loaded = true;
IsLoading = true;
StatusText = "正在读取贡献者…";
try
{
var list = await ContributorsService.FetchAsync(_services.Settings.Current.UpdateRepository);
Contributors.Clear();
foreach (var c in list)
Contributors.Add(new ContributorItem(c));
HasContributors = Contributors.Count > 0;
StatusText = HasContributors ? $"{Contributors.Count} 位贡献者" : "暂无贡献者信息";
}
catch (Exception ex)
{
StatusText = "读取失败:" + ex.Message;
}
finally
{
IsLoading = false;
}
}
[RelayCommand]
private void OpenRepository() => Shell.OpenUrl(RepositoryText);
/// <summary>重新下载启动器:关闭所有窗口,进度窗下载新版,完成后重启。</summary>
[RelayCommand]
private async System.Threading.Tasks.Task ReinstallLauncher()
{
if (LauncherUpdateFlow.IsRunning) return;
await LauncherUpdateFlow.RunAsync(_services, "正在重新下载启动器");
}
}
/// <summary>一位贡献者的展示项。</summary>
public sealed class ContributorItem
{
public ContributorItem(Contributor c)
{
Name = c.DisplayName;
Contributions = c.Contributions;
AvatarUrl = c.AvatarUrl;
}
public string Name { get; }
public int Contributions { get; }
public string? AvatarUrl { get; }
public string ContributionsText => $"{Contributions} 次提交";
public bool HasAvatar => !string.IsNullOrWhiteSpace(AvatarUrl);
}
+411
View File
@@ -0,0 +1,411 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using GC.Models;
using GC.Services;
namespace GC.ViewModels;
public partial class DownloadViewModel : ObservableObject
{
private readonly AppServices _services;
private readonly MainViewModel _main;
private bool _initialized;
// 每次切源取消上一次加载,并用 generation 序号丢弃过期结果,避免并发写 Models 集合
private CancellationTokenSource? _loadCts;
private int _loadGeneration;
public ObservableCollection<SourceItemViewModel> Sources { get; } = new();
public ObservableCollection<RemoteModelRowViewModel> Models { get; } = new();
public ObservableCollection<IDownloadJob> Jobs => _services.Downloads.Jobs;
[ObservableProperty] private SourceItemViewModel? _selectedSource;
[ObservableProperty] private string _importUrl = "";
[ObservableProperty] private bool _isBusy;
[ObservableProperty] private string _statusMessage = "";
[ObservableProperty] private bool _hasModels;
[ObservableProperty] private bool _isBackgroundOpen = true;
[ObservableProperty] private string _jobSummary = "";
[ObservableProperty] private bool _hasJobs;
[ObservableProperty] private bool _isSourceEmpty;
public DownloadViewModel(AppServices services, MainViewModel main)
{
_services = services;
_main = main;
Jobs.CollectionChanged += OnJobsChanged;
foreach (var job in Jobs) job.PropertyChanged += OnJobPropertyChanged;
L.I.LanguageChanged += RefreshLanguage;
RebuildSources();
UpdateJobState();
}
public string BackgroundTitle => L.I["dl.background"];
public string ImportHint => L.I["dl.hint"];
// ------------------------------------------------------------ 页面生命周期
public void OnShown()
{
if (_initialized) return;
_initialized = true;
if (SelectedSource == null)
SelectedSource = Sources.FirstOrDefault(s => s.Model.Enabled && !string.IsNullOrWhiteSpace(s.Model.Url))
?? Sources.FirstOrDefault();
}
// ------------------------------------------------------------ 模型源
private void RebuildSources()
{
var keepId = SelectedSource?.Model.Id;
Sources.Clear();
foreach (var source in _services.Settings.Current.Sources)
Sources.Add(new SourceItemViewModel(source, this, _services));
SelectedSource = Sources.FirstOrDefault(s => s.Model.Id == keepId) ?? SelectedSource;
}
partial void OnSelectedSourceChanged(SourceItemViewModel? value)
{
if (value == null) return;
if (string.IsNullOrWhiteSpace(value.Model.Url))
{
Models.Clear();
HasModels = false;
IsSourceEmpty = true;
StatusMessage = L.I["dl.pickSource"];
return;
}
_ = LoadAsync(value, force: false);
}
internal void OnSourceEnabledChanged(SourceItemViewModel source)
{
if (!source.Model.Enabled && SelectedSource == source) Models.Clear();
}
internal void RemoveSource(SourceItemViewModel source)
{
if (source.Model.BuiltIn) return; // 内置默认源不允许删除
_services.Settings.Current.Sources.Remove(source.Model);
_services.Settings.Save();
var wasSelected = SelectedSource == source;
Sources.Remove(source);
if (wasSelected)
{
SelectedSource = Sources.FirstOrDefault();
if (SelectedSource == null)
{
Models.Clear();
HasModels = false;
}
}
}
/// <summary>
/// 只允许两个内置源(Xhmcl / GitCode),不再接受任意地址。
/// 旧的「自定义源」入口统一改为:按测速结果切换到更快的那个源。
/// </summary>
[RelayCommand]
private async Task ImportAsync()
{
var fastest = await _services.Selector.PickFastestAsync(force: true);
var target = Sources.FirstOrDefault(x =>
SourcePreset.Find(fastest.Id) != null &&
SourcePreset.Detect(x.Model.Url).Id == fastest.Id);
if (target == null)
{
StatusMessage = "没有可用的下载源";
return;
}
SelectedSource = target;
var lat = _services.Selector.LastLatency;
StatusMessage = $"已切换到 {fastest.Name}" +
(lat.Count > 0 ? "(" + string.Join(",", lat.Select(kv =>
$"{SourcePreset.Find(kv.Key)?.Name ?? kv.Key} {kv.Value}ms")) + ")" : "");
await LoadAsync(target, force: true);
}
private static string DeriveName(string url)
{
var trimmed = url.TrimEnd('/', '\\');
var slash = trimmed.LastIndexOfAny(new[] { '/', '\\' });
var name = slash >= 0 ? trimmed[(slash + 1)..] : trimmed;
if (name.EndsWith(".git", StringComparison.OrdinalIgnoreCase)) name = name[..^4];
if (name.EndsWith(".zip", StringComparison.OrdinalIgnoreCase)) name = name[..^4];
return string.IsNullOrWhiteSpace(name) ? url : name;
}
[RelayCommand]
private async Task RefreshAsync()
{
if (SelectedSource == null) return;
await LoadAsync(SelectedSource, force: true);
}
internal async Task RefreshFromSource(SourceItemViewModel source)
{
SelectedSource = source;
await LoadAsync(source, force: true);
}
private async Task LoadAsync(SourceItemViewModel source, bool force)
{
if (!source.Model.Enabled) return;
// 取消上一次尚未完成的加载,避免快速切换源时并发 Clear/写入同一集合
_loadCts?.Cancel();
_loadCts?.Dispose();
_loadCts = new CancellationTokenSource();
var ct = _loadCts.Token;
var generation = ++_loadGeneration;
IsBusy = true;
StatusMessage = L.I["dl.syncing"];
try
{
// 第 6 项:下载页与启动更新用同一个源、同一种下载方式。
// 每次加载前先让选择器给出最快源(有缓存,不会真的每次都测)。
try
{
var fastest = await _services.Selector.PickFastestAsync(false, ct);
if (fastest.Id != SourcePreset.Detect(source.Model.Url).Id)
{
var prefer = Sources.FirstOrDefault(x =>
SourcePreset.Detect(x.Model.Url).Id == fastest.Id && x.Model.Enabled);
if (prefer != null && prefer != source)
{
SelectedSource = prefer;
source = prefer;
}
}
}
catch { /* 测速失败就沿用当前源 */ }
var index = await _services.Sources.FetchAsync(source.Model, force, null, ct);
// 只有「仍是当前选中源 + 仍是最新一次加载」才可以写 UI 集合
if (ct.IsCancellationRequested || generation != _loadGeneration || SelectedSource != source)
return;
if (index.Error != null)
{
Models.Clear();
HasModels = false;
IsSourceEmpty = true;
StatusMessage = DescribeError(index.Error);
return;
}
var installedIds = new HashSet<string>(
_services.Models.Scan().Select(p => p.Id), StringComparer.OrdinalIgnoreCase);
Models.Clear();
foreach (var model in index.Models)
{
Models.Add(new RemoteModelRowViewModel(model, source,
installedIds.Contains(model.Id), DownloadCommand));
}
HasModels = Models.Count > 0;
IsSourceEmpty = Models.Count == 0;
StatusMessage = index.FromCache
? $"{L.I.F("dl.ready", Models.Count)} · {L.I["dl.fromCache"]}"
: L.I.F("dl.ready", Models.Count);
}
catch (OperationCanceledException)
{
// 被更新的加载取代或页面关闭:忽略,不覆盖新结果
}
catch (Exception ex)
{
if (!ct.IsCancellationRequested) StatusMessage = ex.Message;
}
finally
{
// 只有最后一次加载才复位 Busy,避免旧任务把新任务的忙碌状态清掉
if (generation == _loadGeneration) IsBusy = false;
}
}
private static string DescribeError(string error)
{
if (error.StartsWith("dl.", StringComparison.Ordinal))
{
var text = L.I[error];
return text == error ? error : text;
}
return error;
}
// ------------------------------------------------------------ 下载
[RelayCommand]
private async Task DownloadAsync(RemoteModelRowViewModel row)
{
if (row == null) return;
row.RowOpacity = 0;
row.RowHeight = 0;
IsBackgroundOpen = true;
_services.Downloads.Enqueue(row.Model);
await Task.Delay(240);
Models.Remove(row);
HasModels = Models.Count > 0;
IsSourceEmpty = Models.Count == 0;
}
[RelayCommand]
private void CancelJob(IDownloadJob? job)
{
if (job != null) _services.Downloads.Cancel(job);
}
[RelayCommand]
private void RetryJob(IDownloadJob? job)
{
if (job != null) _services.Downloads.Retry(job);
}
[RelayCommand]
private void RemoveJob(IDownloadJob? job)
{
if (job != null) _services.Downloads.Remove(job);
}
[RelayCommand]
private void ClearFinished() => _services.Downloads.ClearFinished();
[RelayCommand]
private void ToggleBackground() => IsBackgroundOpen = !IsBackgroundOpen;
// ------------------------------------------------------------ 任务展示
private void OnJobsChanged(object? sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null)
foreach (IDownloadJob job in e.NewItems) job.PropertyChanged += OnJobPropertyChanged;
if (e.OldItems != null)
foreach (IDownloadJob job in e.OldItems) job.PropertyChanged -= OnJobPropertyChanged;
UpdateJobState();
}
private void OnJobPropertyChanged(object? sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(IDownloadJob.State))
{
if (sender is IDownloadJob { State: DownloadState.Completed })
_services.Models.NotifyChanged();
}
UpdateJobState();
}
private void UpdateJobState()
{
HasJobs = Jobs.Count > 0;
JobSummary = $"{L.I["dl.background"]} ({Jobs.Count})";
OnPropertyChanged(nameof(JobSummary));
}
private void RefreshLanguage()
{
foreach (var source in Sources) source.RefreshLanguage();
foreach (var model in Models) model.RefreshLanguage();
foreach (var job in Jobs) job.RefreshText();
OnPropertyChanged(nameof(BackgroundTitle));
OnPropertyChanged(nameof(ImportHint));
UpdateJobState();
}
}
public partial class SourceItemViewModel : ObservableObject
{
private readonly DownloadViewModel _owner;
private readonly AppServices _services;
public ModelSource Model { get; }
public SourceItemViewModel(ModelSource model, DownloadViewModel owner, AppServices services)
{
Model = model;
_owner = owner;
_services = services;
RemoveCommand = new RelayCommand(() => _owner.RemoveSource(this));
RefreshCommand = new AsyncRelayCommand(async () => await _owner.RefreshFromSource(this));
}
public string Name => string.IsNullOrWhiteSpace(Model.Name) ? Model.Id : Model.Name;
public string HostText => string.IsNullOrWhiteSpace(Model.Url) ? L.I["dl.noSource"] : Model.DisplayHost;
public bool HasUrl => !string.IsNullOrWhiteSpace(Model.Url);
/// <summary>内置默认源不可删除(下载页隐藏删除按钮)。</summary>
public bool CanRemove => !Model.BuiltIn;
public bool Enabled
{
get => Model.Enabled;
set
{
if (Model.Enabled == value) return;
Model.Enabled = value;
_services.Settings.Save();
OnPropertyChanged();
_owner.OnSourceEnabledChanged(this);
}
}
public ICommand RemoveCommand { get; }
public ICommand RefreshCommand { get; }
public void RefreshLanguage()
{
OnPropertyChanged(nameof(Name));
OnPropertyChanged(nameof(HostText));
}
}
public partial class RemoteModelRowViewModel : ObservableObject
{
public RemoteModel Model { get; }
public SourceItemViewModel Source { get; }
public RemoteModelRowViewModel(RemoteModel model, SourceItemViewModel source, bool installed, ICommand downloadCommand)
{
Model = model;
Source = source;
Installed = installed;
DownloadCommand = downloadCommand;
}
public string Name => Model.LocalizedName;
public string Description => Model.LocalizedDescription;
public string VersionText => "v" + Model.Manifest.Version;
public string SizeText => ModelScanner.HumanSize(Model.SizeBytes);
public string MetaText => $"{VersionText} · {SizeText}";
public string TagsText => string.Join(" · ", Model.Manifest.Tags ?? new List<string>());
public bool HasTags => !string.IsNullOrWhiteSpace(TagsText);
[ObservableProperty] private bool _installed;
[ObservableProperty] private double _rowHeight = 92;
[ObservableProperty] private double _rowOpacity = 1;
public string ButtonText => Installed ? L.I["dl.reinstall"] : L.I["dl.download"];
public ICommand DownloadCommand { get; }
partial void OnInstalledChanged(bool value) => OnPropertyChanged(nameof(ButtonText));
public void RefreshLanguage()
{
OnPropertyChanged(nameof(Name));
OnPropertyChanged(nameof(Description));
OnPropertyChanged(nameof(MetaText));
OnPropertyChanged(nameof(TagsText));
OnPropertyChanged(nameof(ButtonText));
}
}
+148
View File
@@ -0,0 +1,148 @@
using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Input;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using GC.Models;
using Avalonia.Media.Imaging;
using GC.Services;
namespace GC.ViewModels;
public partial class HomeViewModel : ObservableObject
{
private readonly AppServices _services;
private readonly MainViewModel _main;
public ObservableCollection<ModelCardViewModel> Models { get; } = new();
[ObservableProperty] private ModelCardViewModel? _selected;
[ObservableProperty] private bool _isEmpty;
public string CountText => L.I.F("home.count", Models.Count);
public string SourceCountText => _services.Settings.Current.Sources
.Count(s => s.Enabled && !string.IsNullOrWhiteSpace(s.Url)).ToString();
public string MemoryText => $"{_services.Memory.BudgetMb} MB";
public string SelectedHint => Selected == null ? L.I["home.recent"] : L.I["home.launchHint"];
public HomeViewModel(AppServices services, MainViewModel main)
{
_services = services;
_main = main;
_services.Models.Changed += Refresh;
L.I.LanguageChanged += RefreshLanguage;
Refresh();
}
public void Refresh()
{
var keepId = Selected?.Package.Id;
Models.Clear();
foreach (var package in _services.Models.Scan())
Models.Add(new ModelCardViewModel(package, _services, this));
Selected = Models.FirstOrDefault(m => m.Package.Id == keepId) ?? Models.FirstOrDefault();
IsEmpty = Models.Count == 0;
RefreshLanguage();
}
private void RefreshLanguage()
{
OnPropertyChanged(nameof(CountText));
OnPropertyChanged(nameof(SourceCountText));
OnPropertyChanged(nameof(MemoryText));
OnPropertyChanged(nameof(SelectedHint));
foreach (var model in Models) model.RefreshLanguage();
}
public void LaunchModel(ModelCardViewModel card)
{
Selected = card;
_main.PlayModel(card.Package);
}
public async Task DeleteAsync(ModelCardViewModel card)
{
if (!await _main.ConfirmAsync(L.I.F("home.deleteConfirm", card.Name))) return;
_services.Models.Delete(card.Package.Id);
_services.Models.NotifyChanged();
Refresh();
}
[RelayCommand]
private void Launch()
{
var card = Selected ?? Models.FirstOrDefault();
if (card != null) _main.PlayModel(card.Package);
}
[RelayCommand]
private void OpenDownload() => _main.GoDownload();
[RelayCommand]
private void OpenSettings() => _main.GoSettings();
[RelayCommand]
private void OpenFolder() => Shell.OpenFolder(_services.Paths.ModelRoot);
}
public partial class ModelCardViewModel : ObservableObject
{
private readonly AppServices _services;
private Bitmap? _preview;
public ModelPackage Package { get; }
public ModelCardViewModel(ModelPackage package, AppServices services, HomeViewModel home)
{
Package = package;
_services = services;
LaunchCommand = new RelayCommand(() => home.LaunchModel(this));
DeleteCommand = new AsyncRelayCommand(() => home.DeleteAsync(this));
OpenFolderCommand = new RelayCommand(() => Shell.OpenFolder(package.Directory));
}
public string Name => Package.LocalizedName;
public string Description => Package.LocalizedDescription;
public string VersionText => "v" + Package.Manifest.Version;
public string SizeText => ModelScanner.HumanSize(Package.SizeBytes);
public string MetaText => $"{VersionText} · {SizeText}";
public string TagsText => string.Join(" · ", Package.Manifest.Tags ?? new());
public bool HasTags => !string.IsNullOrWhiteSpace(TagsText);
public string AuthorText => string.IsNullOrWhiteSpace(Package.Manifest.Author) ? "" : Package.Manifest.Author;
/// <summary>封面图来自模型包自带的 preview.png —— 启动器只显示,不渲染。</summary>
public Bitmap? Preview
{
get
{
if (_preview != null) return _preview;
try
{
if (File.Exists(Package.PreviewPath)) _preview = new Bitmap(Package.PreviewPath);
}
catch (Exception ex)
{
Console.Error.WriteLine($"读取模型封面失败 {Package.Id}: {ex.Message}");
}
return _preview;
}
}
public bool HasPreview => Preview != null;
public ICommand LaunchCommand { get; }
public ICommand DeleteCommand { get; }
public ICommand OpenFolderCommand { get; }
public void RefreshLanguage()
{
OnPropertyChanged(nameof(Name));
OnPropertyChanged(nameof(Description));
OnPropertyChanged(nameof(MetaText));
OnPropertyChanged(nameof(TagsText));
}
}
+228
View File
@@ -0,0 +1,228 @@
using System;
using System.Linq;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using GC.Models;
using GC.Services;
namespace GC.ViewModels;
public partial class MainViewModel : ObservableObject
{
private readonly AppServices _services;
private bool _updateRunning;
public HomeViewModel Home { get; }
public DownloadViewModel Download { get; }
public SettingsViewModel Settings { get; }
public AboutViewModel About { get; }
/// <summary>模型宿主:按清单加载模型自带的功能程序集。</summary>
public ModelHost Models { get; }
[ObservableProperty] private ObservableObject _current = null!;
[ObservableProperty] private bool _isHomeActive = true;
[ObservableProperty] private bool _isDownloadActive;
[ObservableProperty] private bool _isSettingsActive;
[ObservableProperty] private bool _isAboutActive;
// 启动更新状态条
[ObservableProperty] private bool _updateBarVisible;
[ObservableProperty] private bool _updateBusy;
[ObservableProperty] private double _updateProgress;
[ObservableProperty] private string _updateStatus = "";
[ObservableProperty] private string _updateDetail = "";
[ObservableProperty] private string _launcherNotice = "";
/// <summary>由主窗口注入的确认对话框。</summary>
public Func<string, Task<bool>>? ConfirmHandler { get; set; }
/// <summary>
/// 由主窗口注入的「发现启动器新版本」对话框。
/// 参数为新版本号,返回 true 表示用户选择更新。
/// </summary>
public Func<string, Task<bool>>? LauncherUpdateHandler { get; set; }
public event Action<ModelPackage>? PlayerRequested;
/// <summary>打开等高线课件窗口(由主窗口接线)。</summary>
public event Action? CoursewareRequested;
public string VersionText => "v" + LauncherRuntimeInfo.CurrentLauncherVersion;
public string PlatformText => LauncherRuntimeInfo.CurrentRid;
public MainViewModel(AppServices services)
{
_services = services;
Models = services.ModelHost;
Home = new HomeViewModel(services, this);
Download = new DownloadViewModel(services, this);
Settings = new SettingsViewModel(services);
About = new AboutViewModel(services);
Current = Home;
}
partial void OnCurrentChanged(ObservableObject value)
{
IsHomeActive = value is HomeViewModel;
IsDownloadActive = value is DownloadViewModel;
IsSettingsActive = value is SettingsViewModel;
IsAboutActive = value is AboutViewModel;
}
[RelayCommand]
public void GoHome()
{
Home.Refresh();
Current = Home;
}
[RelayCommand]
public void GoDownload()
{
Current = Download;
Download.OnShown();
}
[RelayCommand]
public void GoSettings()
{
Settings.Refresh();
Current = Settings;
}
[RelayCommand]
public void GoAbout()
{
About.OnShown();
Current = About;
}
/// <summary>打开等高线课件(独立 Avalonia WebView 窗口)。</summary>
[RelayCommand]
public void OpenCourseware() => CoursewareRequested?.Invoke();
/// <summary>启动模型:交给模型自己的程序集,在独立窗口中运行。</summary>
public void PlayModel(ModelPackage package)
{
_services.Memory.Refresh();
PlayerRequested?.Invoke(package);
}
public async Task<bool> ConfirmAsync(string message)
=> ConfirmHandler == null || await ConfirmHandler(message);
// ---- 自动更新 ----------------------------------------------------------
/// <summary>启动后由 App 调用:后台检查更新,不阻塞主界面。</summary>
public Task RunStartupUpdateAsync() => RunUpdateAsync(false);
/// <summary>状态条 / 设置页的「检查更新」,忽略自动开关强制检查。</summary>
[RelayCommand]
private Task CheckUpdate() => RunUpdateAsync(true);
private async Task RunUpdateAsync(bool force)
{
if (_updateRunning) return;
_updateRunning = true;
try
{
UpdateBarVisible = true;
UpdateBusy = true;
UpdateProgress = 0;
UpdateStatus = L.I["update.checking"];
UpdateDetail = "";
LauncherNotice = "";
// 在 UI 线程构造,进度回调自动回到 UI 线程
var progress = new Progress<UpdateProgress>(p =>
{
UpdateProgress = Math.Clamp(p.Value, 0, 1);
UpdateStatus = p.Message;
UpdateDetail = p.Detail ?? "";
});
// 双源测速:Xhmcl / GitCode 取快的那个(第 5 项)。
// 启动更新与下载页共用同一个选择器,保证两处用同一个源、同一种下载方式。
UpdateStatus = "正在选择最快的下载源…";
try
{
var fastest = await _services.Selector.PickFastestAsync(
force, default);
_services.Updates.UseRemote(_services.DownloadModule.CreateRemote(fastest));
var lat = _services.Selector.LastLatency;
UpdateDetail = "源:" + fastest.Name +
(lat.Count > 0 ? "(" + string.Join(",", lat.Select(kv =>
$"{SourcePreset.Find(kv.Key)?.Name ?? kv.Key} {kv.Value}ms")) + ")" : "");
}
catch (Exception ex)
{
Console.Error.WriteLine($"[update] 测速失败,沿用当前源: {ex.Message}");
}
// 启动器:读 Release latest 版本号,与当前运行版本不同就弹窗询问
var latest = await _services.LauncherUpdates.CheckAsync(_services.Updates.Remote);
if (latest != null)
{
var agreed = LauncherUpdateHandler != null &&
await LauncherUpdateHandler(latest);
if (agreed)
{
// 走完整更新流程(关窗 -> 进度窗下载 -> 重启)
UpdateBusy = false;
_updateRunning = false;
UpdateBarVisible = false;
await LauncherUpdateFlow.RunAsync(_services, "正在更新启动器");
return;
}
UpdateStatus = $"启动器有新版本 v{latest}(已跳过)";
UpdateDetail = "点击「检查更新」可再次更新,模型仍会同步到最新";
}
// 模型:同步到最新版
var result = await _services.Updates.RunAsync(force, progress, default);
UpdateStatus = result.Message;
UpdateDetail = result.Error ?? "";
LauncherNotice = result.LauncherMessage ?? "";
// 首次启动 + 断网:本地一个模型都没有,这时候不能只留一个空页面。
// 明确告诉用户「没坏、可以怎么办」,并保留状态条(不自动隐藏)。
if (result.Outcome == UpdateOutcome.Unavailable && Home.Models.Count == 0)
{
UpdateStatus = "暂时连不上模型源,模型库为空";
UpdateDetail = "可以到「下载」页点重试,或把模型文件夹放进 .GC/model/ 后重新打开";
return;
}
// 模型下载完成后本次启动就刷新列表,立刻可用
if (result.UpdatedModels > 0) Home.Refresh();
if ((result.Outcome == UpdateOutcome.NoChange || result.Outcome == UpdateOutcome.Applied) &&
string.IsNullOrEmpty(LauncherNotice))
_ = AutoHideAsync();
}
catch (Exception ex)
{
UpdateStatus = L.I["update.offline"];
UpdateDetail = ex.Message;
}
finally
{
UpdateBusy = false;
_updateRunning = false;
}
}
private async Task AutoHideAsync()
{
try
{
await Task.Delay(6000);
if (!_updateRunning && string.IsNullOrEmpty(LauncherNotice)) UpdateBarVisible = false;
}
catch { /* 忽略 */ }
}
}
+217
View File
@@ -0,0 +1,217 @@
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Input;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using GC.Models;
using GC.Services;
namespace GC.ViewModels;
public sealed class LanguageOption
{
public string Code { get; init; } = "auto";
public string Label { get; set; } = "";
public override string ToString() => Label;
}
public partial class SettingsViewModel : ObservableObject
{
private readonly AppServices _services;
private bool _loading = true;
public ObservableCollection<SettingsSourceViewModel> Sources { get; } = new();
public ObservableCollection<LanguageOption> Languages { get; } = new();
public int[] FrameRates { get; } = { 24, 30, 60, 90, 120 };
[ObservableProperty] private LanguageOption? _selectedLanguage;
[ObservableProperty] private int _selectedFps = 120;
[ObservableProperty] private double _memoryValue = 2048;
[ObservableProperty] private bool _memoryAuto = true;
[ObservableProperty] private string _statusMessage = "";
[ObservableProperty] private bool _autoUpdate = true;
public string UpdateSourceText => _services.Updates.Remote.DisplayName;
public string LastCheckText
{
get
{
var value = _services.Settings.Current.LastUpdateCheck;
if (string.IsNullOrWhiteSpace(value)) return L.I["update.never"];
return DateTimeOffset.TryParse(value, out var time)
? time.ToLocalTime().ToString("yyyy-MM-dd HH:mm") : value!;
}
}
public string PendingText => string.IsNullOrWhiteSpace(_services.Settings.Current.PendingLauncherVersion)
? L.I["update.none"] : _services.Settings.Current.PendingLauncherVersion!;
public string MemoryValueText => MemoryAuto
? $"{L.I["set.memory.auto"]} ({_services.Memory.BudgetMb} MB)"
: $"{(int)Math.Round(MemoryValue)} MB";
public string UsageText => _services.Memory.UsageText;
public string ModelRoot => _services.Paths.ModelRoot;
public string DataRoot => _services.Paths.DataRoot;
public string PlatformText => $"{RuntimeInformation.OSDescription} · {RuntimeInformation.RuntimeIdentifier}";
public string VersionText => "v1.0.0";
public string MemoryHint => L.I["set.memory.hint"];
public SettingsViewModel(AppServices services)
{
_services = services;
L.I.LanguageChanged += OnLanguageChanged;
Refresh();
_loading = false;
}
public void Refresh()
{
_loading = true;
BuildLanguages();
var settings = _services.Settings.Current;
SelectedFps = settings.RenderFps;
MemoryValue = settings.MemoryMb;
MemoryAuto = settings.MemoryAuto;
AutoUpdate = settings.AutoUpdateOnStartup;
Sources.Clear();
foreach (var source in settings.Sources)
Sources.Add(new SettingsSourceViewModel(source, _services, this));
_loading = false;
OnPropertyChanged(nameof(UsageText));
OnPropertyChanged(nameof(MemoryValueText));
OnPropertyChanged(nameof(MemoryHint));
OnPropertyChanged(nameof(ModelRoot));
OnPropertyChanged(nameof(DataRoot));
OnPropertyChanged(nameof(UpdateSourceText));
OnPropertyChanged(nameof(LastCheckText));
OnPropertyChanged(nameof(PendingText));
}
partial void OnAutoUpdateChanged(bool value)
{
if (_loading) return;
_services.Settings.Apply(s => s.AutoUpdateOnStartup = value);
}
private void BuildLanguages()
{
var current = _services.Settings.Current.Language;
Languages.Clear();
Languages.Add(new LanguageOption { Code = "auto", Label = L.I["set.language.auto"] });
foreach (var (code, label) in L.Supported)
Languages.Add(new LanguageOption { Code = code, Label = label });
SelectedLanguage = Languages.FirstOrDefault(l => l.Code == current) ?? Languages[0];
}
private void OnLanguageChanged()
{
_loading = true;
BuildLanguages();
_loading = false;
Refresh();
}
partial void OnSelectedLanguageChanged(LanguageOption? value)
{
if (_loading || value == null) return;
_services.Settings.Apply(s => s.Language = value.Code);
L.I.SetLanguage(value.Code);
}
partial void OnSelectedFpsChanged(int value)
{
if (_loading) return;
_services.Settings.Apply(s => s.RenderFps = Math.Clamp(value, 12, 120));
}
partial void OnMemoryValueChanged(double value)
{
if (_loading) return;
var mb = (int)Math.Round(value);
_services.Settings.Apply(s => s.MemoryMb = mb);
_services.Memory.Apply(mb);
OnPropertyChanged(nameof(MemoryValueText));
OnPropertyChanged(nameof(UsageText));
}
partial void OnMemoryAutoChanged(bool value)
{
if (_loading) return;
_services.Settings.Apply(s => s.MemoryAuto = value);
_services.Memory.ApplyAuto(value, (int)Math.Round(MemoryValue));
OnPropertyChanged(nameof(MemoryValueText));
OnPropertyChanged(nameof(UsageText));
}
[RelayCommand]
private void OpenModelFolder() => Shell.OpenFolder(_services.Paths.ModelRoot);
[RelayCommand]
private void OpenDataFolder() => Shell.OpenFolder(_services.Paths.DataRoot);
[RelayCommand]
private void ClearCache()
{
// 模型数据由模型自己管理;这里只回收启动器侧托管内存
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
_services.Memory.Refresh();
StatusMessage = L.I["set.cacheCleared"];
OnPropertyChanged(nameof(UsageText));
}
[RelayCommand]
private void ApplyMemory()
{
_services.Memory.Apply((int)Math.Round(MemoryValue));
StatusMessage = L.I["common.applied"];
OnPropertyChanged(nameof(UsageText));
}
internal void RemoveSource(SettingsSourceViewModel source)
{
if (source.Model.BuiltIn) return; // 内置默认源不允许删除
_services.Settings.Current.Sources.Remove(source.Model);
_services.Settings.Save();
Sources.Remove(source);
_services.Settings.Notify();
}
}
public partial class SettingsSourceViewModel : ObservableObject
{
private readonly AppServices _services;
private readonly SettingsViewModel _owner;
public ModelSource Model { get; }
public SettingsSourceViewModel(ModelSource model, AppServices services, SettingsViewModel owner)
{
Model = model;
_services = services;
_owner = owner;
RemoveCommand = new RelayCommand(() => _owner.RemoveSource(this));
}
public string Name => string.IsNullOrWhiteSpace(Model.Name) ? Model.Id : Model.Name;
public string UrlText => string.IsNullOrWhiteSpace(Model.Url) ? L.I["dl.noSource"] : Model.Url;
/// <summary>内置默认源不可删除。</summary>
public bool CanRemove => !Model.BuiltIn;
public bool Enabled
{
get => Model.Enabled;
set
{
if (Model.Enabled == value) return;
Model.Enabled = value;
_services.Settings.Save();
OnPropertyChanged();
}
}
public ICommand RemoveCommand { get; }
}
+147
View File
@@ -0,0 +1,147 @@
<UserControl xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:loc="using:GC.Services"
xmlns:vm="using:GC.ViewModels"
x:Class="GC.Views.AboutView"
x:DataType="vm:AboutViewModel">
<ScrollViewer>
<StackPanel Margin="28,24" Spacing="16" MaxWidth="880" HorizontalAlignment="Left">
<StackPanel Spacing="4">
<TextBlock Classes="h1" Text="关于" />
<TextBlock Classes="muted" Text="版本信息与开发者" />
</StackPanel>
<!-- 应用信息 -->
<Border Classes="card" Padding="22,20">
<Grid ColumnDefinitions="Auto,*">
<Border Width="62" Height="62" CornerRadius="16" Background="#1C2C4C"
VerticalAlignment="Top">
<TextBlock Text="◎" FontSize="32" Foreground="#8FB6FF"
HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border>
<StackPanel Grid.Column="1" Margin="18,0,0,0" Spacing="10">
<StackPanel Spacing="2">
<TextBlock Text="{Binding AppName}" FontSize="19" FontWeight="SemiBold" />
<TextBlock Classes="faint" Text="{Binding PlatformText}" />
</StackPanel>
<Grid ColumnDefinitions="96,*" RowDefinitions="Auto,Auto,Auto">
<TextBlock Classes="h3" Text="版本" />
<TextBlock Grid.Column="1" Classes="muted" Text="{Binding VersionText}"
FontWeight="SemiBold" />
<TextBlock Grid.Row="1" Classes="h3" Text="仓库" Margin="0,8,0,0" />
<Button Grid.Row="1" Grid.Column="1" Classes="ghost small" Margin="0,6,0,0"
HorizontalAlignment="Left" Padding="0"
Command="{Binding OpenRepositoryCommand}"
Content="{Binding RepositoryText}" />
<TextBlock Grid.Row="2" Classes="h3" Text="Git 服务" Margin="0,8,0,0" />
<TextBlock Grid.Row="2" Grid.Column="1" Classes="muted" Text="itxiaohui"
FontWeight="SemiBold" Margin="0,8,0,0" />
</Grid>
</StackPanel>
</Grid>
</Border>
<!-- 维护 -->
<Border Classes="card" Padding="22,20">
<StackPanel Spacing="12">
<TextBlock Classes="h2" Text="启动器维护" />
<TextBlock Classes="muted" TextWrapping="Wrap"
Text="重新下载会关闭所有窗口,显示下载进度,完成后自动启动新版本并删除旧版本。" />
<Button Classes="primary" Content="重新下载启动器"
HorizontalAlignment="Left" Padding="18,8"
Command="{Binding ReinstallLauncherCommand}" />
</StackPanel>
</Border>
<!-- 感谢(样式抄「开发者」卡片,内容写死,不读取数据) -->
<Border Classes="card" Padding="22,20">
<StackPanel Spacing="14">
<TextBlock Classes="h2" Text="感谢" />
<StackPanel Orientation="Horizontal" Spacing="10">
<Border Background="{DynamicResource SurfaceAlt}"
BorderBrush="{DynamicResource Line}" BorderThickness="1"
CornerRadius="12" Padding="12,10" MinWidth="190">
<StackPanel Orientation="Horizontal" Spacing="10">
<Border Width="34" Height="34" CornerRadius="17"
Background="{DynamicResource AccentSoft}">
<TextBlock Text="◉" FontSize="15" Foreground="{DynamicResource Accent}"
HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border>
<StackPanel VerticalAlignment="Center" Spacing="1">
<TextBlock Text="地理洪老师" FontSize="12.5" FontWeight="SemiBold" />
<TextBlock Classes="faint" Text="地理学科内容指导" />
</StackPanel>
</StackPanel>
</Border>
<Border Background="{DynamicResource SurfaceAlt}"
BorderBrush="{DynamicResource Line}" BorderThickness="1"
CornerRadius="12" Padding="12,10" MinWidth="190">
<StackPanel Orientation="Horizontal" Spacing="10">
<Border Width="34" Height="34" CornerRadius="17"
Background="{DynamicResource AccentSoft}">
<TextBlock Text="◉" FontSize="15" Foreground="{DynamicResource Accent}"
HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border>
<StackPanel VerticalAlignment="Center" Spacing="1">
<TextBlock Text="itxiaohui" FontSize="12.5" FontWeight="SemiBold" />
<TextBlock Classes="faint" Text="Git 服务与部署支持" />
</StackPanel>
</StackPanel>
</Border>
</StackPanel>
</StackPanel>
</Border>
<!-- 开发者 -->
<Border Classes="card" Padding="22,20">
<StackPanel Spacing="14">
<Grid ColumnDefinitions="*,Auto">
<TextBlock Classes="h2" Text="{Binding ContributorsTitle}" />
<Button Grid.Column="1" Classes="ghost small" Content="刷新"
Command="{Binding LoadCommand}" IsEnabled="{Binding !IsLoading}" />
</Grid>
<TextBlock Classes="faint" Text="{Binding StatusText}" />
<ProgressBar IsIndeterminate="True" Height="3" IsVisible="{Binding IsLoading}" />
<ItemsControl ItemsSource="{Binding Contributors}" IsVisible="{Binding HasContributors}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border Background="{DynamicResource SurfaceAlt}"
BorderBrush="{DynamicResource Line}" BorderThickness="1"
CornerRadius="12" Padding="12,10" Margin="0,0,10,10" MinWidth="190">
<StackPanel Orientation="Horizontal" Spacing="10">
<Border Width="34" Height="34" CornerRadius="17"
Background="{DynamicResource AccentSoft}">
<TextBlock Text="◉" FontSize="15" Foreground="{DynamicResource Accent}"
HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border>
<StackPanel VerticalAlignment="Center" Spacing="1">
<TextBlock Text="{Binding Name}" FontSize="12.5" FontWeight="SemiBold" />
<TextBlock Classes="faint" Text="{Binding ContributionsText}" />
</StackPanel>
</StackPanel>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</Border>
</StackPanel>
</ScrollViewer>
</UserControl>
+11
View File
@@ -0,0 +1,11 @@
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
namespace GC.Views;
public partial class AboutView : UserControl
{
public AboutView() => InitializeComponent();
private void InitializeComponent() => AvaloniaXamlLoader.Load(this);
}
+21
View File
@@ -0,0 +1,21 @@
<Window xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:loc="using:GC.Services"
x:Class="GC.Views.ConfirmWindow"
Title="{loc:Loc app.name}"
Width="440" SizeToContent="Height"
CanResize="False" ShowInTaskbar="False"
WindowStartupLocation="CenterOwner"
Background="Transparent"
SystemDecorations="None"
TransparencyLevelHint="Transparent">
<StackPanel Margin="24,20,24,20" Spacing="14">
<TextBlock x:Name="TitleText" Classes="h2" Text="{loc:Loc common.confirmTitle}" />
<TextBlock x:Name="MessageText" Classes="muted" TextWrapping="Wrap" />
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Spacing="8" Margin="0,6,0,0">
<Button x:Name="CancelButton" Content="{loc:Loc common.cancel}" Click="OnCancel" />
<Button x:Name="ConfirmButton" Classes="primary" Content="{loc:Loc common.confirm}" Click="OnConfirm" />
</StackPanel>
</StackPanel>
</Window>
+66
View File
@@ -0,0 +1,66 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using Avalonia.Media;
namespace GC.Views;
public partial class ConfirmWindow : Window
{
public ConfirmWindow() : this("") { }
public ConfirmWindow(string message) : this(null, message, null, null) { }
/// <summary>
/// 可定制标题与按钮文案的确认窗。
/// </summary>
public ConfirmWindow(string? title, string message, string? confirmText, string? cancelText)
{
AvaloniaXamlLoader.Load(this);
TransparencyLevelHint = new[] { WindowTransparencyLevel.Transparent };
Background = Brushes.Transparent;
if (this.Content is Control content)
{
// 先把 content 从 Window 上摘下来,否则再赋给 Border.Child 会抛
// "The Control already has a parent."
this.Content = null;
this.Content = new Border
{
CornerRadius = new CornerRadius(14),
BorderBrush = (this.FindResource("Line") as IBrush) ?? Brushes.Gray,
BorderThickness = new Thickness(1),
Background = (this.FindResource("Surface") as IBrush) ?? Brushes.White,
ClipToBounds = true,
Child = content
};
}
var text = this.FindControl<TextBlock>("MessageText");
if (text != null) text.Text = message;
if (!string.IsNullOrWhiteSpace(title))
{
var titleBlock = this.FindControl<TextBlock>("TitleText");
if (titleBlock != null) titleBlock.Text = title;
}
if (!string.IsNullOrWhiteSpace(confirmText))
{
var ok = this.FindControl<Button>("ConfirmButton");
if (ok != null) ok.Content = confirmText;
}
if (!string.IsNullOrWhiteSpace(cancelText))
{
// 取消按钮是第一个("取消"),这里按名查找更稳
var cancel = this.FindControl<Button>("CancelButton");
if (cancel != null) cancel.Content = cancelText;
}
}
private void OnCancel(object? sender, RoutedEventArgs e) => Close(false);
private void OnConfirm(object? sender, RoutedEventArgs e) => Close(true);
}
+50
View File
@@ -0,0 +1,50 @@
using System;
using Avalonia;
using Avalonia.Controls;
using AvaloniaWebView;
using GC.Services;
namespace GC.Views;
/// <summary>
/// 等高线地形课件窗口:内嵌 WebView 渲染本地 HTML 课件。
/// 课件资源由 <see cref="CoursewareServer"/> 通过回环 HTTP 提供,
/// 解决 file:// 下的同源策略与视频拖动问题。
/// </summary>
public sealed class CoursewareWindow : Window
{
private readonly CoursewareServer? _server;
public CoursewareWindow()
{
Title = "等高线地形课件";
Width = 1180;
Height = 780;
MinWidth = 760;
MinHeight = 520;
WindowStartupLocation = WindowStartupLocation.CenterOwner;
try
{
_server = new CoursewareServer();
var webView = new WebView();
webView.Url = new Uri(_server.BaseUrl + "index.html");
Content = webView;
}
catch (Exception ex)
{
Content = new TextBlock
{
Text = $"课件加载失败:{ex.Message}",
Margin = new Thickness(24),
TextWrapping = Avalonia.Media.TextWrapping.Wrap,
};
}
}
protected override void OnClosed(EventArgs e)
{
_server?.Dispose();
base.OnClosed(e);
}
}
+154
View File
@@ -0,0 +1,154 @@
<UserControl xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:loc="using:GC.Services"
x:Class="GC.Views.DownloadView">
<Grid ColumnDefinitions="316,*" Margin="24,22,24,24">
<!-- 模型源 -->
<Border Grid.Column="0" Classes="card" Padding="18" Margin="0,0,16,0">
<Grid RowDefinitions="Auto,Auto,Auto,*,Auto">
<TextBlock Classes="h2" Text="{loc:Loc dl.sources}" />
<!-- 只允许 Xhmcl / GitCode 两个内置源;这里是对比测速并自动切换 -->
<StackPanel Grid.Row="1" Margin="0,12,0,0" Spacing="8">
<Button Classes="primary" Content="测速并切换到最快源"
Command="{Binding ImportCommand}" HorizontalAlignment="Stretch" />
</StackPanel>
<TextBlock Grid.Row="2" Classes="faint" Text="{loc:Loc dl.hint}"
TextWrapping="Wrap" Margin="0,9,0,12" />
<ScrollViewer Grid.Row="3" VerticalScrollBarVisibility="Auto">
<ListBox ItemsSource="{Binding Sources}" SelectedItem="{Binding SelectedSource}"
Background="Transparent" BorderThickness="0" Padding="0">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid ColumnDefinitions="*,Auto" Margin="0,3">
<StackPanel Spacing="2" VerticalAlignment="Center">
<TextBlock Text="{Binding Name}" FontSize="12.5" FontWeight="SemiBold"
TextTrimming="CharacterEllipsis" />
<TextBlock Text="{Binding HostText}" Classes="faint" TextTrimming="CharacterEllipsis" />
</StackPanel>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</ScrollViewer>
<Border Grid.Row="4" Classes="panel" Padding="12,9" Margin="0,10,0,0">
<StackPanel Spacing="3">
<TextBlock Classes="eyebrow" Text="{loc:Loc dl.available}" />
<TextBlock Classes="faint" Text="{Binding StatusMessage}" TextWrapping="Wrap" />
</StackPanel>
</Border>
</Grid>
</Border>
<!-- 可用模型 + 后台任务 -->
<Border Grid.Column="1" Classes="card" Padding="20">
<Grid RowDefinitions="Auto,*,Auto">
<Grid ColumnDefinitions="*,Auto,Auto">
<StackPanel>
<TextBlock Classes="h2" Text="{loc:Loc dl.available}" />
<TextBlock Classes="muted" Text="{Binding StatusMessage}" Margin="0,3,0,0" />
</StackPanel>
<ProgressBar Grid.Column="1" IsIndeterminate="True" Width="90" Height="4"
IsVisible="{Binding IsBusy}" VerticalAlignment="Center" Margin="12,0" />
<Button Grid.Column="2" Classes="small" Content="{loc:Loc dl.refresh}"
Command="{Binding RefreshCommand}" VerticalAlignment="Center" />
</Grid>
<ScrollViewer Grid.Row="1" Margin="0,14,0,0" VerticalScrollBarVisibility="Auto">
<ItemsControl ItemsSource="{Binding Models}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border Height="{Binding RowHeight}" Opacity="{Binding RowOpacity}"
ClipToBounds="True" Margin="0,0,0,10">
<Border.Transitions>
<Transitions>
<DoubleTransition Property="Height" Duration="0:0:0.24" Easing="CubicEaseOut" />
<DoubleTransition Property="Opacity" Duration="0:0:0.18" />
</Transitions>
</Border.Transitions>
<Border Classes="panel" Padding="14,11">
<Grid ColumnDefinitions="*,Auto">
<StackPanel Spacing="3" VerticalAlignment="Center">
<StackPanel Orientation="Horizontal" Spacing="8">
<TextBlock Text="{Binding Name}" FontSize="13" FontWeight="SemiBold" />
<Border Classes="tag" VerticalAlignment="Center">
<TextBlock Text="{Binding VersionText}" Classes="faint" />
</Border>
<TextBlock Text="{Binding SizeText}" Classes="faint" VerticalAlignment="Center" />
</StackPanel>
<TextBlock Text="{Binding Description}" Classes="muted"
MaxLines="1" TextTrimming="CharacterEllipsis" MaxWidth="520" />
<TextBlock Text="{Binding TagsText}" Classes="faint" IsVisible="{Binding HasTags}" />
</StackPanel>
<Button Grid.Column="1" Classes="primary small" Content="{Binding ButtonText}"
Command="{Binding DownloadCommand}" CommandParameter="{Binding}"
VerticalAlignment="Center" Margin="12,0,0,0" />
</Grid>
</Border>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
<!-- 后台任务(下载时折叠到这里) -->
<Border Grid.Row="2" Classes="panel" Margin="0,12,0,0" Padding="6" IsVisible="{Binding HasJobs}">
<StackPanel>
<Grid ColumnDefinitions="*,Auto">
<Button Classes="ghost" Content="{Binding JobSummary}" Command="{Binding ToggleBackgroundCommand}"
HorizontalContentAlignment="Left" FontSize="12" FontWeight="SemiBold" Padding="10,7" />
<Button Grid.Column="1" Classes="ghost small" Content="{loc:Loc dl.clearDone}"
Command="{Binding ClearFinishedCommand}" VerticalAlignment="Center" Margin="0,0,6,0" />
</Grid>
<ScrollViewer MaxHeight="200" IsVisible="{Binding IsBackgroundOpen}">
<ItemsControl ItemsSource="{Binding Jobs}" Margin="6,0,6,6">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border Background="{DynamicResource Surface}" CornerRadius="9" Padding="10,8" Margin="0,4,0,0">
<Grid ColumnDefinitions="*,Auto">
<StackPanel Spacing="4">
<Grid ColumnDefinitions="*,Auto">
<TextBlock Text="{Binding Name}" FontSize="12" FontWeight="SemiBold" />
<TextBlock Grid.Column="1" Text="{Binding StatusText}" Classes="faint" />
</Grid>
<ProgressBar Value="{Binding Progress}" Maximum="1" IsVisible="{Binding IsActive}" />
<TextBlock Text="{Binding DetailText}" Classes="faint" TextTrimming="CharacterEllipsis" />
</StackPanel>
<StackPanel Grid.Column="1" Orientation="Horizontal" Spacing="2"
VerticalAlignment="Center" Margin="10,0,0,0">
<Button Classes="ghost small" Content="{loc:Loc dl.cancel}"
IsVisible="{Binding IsActive}"
Command="{Binding $parent[ItemsControl].DataContext.CancelJobCommand}"
CommandParameter="{Binding}" />
<Button Classes="ghost small" Content="{loc:Loc dl.retry}"
IsVisible="{Binding CanRetry}"
Command="{Binding $parent[ItemsControl].DataContext.RetryJobCommand}"
CommandParameter="{Binding}" />
<Button Classes="ghost small" Content="{loc:Loc dl.removeTask}"
Command="{Binding $parent[ItemsControl].DataContext.RemoveJobCommand}"
CommandParameter="{Binding}" />
</StackPanel>
</Grid>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
</StackPanel>
</Border>
</Grid>
</Border>
</Grid>
</UserControl>
Loaded 100 of 425 files, more files were not shown because too many files have changed in this diff. Show more