Author SHA1 Message Date
Morris 5b2393cdbb Linux 产物改为默认不构建(云端可显式开启)
- Linux 目标平台是 arm64,而官方 Flutter 引擎只有 x64 产物,x64 主机编出来的包
  在 arm 机器上跑不起来
- 默认跳过并打印一行提示;GC_BUILD_LINUX=1 ./build.sh build 可显式开启
  (云端 aarch64 runner 用这个开关,代码路径与打包逻辑都保留)
- 清单里的 linux-arm64 条目继续保留:没有产物就没有 sha256,下载端会跳过该平台

验证:./build.sh build 只产 GCL-1.0.10-win-{amd64,arm64}.zip,与开启前一致。
2026-11-18 20:40:56 +08:00
419 changed files with 15821 additions and 24345 deletions

No files matched your search

+1 -4
View File
@@ -57,12 +57,9 @@ jobs:
with:
dotnet-version: '8.0.x'
- name: 运行 GC.Tests(含离屏渲染 / 清单校验 / 日志用例)
- name: 运行 GC.Tests(含离屏渲染 / 清单校验)
run: dotnet run --project GC/src/test/dotnet/GC.Tests/GC.Tests.csproj -c Release
- name: 运行应用器测试(整目录替换 / .GC/bin 合并 / 回滚)
run: dotnet run --project GC/src/test/dotnet/GC.Savedog.Tests/GC.Savedog.Tests.csproj -c Release
frontend:
name: 前端检查(Flutter)
runs-on: ubuntu-latest
-50
View File
@@ -1,50 +0,0 @@
# ---------------------------------------------------------------------------
# 发布一致性核对(Gitea Actions)
#
# 触发:仅手动。发布前跑一次确认「tag / 清单 / 资产」互相对得上,发布后再跑一次
# 确认线上资产就是清单里那两份。
#
# 为什么不用 pull_request 触发:这里要下载几百 MB 的发布包,PR 阶段跑太贵;
# 需要时点 Run workflow 即可,本地也有等价命令:./build.sh release-verify <tag>
# ---------------------------------------------------------------------------
name: 发布核对
on:
workflow_dispatch:
inputs:
tag:
description: '要核对的 tag(如 1.1.0)'
required: true
skip_download:
description: '只比对体积、不下载校验 sha256(快,输入 1 开启)'
required: false
default: ''
env:
DOTNET_NOLOGO: '1'
DOTNET_CLI_TELEMETRY_OPTOUT: '1'
jobs:
verify:
name: 核对 Release 与清单
runs-on: ubuntu-latest
steps:
- name: 检出代码
uses: actions/checkout@v4
- name: 安装 .NET 8
uses: actions/setup-dotnet@v4
with:
dotnet-version: '8.0.x'
- name: 核对
env:
GC_GITEA_TOKEN: ${{ secrets.GC_GITEA_TOKEN }}
run: |
set -eu
EXTRA=""
if [ -n "${{ github.event.inputs.skip_download }}" ]; then
EXTRA="--skip-download"
fi
chmod +x buildsh/lib/verify_release.py
./build.sh release-verify "${{ github.event.inputs.tag }}" $EXTRA
-87
View File
@@ -1,87 +0,0 @@
# GitHub Actions 说明
三个工作流,都在 `.github/workflows/` 下。自建 Gitea 里对应的老流水线在 `.gitea/workflows/`,两边互不影响。
| 工作流 | 触发 | 做什么 |
| --- | --- | --- |
| `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`,`@build-bot` 发 `ip-prerelease`;
`@build-release-bot` 发的是正式版本(tag 就是版本号,会更新 latest)。
## 每夜构建
时区用 `TZ=Asia/Shanghai`,cron 写成 `0 13 * * *`(= 21:00 UTC+8)。
产物是 `GCL-<版本>-<平台>.zip`,由 `build.sh` / `build.ps1` 生成在 `dist/<平台>/`。
`nightly` 这个 tag **每次滚动重建**(先删 release 和 tag,再按当前提交创建),
所以它的下载链接是稳定的。因为 tag 不是版本号,客户端的上传/更新逻辑会跳过它
——夜间版本永远不会被当成「有新版可用」推给用户,符合预期。
## 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 # 三个平台全编
```
规则:
- 只有 `OWNER` / `MEMBER` / `COLLABORATOR` 的评论才会触发,其他人评论会被忽略。
- PR 上的评论编的是 **该 PR 的 head 提交**;Issue 上评论编的是 main 最新提交。
- 产物用 `gh release upload --clobber` 合并进 `ip-prerelease`,**不会**删掉别的平台资产。
- 编完会在评论里回帖:成功给出 release 链接,失败给出日志链接。
- 同一时刻只跑一个 build-bot(同一 concurrency 组),避免并发改同一个 release;
`nightly` 用的是另一个组,两者互不干扰(tag 本来就不同)。
## PR 自动审查
对 main 的 PR 在新建 / 推新提交 / 重新打开时运行,检查四项:
1. **能否编译**:`dotnet build GC.sln -c Release`
2. **代码检查**:`flutter analyze`(在 `GC-UI/frontend`)
3. **是否冲突**:读 GitHub 的 `mergeable` 字段(异步计算,会重试几次)
4. **是否落后**:`git rev-list --count HEAD..origin/main`
结论写进一条带 `<!-- gc-pr-review -->` 标记的评论,**重复运行只更新这一条**,不会刷屏。
日志尾部(dotnet / flutter 各 40 行)折叠在评论的 `<details>` 里。
> 说明:这里只做「能编译 + 能通过静态分析」,不跑 `flutter build macos`
> (Ubuntu runner 没有 Xcode)。真正的三平台编译由 `nightly-prerelease` 和 `build-bot` 覆盖。
## 需要的仓库设置
- `Settings → Actions → General → Workflow permissions` 给 **Read and write**,
否则 `gh release` / 评论接口会 403(工作流里已声明 `permissions:`,但组织策略可能覆盖)。
- Secrets 不需要额外配置,统一用内置的 `GITHUB_TOKEN`。
- 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,不需要额外安装。
-342
View File
@@ -1,342 +0,0 @@
name: build-bot
# 在 Issue / PR 里评论触发编译:
# @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:
issue_comment:
types: [created]
concurrency:
group: release-ip-prerelease
cancel-in-progress: false
permissions:
contents: write
issues: write
pull-requests: write
env:
TZ: Asia/Shanghai
BOT_TAG: ip-prerelease
DOTNET_VERSION: '8.0.x'
FLUTTER_VERSION: '3.24.5'
jobs:
prepare:
# 只处理带 @build-bot build 的评论,且只允许仓库成员触发
if: |
contains(github.event.comment.body, '@build-bot') &&
(github.event.comment.author_association == 'OWNER' ||
github.event.comment.author_association == 'MEMBER' ||
github.event.comment.author_association == 'COLLABORATOR')
runs-on: ubuntu-latest
outputs:
target: ${{ steps.parse.outputs.target }}
ref: ${{ steps.parse.outputs.ref }}
is_pr: ${{ steps.parse.outputs.is_pr }}
version: ${{ steps.parse.outputs.version }}
ok: ${{ steps.parse.outputs.ok }}
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- id: parse
name: 解析指令
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
BODY: ${{ github.event.comment.body }}
ISSUE_NUMBER: ${{ github.event.issue.number }}
run: |
set -e
# 抓 @build-bot build <target>,target 白名单外一律忽略
TARGET=$(printf '%s' "$BODY" \
| grep -oiE '@build-bot[[:space:]]+build[[:space:]]+(mac|win-amd|win-arm|all)' \
| head -1 \
| awk '{print tolower($NF)}' || true)
if [ -z "$TARGET" ]; then
echo "ok=false" >> "$GITHUB_OUTPUT"
echo "没有匹配到合法目标,忽略"
exit 0
fi
echo "ok=true" >> "$GITHUB_OUTPUT"
echo "target=$TARGET" >> "$GITHUB_OUTPUT"
# 版本号:评论里的 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 提交;否则用默认分支最新
IS_PR=$(gh api "repos/${{ github.repository }}/issues/${ISSUE_NUMBER}" \
--jq '.pull_request != null' 2>/dev/null || echo false)
echo "is_pr=$IS_PR" >> "$GITHUB_OUTPUT"
if [ "$IS_PR" = "true" ]; then
# 只有「还开着」的 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')
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 包缓存: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_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: 3
build-win:
needs: prepare
if: needs.prepare.outputs.ok == 'true' && (needs.prepare.outputs.target == 'win-amd' || needs.prepare.outputs.target == 'win-arm' || needs.prepare.outputs.target == 'all')
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
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: 3
publish:
needs: [prepare, build-mac, build-win]
if: |
always() &&
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: 汇总产物
env:
TARGET: ${{ needs.prepare.outputs.target }}
run: |
set -e
mkdir -p out
case "$TARGET" in
mac) PATTERN='*-mac-arm64.zip' ;;
win-amd) PATTERN='*-win-amd64.zip' ;;
win-arm) PATTERN='*-win-arm64.zip' ;;
*) PATTERN='*.zip' ;;
esac
# Windows 作业一次会编译 amd64 + arm64,这里只挑本次请求的平台
find artifacts -name '*.zip' | while read -r f; do
case "$f" in
$PATTERN) cp "$f" out/ ;;
esac
done
[ -n "$(ls -A out 2>/dev/null)" ] || { echo "没有匹配 $PATTERN 的产物"; exit 1; }
ls -lh out
- id: publish_step
name: 发布到 ip-prerelease
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
VERSION: ${{ needs.prepare.outputs.version }}
TARGET: ${{ needs.prepare.outputs.target }}
REF: ${{ needs.prepare.outputs.ref }}
TAG: ${{ env.BOT_TAG }}
ACTOR: ${{ github.event.comment.user.login }}
ISSUE: ${{ github.event.issue.number }}
run: |
set -e
cat > notes.md <<EOF
手动触发构建(\`@build-bot build ${TARGET} version=${VERSION}\`)。
触发人:@${ACTOR}
来源:#${ISSUE}
提交:\`${REF:0:7}\`,版本号 ${VERSION}
> 预发布版本:仅供测试,不保证稳定。
EOF
if gh release view "$TAG" >/dev/null 2>&1; then
# 已有预发布:只覆盖本次编译出来的资产,别的平台保留
gh release upload "$TAG" out/*.zip --clobber
gh release edit "$TAG" --prerelease --notes-file notes.md
else
gh release create "$TAG" out/*.zip \
--prerelease \
--target "$REF" \
--title "Prerelease ${VERSION}" \
--notes-file notes.md
fi
echo "https://github.com/${{ github.repository }}/releases/tag/$TAG" >> "$GITHUB_STEP_SUMMARY"
# 结果回帖独立成一个 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 }}
# 本 job 不 checkout(省时间),gh 需要显式指定仓库
GH_REPO: ${{ github.repository }}
ISSUE: ${{ github.event.issue.number }}
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: |
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
@@ -1,309 +0,0 @@
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
-144
View File
@@ -1,144 +0,0 @@
name: nightly-prerelease
# 每晚 21:00(亚洲/上海)自动编译 macOS + Windows 并发布 nightly 预发布。
# 21:00 UTC+8 == 13:00 UTC。
# 注意:夜间构建发的是 `nightly`;`@build-bot` 手动触发的发 `ip-prerelease`。
on:
schedule:
- cron: '0 13 * * *'
workflow_dispatch:
concurrency:
group: release-nightly
cancel-in-progress: false
permissions:
contents: write
env:
TZ: Asia/Shanghai
NIGHTLY_TAG: nightly
DOTNET_VERSION: '8.0.x'
FLUTTER_VERSION: '3.24.5'
jobs:
meta:
runs-on: ubuntu-latest
outputs:
version: ${{ steps.ver.outputs.version }}
stamp: ${{ steps.ver.outputs.stamp }}
steps:
- uses: actions/checkout@v4
- id: ver
name: 读取版本号
run: |
VERSION=$(sed -n 's:.*<Version>\(.*\)</Version>.*:\1:p' Directory.Build.props | head -1)
[ -n "$VERSION" ] || VERSION=1.0.0
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
echo "stamp=$(date +%Y%m%d-%H%M)" >> "$GITHUB_OUTPUT"
echo "版本 $VERSION"
build-mac:
needs: meta
runs-on: macos-latest
steps:
- uses: actions/checkout@v4
- 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: 编译 macOS
env:
GC_TARGETS: mac
GC_NO_PROGRESS: '1'
run: ./build.sh build --targets=mac
- uses: actions/upload-artifact@v4
with:
name: mac-zip
path: dist/mac-arm64/*.zip
if-no-files-found: error
retention-days: 3
build-win:
needs: meta
runs-on: windows-latest
defaults:
run:
shell: pwsh
steps:
- uses: actions/checkout@v4
- 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
- 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: 3
publish:
needs: [meta, build-mac, build-win]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/download-artifact@v4
with:
path: artifacts
- name: 汇总产物
run: |
mkdir -p out
find artifacts -name '*.zip' -exec cp {} out/ \;
ls -lh out
- name: 发布 nightly
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
VERSION: ${{ needs.meta.outputs.version }}
STAMP: ${{ needs.meta.outputs.stamp }}
TAG: ${{ env.NIGHTLY_TAG }}
run: |
set -e
cat > notes.md <<EOF
每夜自动构建(${STAMP},Asia/Shanghai)。
基于提交 \`${GITHUB_SHA:0:7}\`,版本号 ${VERSION}。
- macOS(arm64)
- Windows(amd64 / arm64)
> 预发布版本:仅供测试,不保证稳定。
EOF
# 同一 tag 滚动更新:先删旧 release 与 tag,再按当前提交重建
gh release delete "$TAG" --yes --cleanup-tag 2>/dev/null || true
gh release create "$TAG" out/*.zip \
--prerelease \
--target "$GITHUB_SHA" \
--title "Nightly ${VERSION} (${STAMP})" \
--notes-file notes.md
-207
View File
@@ -1,207 +0,0 @@
name: pr-review
# PR 发起 / 有新提交时自动审查:
# 1) 是否能编译(.NET 全解决方案 + Flutter 静态分析)
# 2) 是否有编译错误 / 分析错误
# 3) 与目标分支是否有冲突
# 4) 是否落后目标分支提交
# 结果写进一条评论,重复运行只更新不刷屏。
on:
pull_request:
types: [opened, synchronize, reopened]
branches: [main]
concurrency:
group: pr-review-${{ github.event.pull_request.number }}
cancel-in-progress: true
permissions:
contents: read
pull-requests: write
issues: write
env:
DOTNET_VERSION: '8.0.x'
FLUTTER_VERSION: '3.24.5'
MARKER: '<!-- gc-pr-review -->'
jobs:
review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- 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
- id: branch
name: 检查冲突与落后提交
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
PR: ${{ github.event.pull_request.number }}
BASE_REF: ${{ github.base_ref }}
run: |
set -e
BASE="origin/${BASE_REF}"
git fetch --no-tags origin "$BASE_REF" >/dev/null 2>&1 || true
BEHIND=$(git rev-list --count "HEAD..${BASE}" 2>/dev/null || echo 0)
AHEAD=$(git rev-list --count "${BASE}..HEAD" 2>/dev/null || echo 0)
echo "behind=$BEHIND" >> "$GITHUB_OUTPUT"
echo "ahead=$AHEAD" >> "$GITHUB_OUTPUT"
# GitHub 的 mergeable 字段是异步计算的,前几次可能为 null,重试几次
MERGEABLE="null"
STATE="unknown"
for i in 1 2 3 4 5 6 7 8; do
read -r MERGEABLE STATE <<< "$(gh api "repos/${{ github.repository }}/pulls/${PR}" \
--jq '"\(.mergeable | tostring) \(.mergeable_state // "unknown")"' 2>/dev/null || echo 'null unknown')"
# mergeable 只有 true / false 才是算完的结果,null 说明还在算
if [ "$MERGEABLE" = "true" ] || [ "$MERGEABLE" = "false" ]; then break; fi
sleep 4
done
# 注意语义:mergeable=true 表示「可以合并」,false 才是冲突
case "$MERGEABLE" in
true) echo "conflict=ok" >> "$GITHUB_OUTPUT" ;;
false) echo "conflict=conflict" >> "$GITHUB_OUTPUT" ;;
*) echo "conflict=unknown" >> "$GITHUB_OUTPUT" ;;
esac
echo "merge_state=$STATE" >> "$GITHUB_OUTPUT"
- id: dotnet
name: 编译 .NET
continue-on-error: true
run: |
set -o pipefail
dotnet restore GC.sln > "$GITHUB_WORKSPACE/dotnet-restore.log" 2>&1
dotnet build GC.sln -c Release --no-restore 2>&1 \
| tee "$GITHUB_WORKSPACE/dotnet-build.log"
exit ${PIPESTATUS[0]}
- id: flutter
name: Flutter 静态分析
continue-on-error: true
working-directory: GC-UI/frontend
run: |
set -o pipefail
# 日志统一写到仓库根目录:后面的汇总步骤在根目录读,路径必须一致
flutter pub get 2>&1 | tee "$GITHUB_WORKSPACE/flutter-pubget.log"
# 仓库里已有历史 warning / info,不应该让它们卡住合并;
# 只把真正的 error 当失败。
flutter analyze --no-fatal-infos --no-fatal-warnings 2>&1 \
| tee "$GITHUB_WORKSPACE/flutter-analyze.log"
exit ${PIPESTATUS[0]}
- id: summary
name: 生成审查结论
if: always()
env:
DOTNET_OUTCOME: ${{ steps.dotnet.outcome }}
FLUTTER_OUTCOME: ${{ steps.flutter.outcome }}
CONFLICT: ${{ steps.branch.outputs.conflict }}
BEHIND: ${{ steps.branch.outputs.behind }}
AHEAD: ${{ steps.branch.outputs.ahead }}
PR: ${{ github.event.pull_request.number }}
run: |
set -e
bad=0
# 静态分析结果分「错误」和「警告/提示」:只有错误才算不通过
FE=$(grep -cE '^ *error •' flutter-analyze.log 2>/dev/null || true); FE=${FE:-0}
FW=$(grep -cE '^ *(warning|info) •' flutter-analyze.log 2>/dev/null || true); FW=${FW:-0}
case "$DOTNET_OUTCOME" in
success) DOTNET_LINE="✅ .NET 编译通过" ;;
*) DOTNET_LINE="❌ .NET 编译失败"; bad=1 ;;
esac
case "$FLUTTER_OUTCOME" in
success)
if [ "$FW" -gt 0 ]; then
FLUTTER_LINE="✅ 无错误(另有 ${FW} 条历史 warning/info,未阻断)"
else
FLUTTER_LINE="✅ 无错误"
fi ;;
*) FLUTTER_LINE="❌ 有 ${FE} 个 error"; bad=1 ;;
esac
case "$CONFLICT" in
ok) CONFLICT_LINE="✅ 与目标分支无冲突" ;;
conflict) CONFLICT_LINE="❌ 与目标分支存在冲突,需要先解决"; bad=1 ;;
*) CONFLICT_LINE="⚠️ 冲突状态暂时无法判断(稍后重跑)" ;;
esac
if [ "${BEHIND:-0}" -gt 0 ] 2>/dev/null; then
BEHIND_LINE="⚠️ 落后目标分支 **${BEHIND}** 个提交,建议先 rebase / merge"
else
BEHIND_LINE="✅ 已包含目标分支最新提交"
fi
if [ "$bad" = 0 ]; then
HEAD="## ✅ PR 自动审查通过"
else
HEAD="## ❌ PR 自动审查未通过"
fi
{
echo "$HEAD"
echo
echo "| 检查项 | 结果 |"
echo "| --- | --- |"
echo "| 能否编译 | $DOTNET_LINE |"
echo "| 代码检查 | $FLUTTER_LINE |"
echo "| 合并冲突 | $CONFLICT_LINE |"
echo "| 分支同步 | $BEHIND_LINE |"
echo
echo "本次提交领先目标分支 ${AHEAD:-0} 个提交。"
echo
echo "<details><summary>详细日志</summary>"
echo
echo '```'
echo "== dotnet build(尾部 40 行)=="
tail -40 dotnet-build.log 2>/dev/null || echo "(日志缺失:编译步骤可能未执行)"
echo
echo "== flutter analyze(尾部 40 行)=="
if [ -f flutter-analyze.log ]; then
tail -40 flutter-analyze.log
elif [ -f flutter-pubget.log ]; then
echo "(analyze 未产生日志,pub get 输出如下)"
tail -20 flutter-pubget.log
else
echo "(日志缺失:Flutter 步骤可能未执行)"
fi
echo '```'
echo
echo "</details>"
echo
echo "_由 PR 自动审查生成;推送新提交后会更新本条评论。_"
echo
echo "$MARKER"
} > body.md
- name: 写入 / 更新 PR 评论
if: always()
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
PR: ${{ github.event.pull_request.number }}
run: |
set -e
[ -f body.md ] || exit 0
CID=$(gh api "repos/${{ github.repository }}/issues/${PR}/comments" --paginate \
--jq ".[] | select(.body | contains(\"$MARKER\")) | .id" | head -1 || true)
if [ -n "$CID" ]; then
gh api -X PATCH "repos/${{ github.repository }}/issues/comments/${CID}" \
-F body=@body.md >/dev/null
else
gh api -X POST "repos/${{ github.repository }}/issues/${PR}/comments" \
-F body=@body.md >/dev/null
fi
-17
View File
@@ -54,20 +54,3 @@ GC-UI/frontend/test/shots/
# GC.Tests 离屏渲染输出(dotnet run ... GC.Tests 默认写到仓库根 screenshots/)
screenshots/
# 构建/发布临时文件(禁止入库)
decrypt.js
script_*.js
*.mp4
courseware/
.GC/UI/frontend/courseware/assets/*.png
.workbuddy/
# 课程离线课件的单文件产物(79MB,由构建生成,不入库)
等高线.html
# 工具链临时备份
buildsh/cross/*.cmake.bak
# Gradle 全局缓存(不是项目文件)
.gradle-home/
-122
View File
@@ -1,122 +0,0 @@
# 2026-11-19 工作日志
## GC 项目 Flutter 1.1.1 编译环境配置
### 项目结构关键发现
- 仓库有两个远程:`origin`(Avalonia 版,分支 `main`)和 `origin2`(**Flutter 版**,分支 `origin2/main`,tag `1.1.1`)。
- 用户口中的"C#+Flutter 项目"指 **origin2/main**:`GC-UI/` 是前后端分离实现——Flutter 前端(`GC-UI/frontend/`)+ .NET 8 后端(`GC-UI/backend/GC.UI.Server/`)。模型窗口仍由后端用 Avalonia 承载(契约不可变)。
- 当前 `main` 分支是纯 Avalonia 版,无 Flutter 代码。最初误判"没有 Flutter",实际在另一远程分支。
### 分支操作
- 原 `main` 有未提交改动(8 个文件,version.json 从 1.0.7 手改成 1.1.1),已 stash 到 `stash@{0}`(message: `backup-before-flutter-switch-20261119`)。
- 已新建本地分支 `flutter-1.1.1` 跟踪 `origin2/main`,HEAD 在 tag `1.1.1`(commit 3c74eff)。
### Flutter 环境(已完成)
- 工程锁定 Flutter **3.24.5**(Dart 3.5.4),依据是 `GC-UI/frontend/.metadata` 的 revision `dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668`,与官方 release hash 一致。
- SDK 安装在 `/Users/lixi/development/flutter`,zip 校验 sha256 `ca9624a6de7a1a8962f2f0a3e2a57b16434ca34f1137b8d9dc68c5ca1f187133`。
- 国内镜像(快 100 倍,8MB/s):`FLUTTER_STORAGE_BASE_URL=https://storage.flutter-io.cn`、`PUB_HOSTED_URL=https://pub.flutter-io.cn`。
- 已把 PATH 和两个镜像变量写入 `~/.zshrc`。
- `flutter pub get` 成功,`flutter analyze` 零问题(代码本身健康)。
- 注意:Flutter 构建命令需在无沙箱模式下运行(需写 SDK 缓存目录 `.pub-preload-cache`)。
### 编译阻塞(待用户处理)
- 目标 macOS 版,但本机**只有 Command Line Tools,无完整 Xcode**(`xcodebuild` 不存在)。
- `flutter build macos --release` 实测报错 exit 72:`xcrun: error: unable to find utility "xcodebuild"`。
- App Store 无 Apple ID 登录态(MobileMeAccounts / 钥匙串均无凭据),命令行无法无人值守安装 Xcode。
- 用户选择:**自己手动在 App Store 登录并安装 Xcode**,装完后再继续 `flutter build macos`。
- 备选方案(用户未选):本机可用 `buildsh/cross/build-ui-win-cross.sh` 走 mingw-w64 + wine 交叉编译 Windows 版(需 `brew install mingw-w64 cmake ninja` + `brew install --cask wine-stable`),Rosetta 2 已安装。
### 编译完成(Xcode 27.2 装好后)
用户手动装好 Xcode 27.2(`/Applications/Xcode.app`,xcode-select 已指向)。编译过程连破 3 个新 Xcode 兼容问题:
1. **部署目标过低**:`macos/Runner.xcodeproj/project.pbxproj` 三处 `MACOSX_DEPLOYMENT_TARGET = 10.14` → 改为 `12.0`(Xcode 27 最低支持 12.0)。这是对工程文件的持久化改动。
2. **lipo -verify_arch 参数解析变更**:Flutter 3.24.5 的 `packages/flutter_tools/lib/src/build_system/targets/macos.dart` 一次性传多个架构给 `-verify_arch`,Xcode 27 的 lipo 报 "requires exactly one input file"。改为逐个架构分别验证。改后需删 `bin/cache/flutter_tools.stamp` 强制重建 snapshot 才生效。
3. **假符号链接**:解压 Flutter SDK 时沙箱把 `.framework` 里的符号链接写成文本文件路径(内容是 `Versions/Current/...`),导致 SwiftPM 报 `Unable to resolve module 'FlutterMacOS'`。按「先 Versions/Current→A,再顶层 4 个链接」顺序修复,共 19 个(SDK artifacts 15 + build 目录 4)。修复脚本思路见 `/tmp/fix2.sh`(临时)。
**产物**:`GC-UI/frontend/build/macos/Build/Products/Release/GC-UI.app`(38MB,版本 1.1.1,universal x86_64+arm64,adhoc 签名,bundle id com.morris.gc.gcUi)。
交付 zip:`dist/GC-UI-1.1.1-mac-universal.zip`(16MB,sha256 `55f40c146e86cfed3adc1f02a72ab89944dd81ba8e9c8ba6cf929f7061573db5`)。
注意:这是 Flutter 前端外壳,需 .NET 后端(GC.UI.Server / GC-BOOT 进程内托管)配合才能完整工作。完整发布包 `GC.app` 需走 `build.sh build`,但该流程强制走 Windows 交叉编译(wine/mingw,本机装不了,Homebrew 被沙箱拦截),故未跑完整发布。
### "打开即连好"完整发布包(用户反馈单独 GC-UI.app 报"无法连接后端")
根因:Flutter 前端不含后端,靠 `GC_UI_PORT` 环境变量 / `.GC/ui-backend.json` 发现后端。正统入口是 `GC-BOOT`(产物 `GC`):`FlutterShell.TryRun` 在进程内起后端 → 选端口 → 拉起 `GC-UI.app/Contents/MacOS/GC-UI` 并传入 `GC_UI_PORT` → 前端自动连上。单独双击 GC-UI.app 必然连不上。
手动只构建 macOS 完整包(绕开装不了的 wine/mingw):
1. `dotnet publish GC-BOOT/GC-BOOT.csproj -c Release -r osx-arm64 --self-contained -p:... -o dist/mac-arm64`(GC-BOOT.csproj 已把后端作库引用,`FrameworkReference Microsoft.AspNetCore.App`,一个 exe 够用)
2. 同样 publish `GC-SAVEDOG`(裁剪)
3. 复制 GC-UI.app 到 dist/mac-arm64
4. 组装 GC.app:Info.plist(版本 1.1.1)+ Contents/MacOS 放 GC/GC.UI.Server.runtimeconfig.json/GC-UI.app,SAVEDOG 收进 `.GC/bin`,iconutil 从 icon-1024.png 生成 AppIcon.icns
5. `ditto -c -k --sequesterRsrc --keepParent` 打包
**验证通过**:`open GC.app` 后用 curl 查 `http://127.0.0.1:17890/api/health` 返回 `{"ok":true,"version":"1.1.1","platform":"osx-arm64"}`;frontend 进程 GC-UI 在跑;models/settings/about API 全部正常。测试完已 pkill 并清掉 .GC 运行数据。
最终交付:`dist/mac-arm64/GC-1.1.1-mac-arm64.zip`(72MB,sha256 `3bb4101fee9588b1a3b73dcf2e65bc081b83220e5fbbe18a433ee2af8ccfb5e3`),解压得 GC.app,双击即自动连好后端。旧的 `dist/GC-UI-1.1.1-mac-universal.zip` 只是纯前端,已被取代。
注意:dotnet publish 的 `-o dist/mac-arm64` 不会清旧文件;`rm -rf dist/mac-arm64` 会触发批量删除保护(156 文件)。发布包数据目录落在 dist/mac-arm64/.GC(AppPaths 回退逻辑),启动器日志里 SAVEDOG 显示"未找到"是因为它找的是同级而非 .GC/bin,不影响主流程。
### 真正根因:App Sandbox 缺 network.client(用户第二次反馈仍连不上)
上面的"验证通过"是**假阳性**:只 curl 了后端(后端在沙箱外,当然正常),从没让前端真发请求。前端报"无法连接后端(baseUrl)"是 api_client.dart:428 的 ApiException。
真因:`GC-UI/frontend/macos/Runner/Release.entitlements` 只开了 `com.apple.security.app-sandbox=true`,**没有 `com.apple.security.network.client`**。沙箱内进程向 127.0.0.1:17890 发起出站 HTTP 会被内核拒绝(EPERM),所以发布版前端连不上;DebugProfile.entitlements 有 network.server 所以开发时正常,掩盖了问题。用 `codesign -d --entitlements :- GC-UI.app` 可确认签名里只有 app-sandbox。
修复:给 Release.entitlements 加 `network.client` + `network.server` → 重新 `flutter build macos --release`(新签名自动嵌入)→ 替换 GC.app 内 GC-UI.app → 重打包。
**这次验证到位**:`open GC.app` 后 `lsof -nP -a -p <前端PID> -iTCP` 显示 `GC-UI ... TCP 127.0.0.1:60082->127.0.0.1:17890 (ESTABLISHED)`——前端真连上了。这才是"打开即连好"的硬证据。
最终交付覆盖更新:`dist/mac-arm64/GC-1.1.1-mac-arm64.zip`(72MB,sha256 `2b0f4c25ce4e52edf18a45ceb2fe2f91612757db5589f346ffd984665cab5172`),包内前端签名已含 network.client/server。
教训:验证桌面端"连后端"必须看**前端进程的网络连接**(lsof),不能只 curl 后端。无 GUI 会话时 screencapture/AppleScript 不可用。
### 恢复用户改动
回到 `main` 后执行 `git stash pop` 恢复 `stash@{0}` 的 8 个文件改动。
当前 checkout 分支:`flutter-1.1.1`(跟踪 origin2/main,tag 1.1.1)。
### 提交 PR 到 xhmcl(Gitea 28.1.0,git.xhmcl.com/Morris/GC)
分支 `fix/macos-release-sandbox-network`(commit 3efdf74),**只含本次修复两文件**:`Release.entitlements`、`project.pbxproj`。
严格排除了干扰项:`model/contour-map/*`(他人地貌改动)、`pubspec.lock`(配国内镜像 pub get 的副作用,不能提交)、未跟踪的 mp4/js/html 等。
PR #28:https://git.xhmcl.com/Morris/GC/pulls/28 (base main,state open,mergeable=true,+7/−3,2 files)。
**凭据/接口要点(踩坑记录)**:
- 该实例 git 协议与 API 认证分离。`gdt_...` 是 git 凭据(当密码用可 push),但调 API 全部 401(Authorization: token/Bearer、X-Token、PRIVATE-TOKEN、query 都试过)。
- 建 PR 必须用**账号登录密码**做 basic auth:`curl -u 'Morris:<密码>' -X POST .../api/v1/repos/Morris/GC/pulls -d @body.json`,返回 201。
- push 时若报 "unable to get credential storage lock: File exists",用 `git -c credential.helper= push` + `GIT_ASKPASS` 脚本绕过;其实首次已推成功,是误报。
- 临时凭据文件(netrc/askpass/pr.json)用完即删,不落盘留存。
- 注意:本机无图形会话时 screencapture/AppleScript 不可用;验证"前端连后端"必须用 `lsof -nP -a -p <PID> -iTCP` 看 ESTABLISHED。
### 模型无法启动 + 后端崩溃(PR #29)
**根因**:macOS 的 AppKit 要求 NSApplication 在**主线程**。Flutter 模式下 `FlutterShell` 用 `ui.WaitForExit()` 占住主线程,而 `AvaloniaHost` 在 `new Thread(...)` 副线程里跑 `StartWithClassicDesktopLifetime`。点「启动模型」时模型窗口在副线程触碰 AppKit → 进程级崩溃,后端随之消失(表现为"无法启动模型"+"后端容易崩溃")。纯 Avalonia 版不受影响,只在 Flutter 打包模式暴露。
**修复**(4 文件,+114/−51):
- `AvaloniaHost`:新增 `RunOnCurrentThread()`/`Shutdown()`,`EnsureStartedAsync()` 改为只等 `_ready`,不再自建线程。
- `BackendServer.Start(args, port, out AvaloniaHost)` 重载(out 参数不能在 lambda 里用,内部用局部 `host`)。
- `FlutterShell`:前端拉起后在主线程跑 Avalonia 事件循环,`ui.Exited` 时后台 `Shutdown()`;Avalonia 不可用时退化 `WaitForExit()`。
- `Program.cs`:`app.StartAsync()` 后主线程跑 Avalonia,失败则 `WaitForShutdown()`(需 `using Microsoft.Extensions.Hosting`)。
**验证**:`/api/health` → `uiAvailable:true`;前端 `ESTABLISHED →17890`;`POST launch` → `HTTP 200 {"ok":true,"message":"已启动模型 contour-map"}`;启动后后端存活。
**交付**:`dist/mac-arm64/GC-1.1.1-mac-arm64.zip`(72MB,sha256 `4b3978eab5cb8fba4e97a3a623cb532080b9e0e24dd6f3e28e69440966c510bb`)。
PR #29:https://git.xhmcl.com/Morris/GC/pulls/29
**坑**:`dist/mac-arm64/GC.app` 在清理 `.GC` 时被误删过;可从 `/tmp/gc-fresh-test/GC.app` 取 `GC-SAVEDOG` 与结构,配合 `/tmp/gc-new/GC`(publish 产物)+ build 目录新前端重建。组装脚本见上面的"打开即连好完整发布包"步骤。
## contour-map 模型重写(对照加密 HTML 课件移植)
**背景**:用户提供的 `~/Downloads/等高线及地形部位演示.html`(79MB)是授权壳 + AES-256-GCM + gzip 的课件,内含 Three.js 版五大地貌演示。已在本地用 node 复现解密(key = 两数组异或,AAD `QLAB|contour-landform-reading|...`),还原出 83MB 内部课件;其内容为「10 张内嵌 PNG + 切割视频 + 标注层」,并非可交互 3D。按用户要求改为在 `model/contour-map` 用 C#/Avalonia 重写。
**改动文件**(均在 `model/contour-map/src/`):
- `TerrainField.cs`:新增 `LandformKind`(Peak/Ridge/Valley/Saddle/Cliff)与五个高度场生成器。要点是地形要**宽阔**(穹状山体、宽脊、V 形谷、双峰垭口、台地陡崖),半径过小会变成“尖锥/薄墙”。
- `ContourView.cs`:重写为可交互 3D(拖动旋转、滚轮缩放),四步实验(切割/成线/投影/判坡),俯视/立体切换,自动取景 `UpdateCamera`(按包围盒八点投影铺满画布),法线光照,裙边侧壁,分层设色在 3D 用 `ColorForHeightSmooth` 平滑过渡、俯视仍用硬分档。
- `ContourPage.cs`:地貌标签移到画布上方(WrapPanel,窄屏自动换行);右侧栏 344px,<980px 自动隐藏;四步流程/观察面板/判读要点;底部播放、重置、视图切换、上色、实时读数;空格与 1–5 快捷键;全屏。
- `DefaultTexts.cs`:90 个键,中英各一套。
- `ContourMapRuntime.cs`:`LoadTexts` 改为「内置默认 + i18n/*.json 覆盖」,之前完全忽略语言包。
- 清单 `contour-map.json` 版本 1.1 → 1.2;`help.json` 同步新交互。
**修掉的真实 Bug**:
1. `ExtractContour` 的 `Chain()` 只向尾部延伸,一条等高线被切成大量短链 → 3D 里显示成**虚线等高线**。改为端点索引 + 双向延伸后,每层只剩 1 条 300+ 点的完整曲线。
2. `SlopeAt` 固定除以 450,导致山体坡度全饱和为 1(整片红),“疏密判坡”失效。改为按 `span*2.6` 自适应归一化。
3. 切割步骤原本只是叠一张半透明板,山尖仍在。改为把高度场压到切面 `min(h, lv)`,得到真实截面,并用 `ExtractContour(lv)` 精确求交线。
4. 切割时山峰标注悬在切面上方 → 高于切面的山峰不再标注。
**性能**:62×62 面片 + 画刷颜色缓存,1440×900 离屏单帧约 35ms(≈28fps),可接受。
**验证**:`dotnet build` 0 警告 0 错误;`dotnet run --project model/_engine/PreviewGen` 全模型离屏渲染通过并生成封面;自建 `/tmp/ccheck` 全尺寸渲染器逐状态出图核对(默认/俯视/五地貌/四步/中间帧)。
**交付**:PR #30 https://git.xhmcl.com/Morris/GC/pulls/30(`feat/contour-map-rewrite` → `main`,12 文件 +1903/-600,基于最新 main 单提交)。提交 PR 时注意:本地 `flutter-1.1.1` 落后 origin2/main 4 个提交,需先 stash 改动、从 `origin2/main` 建分支再 pop,否则 PR 会带上 48 个无关提交;gitcode(origin) 的 main 更旧且仍是 `NeoRF.*` 命名空间,不宜作为 PR 目标。推送用 `GIT_ASKPASS` 临时脚本传凭据,用完即删,不写 remote URL。
-338
View File
@@ -1,338 +0,0 @@
# 2026-11-21 工作日志
## 把加密 HTML 课件搬进 Flutter 前端(WebView 渲染)
**需求转变**:之前用 C# 重写 contour-map 模型,用户反馈"不够还原",改为直接把原课件搬进 Flutter,用 WebView 原样渲染(100% 还原),去验证 + 优化。
**去验证 / 拆资源**(产物在 `GC-UI/frontend/courseware/`):
- 原始 `~/Downloads/等高线及地形部位演示.html`(79MB)是授权壳(AES-GCM+gzip);解密后 83MB 单文件。
- 写出拆分脚本:CSS、视频、背景图、3 段 JS 抽成独立文件;app.js 里 10 张 data:image/png 抽成 `peak/ridge/valley/saddle/cliff-{3d,top}.png` 并改为相对路径。
- 生成纯净 index.html:去掉 QLAB 注释、零宽水印 span、授权声明 div+style;CSP 放宽为允许 self/data/blob(否则 WebView 加载不了本地资源)。
- 优化:11 张 PNG(全是不透明 RGB)用 sips 转 JPEG(q88),83MB → 27MB(HTML 本体 20KB);视频 17MB 保留原样(核心内容不劣化,且本机无 ffmpeg)。
- 验证无残留:0 个 base64 / QLAB / 授权声明;JS 引用的 42 个 DOM id 全部存在;16 个资源引用无缺失。
**Flutter 接入**:
- 依赖 `flutter_inappwebview: 6.1.5`(兼容 Flutter 3.24.5 / Dart 3.5.4;桌面 Win/mac/Linux 都支持;6.2-beta 要 Flutter 3.32 故不用)。
- 新增 `lib/pages/courseware.dart`:Dart 自带 `HttpServer.bind(loopbackIPv4, 0)` 静态服务器(端口自动分配、含 HTTP Range 支持供视频拖动、路径规范化防越界),把课件 assets 用 `AssetManifest.loadFromAssetBundle(rootBundle)` 解压到系统临时目录再提供给 WebView。
- **坑1**:`InAppLocalhostServer` 的 `port` 是 final,`port=0` 不会回写实际端口 → 弃用,改用 Dart 自带 HttpServer。
- **坑2**:打包后工作目录不固定,不能用相对路径读 assets → 必须解压到临时目录。
- **坑3**:AssetManifest 里的 key 是 `courseware/xxx`(不是 `assets/courseware/xxx`)→ 用 `flutter build bundle --asset-dir /tmp/xx` 检查实际 key。
- `shell.dart`:导航项插在 index=1(主页之后),_buildPage case 顺延;home.dart 的 `goTo(1)/(2)` 改为 `goTo(2)/(3)`;**课件页在 `_content` 里放到 backendReady 检查之前**(纯前端不依赖后端)。
- i18n 加 `nav.courseware`(等高线课件 / Contour Course);macOS Debug entitlements 补 `network.client`。
- pubspec assets 声明 `courseware/` + `courseware/assets/`。
**验证**:`flutter analyze` 零问题;`flutter build macos --debug` 成功;实际启动 app(临时把 `index=1` 后编译)截图确认 WebView 完整渲染出课件(标题、四步流程、地貌标签、播放按钮)——之后已恢复 `index=0` 并重编最终版。
**环境坑(本机 macOS)**:
- 系统 Ruby 2.6 装不了 CocoaPods(需 Ruby≥3)→ `brew install cocoapods`(brew 自带 Ruby 4)。
- brew auto-update 卡住 → `HOMEBREW_NO_AUTO_UPDATE=1`。
- CocoaPods CDN 走代理 SSL 证书校验失败 → `pod repo add trunk-git https://github.com/CocoaPods/Specs.git` + `GIT_SSL_NO_VERIFY=true`;完整 specs 约 3.4GB,clone 超时后目录保留,手动 `git checkout -f master` 完成展开,再 `pod install` 成功。
- GUI 自动化:System Events 的点击/置前被权限拒绝(-10004),但 `tell application "GC-UI" to activate` 可用;验证 GUI 靠 activate + screencapture。
## 提交 PR
- PR #30(C# 3D 模型重写)已合入 `main`(合并提交 `4ef2915`)。
- 从最新 `origin2/main` 新建独立分支 `feat/flutter-courseware`,只提交 Flutter 课件方案(30 文件,含 17MB 视频与 10 张 JPEG),与工作区里那批无关的 C# 安全改动隔离。
- 提交 `355ca89`;已推送到 `origin2` 并通过 Gitea API 创建 **PR #32**:https://git.xhmcl.com/Morris/GC/pulls/32 ,状态 open、mergeable=true。
- PR 草稿说明中注明「C# 重写已在 PR #30 合入 main」,避免与已合入内容混淆。
## 安全修复 PR #33(四类风险)
- 从 fetch 后的最新 `origin2/main`(`1dd3b40`,含 #32 课件)建隔离 worktree `/tmp/gc-security`,分支 `fix/security-hardening`,只应用 7 个安全文件补丁(ModelInstaller / DirectoryRemote / FlutterShell / BackendServer / ApiModels / api_client.dart / DownloadContracts),排除用户工作区里课件/构建副作用;`flutter pub get` 改了 pubspec.lock 已 checkout 还原后 amend。提交 `46ed844`(+305/−34)。
- 验证:dotnet build 0 错误、flutter analyze 0 问题;自建反射测试 32/32(恶意 Id 拒绝 14/14、合法放行 4/4、SafePath 符号链接 5/5、URL 9/9);实机 open GC.app 无/错 token 受保护接口 401、前端 ESTABLISHED→17890。
- 注意:`GC-DOWNLOAD/DirectoryRemote.cs` 验签是「记录 + SignatureTrust 上送,由 UpdateService/LauncherUpdater 统一闸门拒绝」,与 GiteaRemote/GitCodeRemote 设计一致,未在 DirectoryRemote 内直接 return null。
- `--update-test` 19 项失败是**既有测试夹具密钥不匹配**:`.signing/gc-signing.pem` 派生 gc-2026-11 公钥,但测试用 gc-2026-12 硬编码公钥验签,连正常签名清单都判 Invalid;与安全补丁无关(未碰签名文件),篡改相关断言通过。
- push 用邮箱 `chenmoyuan1214@qq.com` + rotated `gdt_` token(askpass)成功;API 建 PR 用登录名 `Morris` + 登录密码(Basic auth)。凭据用完即删。
- **PR #33**:https://git.xhmcl.com/Morris/GC/pulls/33 (base main,open、mergeable=true,7 文件 +305/−34)。
## 15 项优化与 bug 修复(PR 待创建)
- 用户提交 15 项优化/bug 反馈,在隔离 worktree `/tmp/gc-fixes` 分支 `fix/improvements`(tracking origin2/main)上逐一修复。
- 已修改 13 个文件:`+348/-42`。
- 关键修复:
- **#1** DirectoryRemote/GiteaRemote/GitCodeRemote 验签失败时 return null(不再静默传递不可信清单)
- **#2** LauncherUpdater 所有源失败时输出明确错误信息
- **#5** HealthInfo 新增 sessionProof 字段
- **#6** PortScanRange 10→30
- **#7** MemoryBudget 注释澄清 GC 托管内存 vs 物理内存
- **#9** GcLog RetentionDays 14→7
- **#11** SavedogLauncher 检查 Process.Start 返回值
- **#12** FlutterShell.IsHealthy → 异步 IsHealthyAsync,WaitHealthy → WaitHealthyAsync
- **#14** DirectoryRemote Walk 增加 IsIgnoredDir,与远端源一致
- 构建验证:dotnet build 0 错误,flutter analyze 0 问题。
- 已 push 到 `origin2/fix/improvements`,提交 `a407c93`。
- **冲突解决**:PR #33 已将 DirectoryRemote 验签改为"记录日志+上送状态"(不 return null),我们的分支原来改成 return null 与其冲突。rebase 到最新 main(4043ed5)后以 main 改动为基础,仅叠加增量(9 文件 +36/-9),提交 `9cd4fa6`,force push 成功。
- Git 服务器自动创建 **PR #34**:https://git.xhmcl.com/Morris/GC/pulls/34 (open、mergeable=true)
- PR #34 已合并到 main(提交 4043ed5)。
- 基于最新 main 重新推送 `fix/improvements`,创建 **PR #35**:https://git.xhmcl.com/Morris/GC/pulls/35 (open、mergeable=true,9 files +36/-9)
- 交付 zip `dist/mac-arm64/GC-1.1.1-mac-arm64.zip` 仍是 11-19 旧包;`GC.app` 已是安全构建,未重新打包(用户未要求)。
## 补充:1.1.2 编译错误修复(同日 10:20)
用户构建 osx-arm64 报 3 个编译错误,根因与修复:
1. `SharedHttpClientFactory.cs`:`DecompressionMethods` 属于 `System.Net` 命名空间,
原代码误写为 `System.IO.Compression.DecompressionMethods`。改为 `using System.Net`。
(曾误加 System.IO.Compression 4.3.0 NuGet 包,net8.0 上会遮蔽框架类型,已移除)
2. `ModelHost.cs`:`VersionUtil` 定义在 GC-DOWNLOAD,GC.Core 不能反向引用(会循环依赖)。
用 `git mv` 把 `GC-DOWNLOAD/VersionUtil.cs` 移到 `GC/src/Services/VersionUtil.cs`
(namespace GC.Services 不变,GC-DOWNLOAD 通过引用 GC.Core 仍可用)。
连带发现并修复(同一批 1.1.2 半成品重构):
3. `SourceSelector.cs:82`:双语日志 GcLog.Info 调用括号/引号写坏 → 修正
4. `ModelSourceClient.cs`:重构误删 `_paths` 字段+构造函数但代码仍在用 → 恢复
5. `FlutterShell.cs`:缺 `using GC.Services` → 补上
6. 构建脚本 `build_funcs.sh`/`check.sh`/`build-ui-win-cross.sh` 共 4 处 `$VAR(` 全角括号
紧跟变量导致 `set -u` 报 "DEST: unbound variable"(历史遗留 bug)→ 改为 `${VAR}`
编译结果:
- GC-BOOT single-file osx-arm64 + GC-SAVEDOG + Flutter GC-UI.app 全部成功
- 产物:`dist/mac-arm64/GCL-1.1.2-mac-arm64.zip`(99MB,arm64)
- 冒烟测试:`./GC` 后端正常监听 127.0.0.1:17890,版本 1.1.2
备注:build.sh 的清理阶段 `rm -rf dist` 会触发批量删除安全拦截,改为手动调用
publish_rid/build_flutter_ui/package_mac_app 函数完成,未绕过安全机制。
version.json 各平台 sha256/size 仍为空(等 release 上传后统一填),未单独填 macOS。
## 补充:贡献者归并把"远影科技"算入 Morris(10:29)
用户反馈"关于"页开发者列表里"远影科技"(4 次提交)应并入 Morris。
根因:ContributorsService.Aliases 未收录该 git 身份。
查明其身份:name=远影科技 / email=yuanying@yuanying.tech(无 login),
且有一条 Morris 提交共用 yuanying@yuanying.tech 邮箱。
修复:在 Aliases 增加两条映射("远影科技" 和 "yuanying@yuanying.tech" → "Morris")。
用真实 Gitea API 数据模拟归并验证:Morris 45 次(原 41 + 远影科技 4),正确。
已重新编译并打包 macOS 1.1.2(zip sha256 53130e63...4332a)。
## 补充:完整构建"没有出现 .app"问题(10:36)
用户跑完整 `build.sh build` 后没有 .app,贴的日志里有
`error: the following command failed with exit code 0 but produced no further output`
+ 大量 Swift warning(flutter_inappwebview 第三方库的弃用警告)。
澄清:那个 exit code 0 + 最后 `✓ Built GC-UI.app` 说明 Flutter 前端编译成功,是误导性输出。
真正原因:完整脚本在"编译 Windows 前端"步骤失败——flutter-win-cross.log 显示缺 cmake,
脚本 return 1 提前退出,没走到后面的 package_mac_app / pack_launcher 打包步骤。
解决:mac 三个组件都已编好(dist/mac-arm64/ 下 GC + GC-SAVEDOG + GC-UI.app),
手动调用脚本的 package_mac_app + pack_launcher 完成打包。
最终产物:dist/mac-arm64/GCL-1.1.2-mac-arm64.zip(99MB,含全部 122 文件)。
## 环境:为本机安装 Wine(12:25)
需求:在 Apple Silicon macOS 27.3 上安装 Wine。
过程要点(踩坑记录):
- Homebrew 的 wine-stable / wine@staging / wine@devel 三个 cask 全部被禁用
("does not pass the macOS Gatekeeper check",2026-09-01 起),brew 装不了。
- 官方 WineHQ macOS 包仍是 5.0/5.7(2020 年),太旧,不用。
- 采用 gcenx/wine tap 对应 GitHub 的 Gcenx/macOS_Wine_builds:wine-staging 11.21。
- 稳定版 11.0_1 资源下载仅 26 KB/s(brew 卡死 9 分钟的真正原因,非网络故障);
staging 11.21 直连约 78 KB/s,经 ghfast.top 镜像达 1.8 MB/s。
做法:镜像 curl 下载 → 校验 sha256 → 放入 Homebrew 缓存 → 仍不建议依赖 brew。
- 最终手动安装(包内自带 .app):
ditto 到 /Applications/Wine Staging.app → xattr -dr com.apple.quarantine
→ 把 wine/wineserver/wineboot/winecfg/regedit/msiexec/winepath 等软链到 /opt/homebrew/bin
→ WINEDLLOVERRIDES="mscoree,mshtml=" wineboot -u 初始化 ~/.wine(跳过 mono/gecko 弹窗)
结果:wine-11.21 (Staging),x86_64 经 Rosetta 2 运行;`wine cmd /c ver` 返回 Windows 10.0.19045。
体积:/Applications/Wine Staging.app 872MB,~/.wine 338MB。未签名(故被 brew 禁用),已清 quarantine。
## 五项功能改动(13:30)
1. 关于页「重新下载启动器」:新增 POST /api/launcher/redownload(复用 LauncherUpdater.DownloadAsync,
按清单 sha256 逐块校验,缺 sha256 直接拒绝)→ 下载后暂存 .GC/update,重启生效。
api_client._send 增加 timeout 参数(默认 POST 120s 不够下载 100MB)。
2. 下载页提速:源列表 / 任务列表 / 模型索引三个请求改为并发,源列表先渲染,
不再等三轮串行。
3. 模型下载按钮内联进度条:按 JobInfo.modelId 匹配模型,按钮位变成 百分比 + 进度条 + 取消。
4. macOS Dock 双图标:新增 GC-BOOT/MacDock.cs,在「确实要拉起 Flutter 前端」时
把本进程设为 NSApplicationActivationPolicyAccessory(隐藏 Dock);Avalonia 回退分支不受影响。
5. 自绘标题栏:MainFlutterWindow 隐藏系统标题栏(titleVisibility/.hidden、fullSizeContentView、
三个系统按钮隐藏),Flutter 侧 lib/window_chrome.dart 提供 gc/window 通道
(minimize/toggleMaximize/close/isMaximized/beginDrag),shell.dart 顶部挂 GcTitleBar。
坑:NSWindow 没有 unzoom(_:),zoom(_:) 自带切换语义。
## Avalonia 全量移除 + Dock 修复 + 标题栏配色(13:55)
1) Dock 双图标:运行期 setActivationPolicy 不生效,改为打包时给 GC.app 的 Info.plist 加
`LSUIElement=true`(启动器只是后端宿主);MacDock.cs 保留作双保险。实测 plist 已写入、包内无 Avalonia。
2) 移除 Avalonia(彻底):
- 删:GC/src/{App.axaml,App.axaml.cs,Views,ViewModels,Styles,Services/ModelHost.cs,
Services/LauncherUpdateFlow.cs}、GC-BOOT/AvaloniaHost.cs、GC-UI/backend/.../AvaloniaHost.cs、
GC-DRAW、model/_engine/src、model/_engine/PreviewGen、model/_sdk、5 个模型的 src、
GC/src/test/dotnet/GC.Tests(截图工程)
- csproj:GC.Core / GC-BOOT / GC.UI.Server 去掉 Avalonia 包与 ModelSdk 引用
- Localization:avares:// → 嵌入资源(EmbeddedResource GC.Core.Assets.i18n.*)
- 后端:删除 AvaloniaHost、launch 接口改为「客户端内渲染」,health 的 uiAvailable 恒 true
- 模型:新增 lib/models/lookup.dart(后端 id → Flutter 实现)、lib/pages/model_view.dart;
首页「启动模型」→ controller.openModel(id),壳内渲染,不再开窗口
- build_models 简化为只刷清单;check 改为「编译 + 产物」
- 体积:GC 单文件 58MB→44MB,zip 99MB→88MB
3) 标题栏配色:底色 = sideBg 叠 6% accent + 底部 line 描边,跟随主题与强调色。
4) 注意:model/*/*.model/ 里仍有旧的模型 dll(属于模型包内容),运行时不加载,未清理。
## 追加:Dock 三重保险 + 1.1.3(14:20)
用户反馈 Dock 仍是两个。分析:运行时 setActivationPolicy 单独不够,Info.plist LSUIElement 也可能被
LaunchServices 缓存/旧副本干扰。改为三重保险(MacDock.cs + package.sh):
1) Info.plist LSUIElement=true(打包时写入)
2) Carbon TransformProcessType(kProcessTransformToUIElementApplication=4)
3) [NSApp setActivationPolicy:accessory]
启动时打印 "[shell] 启动器以 UIElement 运行" 便于核对。
版本提到 1.1.3(侧栏/关于页可见),并删除旧的 1.1.2 zip 避免误拿。
标题栏底色改为 accent 16% 叠 sideBg,标题文字用 accent。
清理 Directory.Build.props 里已无引用的 AvaloniaVersion。
诊断命令(给用户):osascript -e 'tell application "System Events" to get {name, background only} of every process whose name contains "GC"'
## 修复无法连接后端 + 标题栏配色(14:52)
用户反馈「无法连接后端」。根因:后端写握手文件 `ui-backend.json` 时只写端口没写令牌,
前端在 Finder 直接打开(无环境变量)时就拿不到会话令牌 → 所有 /api 请求 401 → 界面显示「无法连接后端」。
修复:
1) 后端 WriteEndpointFile 把 sessionToken 一并写入
2) 前端 api_client.dart:
- 新增 _readEndpointFile() 从握手文件解析地址+令牌
- defaultBaseUrl 改为依次尝试:define → 环境变量 GC_UI_BASE_URL → GC_UI_PORT → 握手文件 → 兜底
- _sessionToken 改为动态读取(握手文件兜底)
- 新增 rediscover() 方法:后端换端口或握手文件更新时重新解析
- 重试前调用 rediscover() 获取最新地址
3) 设置页提示「令牌已就绪 / 缺少会话令牌」便于诊断
4) 标题栏配色:浅色主题纯白(不再叠强调色),深色主题跟随侧栏底色
同时清理 dist 下残留的 1.1.3 zip,版本号保持 1.1.2。
## 三项改动(16:51)
1. 标题栏颜色:代码已经是 `GcColors.sideBg`(亮色=白色),但用户说没生效——原因是旧构建缓存。
执行 `flutter clean` + 重新构建后打包,应该正常了。
2. 模型回退到 Avalonia:
- home.dart `_launch` 改为调 `api.launchModel(model.id)`(后端接口)
- shell.dart 去掉 activeModel 判断和 ModelViewPage 导入
- 删除 lib/models/lookup.dart、lib/pages/model_view.dart(不再需要)
3. 新增百宝箱页(nav.treasure):
- lib/pages/treasure.dart:今日人品(随机运势文案)+ 幸运颜色 + 幸运数字 + 刷新按钮
- 使用 Random() 生成,每次刷新重新计算
- shell.dart 侧栏添加导航项(Icons.auto_awesome_rounded)
- i18n 中英双语
- 页面路由 case 5
构建:87MB,版本号保持 1.1.2
## Windows 交叉编译问题(17:17)
mingw-w64 14.0.0_3 携带 GCC 16.2,与 Flutter 插件(flutter_inappwebview_windows)不兼容:
- C++20 三路比较(operator<=>)在 EncodableValue 上失败
- mingw 头文件缺少 <cstring> 包含
解决方案:
1. macOS 主机默认只构建 macOS(修改 buildsh/build.sh 的 _want 逻辑)
2. Windows 交叉编译需要在 GCC 13 环境下进行,或改用 Windows CI
已修改:
- buildsh/build.sh: macOS 默认 targets 改为 "mac"
- buildsh/cross/toolchain-mingw.cmake: 添加 C++17 标志和兼容性选项(为将来 GCC 13 准备)
- 临时修复了插件头文件路径问题(复制 .h 文件到 ephemeral 目录)
如需构建 Windows:
- 方法 A:在 Windows 机器上直接 `flutter build windows`
- 方法 B:安装 GCC 13 的 mingw-w64(brew install https://旧版公式 URL)
- 方法 C:设置 CI/CD 流水线在 Windows 上构建
## GitHub 源 + GitHub Actions(19:20)
### 下载源
- `GC/src/Services/SourcePreset.cs`:新增 `GitHub` preset(owner `Morris-morris-cloud`,ApiBase api.github.com,
RawBase raw.githubusercontent.com,RawStyle=`raw`);`All = { Xhmcl, GitHub }`;`Detect` 识别 github.com / 源名。
- `GC-DOWNLOAD/SourceSelector.cs`:单源探测超时改 **2 秒**(ProbeTimeout),CreateRemote 增加 `"github" => GiteaRemote`。
- `GC-DOWNLOAD/GiteaRemote.cs`:新增 `ContentsUrl()`(GitHub 需 `?ref=branch`)与 `ReleasesUrl()`(GitHub 需 `per_page=100`),
删掉不再使用的 `RepoRepoContentsUrl`。GitHub 的 contents/releases API 与 Gitea 同构,复用同一实现。
- 验证:GitHub raw/api 四个端点均 200;仓库目前 0 个 Release(代码已容错,退回仓库清单)。
### CI
- `.github/workflows/nightly-prerelease.yml`:cron `0 13 * * *`(=21:00 Asia/Shanghai),mac+win 两地并行编译,
产物滚动发布到 tag `ip-prerelease`(prerelease=true)。
- `.github/workflows/build-bot.yml`:issue_comment 触发,`@build-bot build mac|win-amd|win-arm|all`,
仅 OWNER/MEMBER/COLLABORATOR 生效;PR 编 head sha,Issue 编 main;用 `gh release upload --clobber` 合并资产。
- `.github/workflows/pr-review.yml`:PR 打开/推送时查 dotnet 编译、flutter analyze、mergeable 冲突、落后 main 提交数,
汇总成带 `<!-- gc-pr-review -->` 标记的单条评论(重复运行只更新)。
- `.github/CI.md`:三套流水线用法与前置设置说明。
- `buildsh/lib/flutter.sh`:新增 `GC_NO_CODESIGN=1` → macOS 加 `--no-codesign`(CI 无签名证书)。
### 其他
- 修了 Windows 交叉编译的「双层 cpp_client_wrapper 嵌套」:flutter-cpp-client-wrapper.zip 自带一层目录,
fetch_engine 的 dest 应到 `windows-x64`;引擎缓存与 ephemeral 里的双层目录已手工拉平。
### 修正(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)
-258
View File
@@ -1,258 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
namespace GC.Services;
/// <summary>
/// 本地目录源:用于离线教学(U 盘 / 共享盘里的仓库副本)与自动化测试。
/// 目录结构与远端仓库一致:version.json + model/&lt;id&gt;/...
/// </summary>
public sealed class DirectoryRemote : IModelRemote
{
private readonly string _root;
// 使用共享 HttpClient(长超时版本)
private static readonly HttpClient Http = SharedHttpClientFactory.GetLongTimeout();
private string? _rawManifest;
private string _launcherVersion = "";
public DirectoryRemote(string root) => _root = Path.GetFullPath(root);
public string DisplayName => _root;
public Task<RepoVersion?> GetVersionAsync(CancellationToken ct)
{
var primary = SafePath("version.json");
var fallback = SafePath(Path.Combine("model", "version.json"));
var file = File.Exists(primary) ? primary : fallback;
if (!File.Exists(file)) return Task.FromResult<RepoVersion?>(null);
// 离线目录同样验签:U 盘 / 共享盘里的清单也可能是被替换过的。
// 验签结论随 version.SignatureTrust 一起上送,由 UpdateService 按策略裁决;
// 这里至少要把失败如实记下来,不能静默丢弃(与 GiteaRemote/GitCodeRemote 保持一致)。
var text = File.ReadAllText(file);
_rawManifest = text;
var version = ManifestLoader.Parse(text, out var verification);
if (verification.Trust is ManifestTrust.Invalid or ManifestTrust.Unsigned)
Console.Error.WriteLine($"[directory] 清单验签失败({verification.Trust}): {verification.Error}");
if (version != null && !string.IsNullOrWhiteSpace(version.Launcher.Version))
_launcherVersion = version.Launcher.Version.Trim();
return Task.FromResult(version);
}
/// <summary>最近一次读到的清单原文(SAVEDOG 二次验签用)。</summary>
public Task<string?> GetRawVersionTextAsync(CancellationToken ct)
=> Task.FromResult(_rawManifest);
public Task<IReadOnlyList<RepoEntry>> ListTreeAsync(string rootPath, CancellationToken ct)
{
var baseDir = SafePath(rootPath ?? "model");
var result = new List<RepoEntry>();
if (!Directory.Exists(baseDir)) return Task.FromResult<IReadOnlyList<RepoEntry>>(result);
Walk(baseDir, baseDir, 0, result);
return Task.FromResult<IReadOnlyList<RepoEntry>>(result);
}
private void Walk(string dir, string baseDir, int depth, List<RepoEntry> result)
{
if (depth > 8) return;
foreach (var sub in Directory.GetDirectories(dir))
{
// 符号链接目录可能指向根目录之外:既不递归进去,也不作为条目暴露。
if (IsReparsePoint(sub)) continue;
var name = Path.GetFileName(sub);
if (name.StartsWith('.')) continue;
var rel = Relative(baseDir, sub);
result.Add(new RepoEntry
{
Name = name,
Path = Relative(_root, sub),
RelativePath = rel,
IsDirectory = true
});
Walk(sub, baseDir, depth + 1, result);
}
foreach (var file in Directory.GetFiles(dir))
{
if (IsReparsePoint(file)) continue;
var name = Path.GetFileName(file);
if (name.StartsWith('.')) continue;
result.Add(new RepoEntry
{
Name = name,
Path = Relative(_root, file),
RelativePath = Relative(baseDir, file),
IsDirectory = false,
Size = new FileInfo(file).Length
});
}
}
public async Task<byte[]> DownloadAsync(RepoEntry entry, CancellationToken ct)
=> await File.ReadAllBytesAsync(SafePath(entry.Path), ct);
public async Task<byte[]?> DownloadPackageAsync(RepoPackage package, CancellationToken ct)
{
// 清单路径 / dist 根目录命名:按仓库内相对路径直接找
foreach (var rel in LauncherArtifacts.CandidateFiles(
package.Rid, package.Dir, package.Path, package.Name, _launcherVersion))
{
string full;
try { full = SafePath(rel); }
catch (InvalidOperationException) { continue; }
if (File.Exists(full)) return await File.ReadAllBytesAsync(full, ct);
}
// dist/<系统>-<架构>/ 里放着的编译产物(与远端同一套查找规则):
// 本地源同样要能跑通「只发产物、不发 Release」的更新方式。
var fromDist = FindInDist(package);
if (fromDist != null) return await File.ReadAllBytesAsync(fromDist, ct);
var url = package.Url;
if (string.IsNullOrWhiteSpace(url)) return null;
// 清单里的 URL 属于外部输入,必须约束来源:
// · file:// 和绝对路径只允许读 _root 之内,杜绝任意本地文件读取;
// · 网络 URL 仅允许 http(s),且目标不能是环回/私有/链路本地/元数据地址,防 SSRF。
if (url!.StartsWith("file://", StringComparison.OrdinalIgnoreCase))
{
var local = new Uri(url).LocalPath;
return await File.ReadAllBytesAsync(SafePath(Path.GetRelativePath(_root, local)), ct);
}
if (Path.IsPathRooted(url))
{
if (File.Exists(url)) return await File.ReadAllBytesAsync(SafePath(Path.GetRelativePath(_root, url)), ct);
return null;
}
if (IsAllowedHttpUrl(url))
return await Http.GetByteArrayAsync(url, ct);
return null;
}
/// <summary>
/// 仅允许 http/https:挡住 file: 导致的任意本地文件读取和 gopher: 之类的协议滥用。
/// IP 字面量直接判公网;主机名(清单里的正常发布 URL)允许,但拒绝 localhost 与
/// 常见本地后缀,避免指向本机。域名解析到内网的情况由 HttpClient 侧的实际连接地址
/// 兜底——本地目录源的主路径本就是本地文件,网络只是兜底。
/// </summary>
private static bool IsAllowedHttpUrl(string url)
{
if (!Uri.TryCreate(url, UriKind.Absolute, out var uri)) return false;
if (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps) return false;
if (uri.HostNameType == UriHostNameType.IPv4 || uri.HostNameType == UriHostNameType.IPv6)
return IsPublicAddress(uri.Host);
var host = uri.Host;
if (string.IsNullOrEmpty(host)) return false;
if (host.Equals("localhost", StringComparison.OrdinalIgnoreCase)) return false;
// 仅允许含点、且各段是字母数字/连字符的常规域名;拒绝 .local/.internal 等本地域。
if (host.EndsWith(".local", StringComparison.OrdinalIgnoreCase) ||
host.EndsWith(".localhost", StringComparison.OrdinalIgnoreCase) ||
host.EndsWith(".internal", StringComparison.OrdinalIgnoreCase))
return false;
foreach (var label in host.Split('.'))
if (label.Length == 0 || label[0] == '-' || label[^1] == '-' ||
!label.All(c => char.IsAsciiLetterOrDigit(c) || c == '-'))
return false;
return true;
}
private static bool IsPublicAddress(string host)
{
if (!IPAddress.TryParse(host, out var ip)) return false;
if (IPAddress.IsLoopback(ip) || IPAddress.Any.Equals(ip) || IPAddress.IPv6Any.Equals(ip)) return false;
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
var b = ip.GetAddressBytes();
if (b[0] == 10 || b[0] == 127 || b[0] == 0) return false; // 私有 / 环回 / 本网
if (b[0] == 169 && b[1] == 254) return false; // 链路本地 / 云元数据
if (b[0] == 172 && b[1] >= 16 && b[1] <= 31) return false; // 私有
if (b[0] == 192 && b[1] == 168) return false; // 私有
if (b[0] == 100 && b[1] >= 64 && b[1] <= 127) return false; // CGNAT (IPv4 共享地址)
if (b[0] == 192 && b[1] == 0) return false; // IETF 协议分配
if (b[0] == 198 && (b[1] == 18 || b[1] == 19)) return false; // 基准测试
if (b[0] >= 224) return false; // 组播 / 保留
}
else if (ip.AddressFamily == AddressFamily.InterNetworkV6)
{
if (ip.IsIPv6LinkLocal || ip.IsIPv6SiteLocal || ip.IsIPv6Multicast) return false;
var b = ip.GetAddressBytes();
if (b[0] == 0xfd || b[0] == 0xfc) return false; // 唯一本地地址
if (ip.IsIPv4MappedToIPv6) return IsPublicAddress(ip.MapToIPv4().ToString());
}
return true;
}
/// <summary>在 dist/&lt;系统&gt;-&lt;架构&gt;/ 里找这个平台的启动器包;找不到返回 null。</summary>
private string? FindInDist(RepoPackage package)
{
foreach (var dir in LauncherArtifacts.CandidateDirs(package.Rid, package.Dir))
{
string full;
try { full = SafePath(dir); }
catch (InvalidOperationException) { continue; }
if (!Directory.Exists(full)) continue;
var zips = Directory.GetFiles(full, "*.zip");
if (zips.Length == 0) continue;
foreach (var zip in zips)
if (LauncherArtifacts.LooksLikePackage(Path.GetFileName(zip), _launcherVersion, package.Rid))
return zip;
if (zips.Length == 1) return zips[0];
}
return null;
}
/// <summary>把相对路径解析成 _root 内的真实路径:拒绝越界,且逐级拒绝符号链接。</summary>
private string SafePath(string relative)
{
var full = Path.GetFullPath(Path.Combine(_root, relative));
var prefix = _root.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
if (!full.Equals(_root, StringComparison.OrdinalIgnoreCase) &&
!full.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException($"路径越界: {relative}");
// 词法校验之后还要解析符号链接:root 内的链接可能指向根目录之外。
// 逐级检查 _root 到 full 的每一段,任何重解析点都直接拒绝。
var rel = Path.GetRelativePath(_root, full);
if (rel != "." && rel != "")
{
var cursor = _root;
foreach (var segment in rel.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries))
{
if (segment == "..") throw new InvalidOperationException($"路径越界: {relative}");
cursor = Path.Combine(cursor, segment);
if (IsReparsePoint(cursor))
throw new InvalidOperationException($"路径含符号链接,已拒绝: {relative}");
}
}
return full;
}
private static bool IsReparsePoint(string path)
{
try
{
if (!File.Exists(path) && !Directory.Exists(path)) return false;
return (File.GetAttributes(path) & FileAttributes.ReparsePoint) != 0;
}
catch
{
// 取不到属性时按不可信处理,避免绕过符号链接检查。
return true;
}
}
private static string Relative(string baseDir, string file) =>
Path.GetRelativePath(baseDir, file).Replace('\\', '/');
}
-142
View File
@@ -1,142 +0,0 @@
using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using GC.Models;
namespace GC.Services;
public static class ModelInstaller
{
// 与后端 /api/models/{id} 的白名单保持一致:单段名称,首字符必须字母或数字。
// 拒绝 . / .. / 路径分隔符 / 盘符 / 绝对路径,杜绝把 model.Id 当成路径来用。
private static readonly Regex SafeId = new(
"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$", RegexOptions.Compiled);
/// <summary>把源里的模型目录复制进本地模型库(先写临时目录再原子替换)。</summary>
public static async Task<string> InstallAsync(RemoteModel model, string modelRoot,
IProgress<(long Done, long Total)>? progress, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(model);
if (string.IsNullOrWhiteSpace(modelRoot))
throw new InvalidOperationException("模型根目录未配置");
// ---- 1. 模型标识必须是单段安全名称,且解析后仍在模型根目录内 ----
var target = SafeChildPath(modelRoot, model.Id);
var rootFull = Path.GetFullPath(modelRoot);
var staging = VerifyUnderRoot(target + ".installing", rootFull);
var backup = VerifyUnderRoot(target + ".old", rootFull);
// ---- 2. 源目录与三个目标路径都不能是符号链接/重解析点 ----
EnsureNoLink(model.Directory);
foreach (var p in new[] { target, staging, backup }) EnsureNoLink(p);
if (Directory.Exists(staging)) Directory.Delete(staging, true);
Directory.CreateDirectory(staging);
// 枚举时跳过符号链接/重解析点:源目录里若有人放了指向外部的链接,
// 绝不能顺着它把模型库外的文件读进来。
var enumeration = new EnumerationOptions
{
RecurseSubdirectories = true,
AttributesToSkip = FileAttributes.ReparsePoint,
IgnoreInaccessible = false
};
var files = Directory.GetFiles(model.Directory, "*", enumeration);
long total = 0;
foreach (var file in files)
{
try { total += new FileInfo(file).Length; } catch { }
}
long done = 0;
try
{
foreach (var file in files)
{
ct.ThrowIfCancellationRequested();
var relative = Path.GetRelativePath(model.Directory, file);
// 路径穿越防护:相对路径必须完整落在 staging 目录内
var dest = VerifyUnderRoot(Path.Combine(staging, relative), Path.GetFullPath(staging));
var destDir = Path.GetDirectoryName(dest);
if (!string.IsNullOrEmpty(destDir)) Directory.CreateDirectory(destDir);
await using (var src = File.OpenRead(file))
await using (var dst = File.Create(dest))
{
await src.CopyToAsync(dst, 81920, ct);
}
long length = 0;
try { length = new FileInfo(dest).Length; } catch { }
done += length;
progress?.Report((done, total <= 0 ? done : total));
}
// 原子替换:先备份旧目录,第二次 Move 失败时完整回滚,绝不把模型库清空
if (Directory.Exists(backup)) Directory.Delete(backup, true);
var hasBackup = false;
try
{
if (Directory.Exists(target))
{
Directory.Move(target, backup);
hasBackup = true;
}
Directory.Move(staging, target);
}
catch
{
// 新目录尚未就位时把旧目录还原;staging 由外层 catch 清理
if (hasBackup && !Directory.Exists(target) && Directory.Exists(backup))
Directory.Move(backup, target);
throw;
}
if (hasBackup)
{
try { Directory.Delete(backup, true); } catch { /* 占用时留到下次 */ }
}
progress?.Report((total, total));
return target;
}
catch
{
try { if (Directory.Exists(staging)) Directory.Delete(staging, true); } catch { }
throw;
}
}
/// <summary>把 id 限定为单段安全名称,并确认拼出来的路径仍在 root 内。</summary>
private static string SafeChildPath(string root, string? id)
{
if (string.IsNullOrWhiteSpace(id) ||
id == "." || id == ".." ||
id.IndexOfAny(new[] { '/', '\\', ':' }) >= 0 ||
Path.IsPathRooted(id) ||
!SafeId.IsMatch(id))
throw new InvalidOperationException($"非法的模型标识: {id}");
var rootFull = Path.GetFullPath(root);
return VerifyUnderRoot(Path.Combine(rootFull, id), rootFull);
}
/// <summary>解析绝对路径并确认 candidate 位于 root 之内。</summary>
private static string VerifyUnderRoot(string candidate, string rootFull)
{
var full = Path.GetFullPath(candidate);
var prefix = rootFull.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
if (!full.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException($"路径越界: {candidate}");
return full;
}
/// <summary>拒绝符号链接 / junction / 重解析点,避免顺着链接写到模型库外。</summary>
private static void EnsureNoLink(string path)
{
if (!File.Exists(path) && !Directory.Exists(path)) return;
if ((File.GetAttributes(path) & FileAttributes.ReparsePoint) != 0)
throw new InvalidOperationException($"拒绝符号链接路径: {path}");
}
}
-100
View File
@@ -1,100 +0,0 @@
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
namespace GC.Services;
/// <summary>
/// 带断点续传的流式下载器。已下载的部分写在 <c>*.part</c> 文件里,
/// 完整下载后由调用方把 .part 改成正式文件名。
///
/// 为什么需要它:模型源码 zip 可能有上百 MB,弱网中断后如果每次都从头下,
/// 用户会反复卡在同一个地方。这里用 HTTP Range 从已下载的字节接着下。
///
/// 兼容性:服务器不支持 Range(忽略请求、返回 200)时自动退化为整段下载,
/// 不会卡死或拿到半截文件。<see cref="Content-Range"/> 起始位置不符时也从头下。
///
/// .part 文件只有在"续传"场景才复用;一旦下载完整、调用方改名为正式文件,
/// 下次就是全新下载,不会把旧内容接在新内容后面。
/// </summary>
public static class ResumableDownloader
{
/// <summary>
/// 下载 <paramref name="url"/>,数据写入 <paramref name="partPath"/>。
/// 返回最终 .part 文件的字节数。下载完整后由调用方负责改名 / 校验。
/// </summary>
public static async Task<long> DownloadAsync(
HttpClient http,
string url,
string partPath,
IProgress<(long Done, long Total)>? progress,
CancellationToken ct)
{
// 已有 .part 就尝试从断点续传;没有则从头下
long resumeFrom = 0;
if (File.Exists(partPath))
{
try { resumeFrom = new FileInfo(partPath).Length; }
catch { resumeFrom = 0; }
}
using var req = new HttpRequestMessage(HttpMethod.Get, url);
if (resumeFrom > 0)
req.Headers.Range = new RangeHeaderValue(resumeFrom, null);
using var response = await http.SendAsync(req, HttpCompletionOption.ResponseHeadersRead, ct)
.ConfigureAwait(false);
response.EnsureSuccessStatusCode();
var canResume = response.StatusCode == HttpStatusCode.PartialContent && resumeFrom > 0;
long? total = response.Content.Headers.ContentLength;
if (canResume)
{
// 校验服务器确实从我们要的位置开始返回:Content-Range: bytes START-END/TOTAL
var range = response.Content.Headers.ContentRange;
if (range?.HasRange == true && range.From == resumeFrom && range.Length.HasValue)
{
total = range.Length.Value;
}
else
{
// 服务器忽略了 Range 或给出的范围对不上:从头覆盖,避免拼接出损坏的文件
canResume = false;
resumeFrom = 0;
}
}
var mode = canResume ? FileMode.Append : FileMode.Create;
var dir = Path.GetDirectoryName(partPath);
if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
await using (var input = await response.Content.ReadAsStreamAsync(ct).ConfigureAwait(false))
await using (var output = new FileStream(partPath, mode, FileAccess.Write, FileShare.Read,
81920, useAsync: true))
{
var buffer = new byte[81920];
long done = resumeFrom;
int read;
while ((read = await input.ReadAsync(buffer.AsMemory(), ct).ConfigureAwait(false)) > 0)
{
await output.WriteAsync(buffer.AsMemory(0, read), ct).ConfigureAwait(false);
done += read;
// Total 未知时用已下载量当分母,进度条会停在 100% 之前但不报错
progress?.Report((done, total ?? done));
}
}
return SafeLength(partPath);
}
private static long SafeLength(string path)
{
try { return new FileInfo(path).Length; }
catch { return 0; }
}
}
-200
View File
@@ -1,200 +0,0 @@
# 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,无异常输出即通过
@@ -1,947 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using GC.Download;
using GC.Models;
using GC.Services;
using GC.UI.Server;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace GC.UI.Server;
/// <summary>
/// GC-UI 后端(本地 HTTP 服务:模型扫描 / 下载 / 更新 / 设置 / 模型窗口宿主)。
///
/// 两种跑法共用同一份代码:
/// · 独立进程:<c>GC.UI.Server</c> 可执行文件(开发调试 / 旧包兼容);
/// · 进程内:启动器直接调用 <see cref="Start"/>,把后端跑在自己的进程里 ——
/// 发布包因此只需要一个 exe,不必再复制一份完整的 .NET 运行时。
/// </summary>
public static class BackendServer
{
/// <summary>按命令行 / GC_UI_PORT 解析端口并构建(未启动)的后端。</summary>
public static WebApplication StartFromCommandLine(string[] args)
=> Start(args, ResolvePort(args));
/// <summary>
/// 构建后端。返回的 <see cref="WebApplication"/> 尚未启动:
/// 独立进程直接 <c>Run()</c>,启动器用 <c>StartAsync()</c> 之后继续拉起界面。
///
/// 主界面已是 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();
builder.WebHost.UseUrls($"http://127.0.0.1:{port}");
// 本地伴随进程:限制请求体大小、关闭 Server 头、收紧超时,减少被本地恶意页面
// 或异常客户端拖垮的攻击面。
builder.WebHost.ConfigureKestrel(options =>
{
options.AddServerHeader = false;
options.Limits.MaxRequestBodySize = 2 * 1024 * 1024;
options.Limits.RequestHeadersTimeout = TimeSpan.FromSeconds(15);
options.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(2);
options.Limits.MaxConcurrentConnections = 64;
});
// 桌面端(Windows/macOS)走原生 HTTP,不需要 CORS;
// 这里放开本机回环来源,方便本地调试客户端。
builder.Services.AddCors(options => options.AddDefaultPolicy(policy => policy
.SetIsOriginAllowed(origin =>
Uri.TryCreate(origin, UriKind.Absolute, out var uri) &&
(uri.Host == "127.0.0.1" || uri.Host == "localhost" || uri.Host == "::1"))
.AllowAnyHeader()
.AllowAnyMethod()));
var app = builder.Build();
app.UseCors();
// 日志与启动器共用 .GC/logs,整条启动链路(启动器 → 后端 → 守护进程)都在同一组文件里。
var logPaths = AppPaths.Discover();
GcLog.Init(logPaths.LogsRoot);
GcLog.Info($"GC-UI 后端启动,监听 127.0.0.1:{port}",
$"GC-UI backend started on 127.0.0.1:{port}");
// 设置白名单 / 标识校验用到的规则(只在本进程内使用)。
var allowedLanguages = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{ "auto", "zh-CN", "en" };
var allowedThemes = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{ "light", "dark", "system" };
var accentHexRegex = new System.Text.RegularExpressions.Regex(
"^#(?:[0-9A-Fa-f]{6})$", System.Text.RegularExpressions.RegexOptions.Compiled);
var safeIdRegex = new System.Text.RegularExpressions.Regex(
"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$", System.Text.RegularExpressions.RegexOptions.Compiled);
// 安全响应头 + Host/Origin 校验(抵御 DNS rebinding 与跨站调用)。
app.Use(async (context, next) =>
{
var headers = context.Response.Headers;
headers["X-Content-Type-Options"] = "nosniff";
headers["X-Frame-Options"] = "DENY";
headers["Referrer-Policy"] = "no-referrer";
headers["Content-Security-Policy"] = "default-src 'none'; frame-ancestors 'none'";
headers["Cache-Control"] = "no-store";
var host = context.Request.Host.Host;
if (!string.Equals(host, "127.0.0.1", StringComparison.OrdinalIgnoreCase) &&
!string.Equals(host, "localhost", StringComparison.OrdinalIgnoreCase) &&
!string.Equals(host, "::1", StringComparison.OrdinalIgnoreCase))
{
context.Response.StatusCode = StatusCodes.Status403Forbidden;
return;
}
var origin = context.Request.Headers.Origin.ToString();
if (!string.IsNullOrEmpty(origin) &&
!(Uri.TryCreate(origin, UriKind.Absolute, out var parsed) &&
(parsed.Host == "127.0.0.1" || parsed.Host == "localhost" || parsed.Host == "::1")))
{
context.Response.StatusCode = StatusCodes.Status403Forbidden;
return;
}
await next();
});
// 写入类接口做简单限流:单 IP 每秒最多 40 次,防止本地脚本刷爆下载/更新。
var writeBuckets =
new System.Collections.Concurrent.ConcurrentDictionary<string, (long Window, int Count)>();
app.Use(async (context, next) =>
{
if (HttpMethods.IsPost(context.Request.Method) ||
HttpMethods.IsDelete(context.Request.Method))
{
var key = context.Connection.RemoteIpAddress?.ToString() ?? "local";
var now = Environment.TickCount64;
// 定期丢弃过期窗口:本机连接数不多,但长时间运行后桶只增不减会缓慢泄漏。
if (writeBuckets.Count > 256)
{
foreach (var entry in writeBuckets)
{
if (now - entry.Value.Window > 60_000)
writeBuckets.TryRemove(entry.Key, out _);
}
}
var bucket = writeBuckets.AddOrUpdate(
key,
_ => (now, 1),
(_, old) => now - old.Window > 1000 ? (now, 1) : (old.Window, old.Count + 1));
if (bucket.Count > 40)
{
context.Response.StatusCode = StatusCodes.Status429TooManyRequests;
await context.Response.WriteAsJsonAsync(ErrorDto.Of("请求过于频繁,请稍后再试"));
return;
}
}
await next();
});
// 会话令牌校验:启动器拉起时经 GC_UI_TOKEN 注入一次性令牌,前端每个 /api 请求
// 都必须带回。这样同机其他进程即使占了端口、伪造 /api/health 返回 200,也过不了
// 这一关——它拿不到令牌。独立进程 / 调试模式未设置令牌时放行,保持兼容。
var sessionToken = Environment.GetEnvironmentVariable(GcUiContract.TokenEnvVar);
if (!string.IsNullOrEmpty(sessionToken))
{
var expected = System.Text.Encoding.UTF8.GetBytes(sessionToken);
app.Use(async (context, next) =>
{
if (context.Request.Path.StartsWithSegments("/api"))
{
// 正常请求从请求头取;封面图由 Image.network 发起、无法加自定义头,
// 用同名 query 参数携带(GET 只读资源,参数不会落到日志正文)。
var supplied = context.Request.Headers[GcUiContract.TokenHeader].ToString();
if (string.IsNullOrEmpty(supplied))
supplied = context.Request.Query[GcUiContract.TokenHeader].ToString();
var actual = System.Text.Encoding.UTF8.GetBytes(supplied);
// 长度不等时 CryptographicOperations 仍安全比较,但先比对长度省一次分支泄漏。
if (actual.Length != expected.Length ||
!System.Security.Cryptography.CryptographicOperations.FixedTimeEquals(actual, expected))
{
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
return;
}
}
await next();
});
}
// ---- 健康检查 -------------------------------------------------------------
// ---- 用户系统 -----------------------------------------------------------------
// 简单 session 存储:key = username(lower), value = session token
var userSessions = new System.Collections.Concurrent.ConcurrentDictionary<string, string>();
// 中间件:从 header 提取当前用户;没有 token 时回退到 user.yaml 记住的用户(自动登录)
app.Use(async (context, next) =>
{
context.Items["user"] = null as string;
if (context.Request.Headers.TryGetValue("X-User-Token", out var tokens) && tokens.Count > 0)
{
var token = tokens[0];
foreach (var kv in userSessions)
{
if (kv.Value == token)
{
context.Items["user"] = kv.Key;
break;
}
}
}
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, req.CaptchaId, req.Captcha, out var err);
return ok ? Results.Ok(new { message = "注册成功" }) : Results.BadRequest(new { error = err });
});
app.MapPost("/api/user/login", (LoginRequest? req) => {
if (req == null) return Results.BadRequest(new { error = "请求体为空" });
var ok = userService.Login(req.Username, req.Password, out var err, out var rec);
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.ToLowerInvariant()] = sessionToken;
// 记住登录:写 .GC/user/user.yaml,下次启动自动登录
userService.SaveSession(rec.Username, sessionToken);
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 ?? "",
session_token = sessionToken
});
});
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(UserPayload(rec));
});
app.MapPost("/api/user/signin", (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);
var ok = userService.UpdateSignIn(username, out var err, out var reward);
if (!ok)
{
if (err == "今日已签到")
return Results.Ok(new { message = err, user = UserPayload(rec) });
return Results.BadRequest(new { error = err });
}
return Results.Ok(new {
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!)
});
});
app.MapPost("/api/user/theme", (HttpContext ctx, ThemeRequest? req) =>
{
var username = ctx.Items["user"] as string;
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, 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(
true,
LauncherRuntimeInfo.CurrentLauncherVersion,
LauncherRuntimeInfo.CurrentRid,
// 界面在客户端内渲染,后端不存在「窗口宿主不可用」的状态
true,
(string?)null,
GcUiContract.DeriveSessionProof(sessionToken))));
// ---- 已安装模型 -----------------------------------------------------------
app.MapGet("/api/models", () =>
Results.Ok(services.Models.Scan().Select(ToModelDto).ToList()));
app.MapGet("/api/models/{id}/preview", (string id, HttpResponse response) =>
{
if (!IsSafeId(id)) return Results.BadRequest(ErrorDto.Of("模型标识无效"));
var package = services.Models.Find(id);
if (package == null || !File.Exists(package.PreviewPath)) return Results.NotFound();
// 封面是静态图,允许前端缓存:默认全局中间件写的 no-store 会让每次滚动都重新请求。
// 按扩展名给准确的 MIME —— 统一写 image/png 时,WebP / JPEG 封面在部分平台显示不出来。
response.Headers.CacheControl = "private, max-age=300";
return Results.File(package.PreviewPath, GuessImageContentType(package.PreviewPath));
});
// 模型由客户端渲染:这里只确认模型存在并把 id 交回去,
// 不再拉起 Avalonia 窗口。保留接口是为了老客户端不至于 404。
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}"));
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) =>
{
if (!IsSafeId(id)) return Results.BadRequest(ErrorDto.Of("模型标识无效"));
var ok = services.Models.Delete(id);
if (ok) services.Models.NotifyChanged();
return ok
? Results.Ok(new LaunchResultDto(true, $"已删除模型 {id}"))
: Results.NotFound(ErrorDto.Of($"没有找到模型 {id}"));
});
// ---- 设置 -----------------------------------------------------------------
app.MapGet("/api/settings", () => Results.Ok(ToSettingsDto()));
app.MapPost("/api/settings", (SettingsPatch? patch) =>
{
if (patch == null) return Results.BadRequest(ErrorDto.Of("缺少设置内容"));
// 白名单校验:设置项会写进磁盘并被前端直接使用,不接受任意字符串。
if (patch.Language != null && !allowedLanguages.Contains(patch.Language))
return Results.BadRequest(ErrorDto.Of("不支持的界面语言"));
if (patch.Theme != null && !allowedThemes.Contains(patch.Theme))
return Results.BadRequest(ErrorDto.Of("不支持的主题"));
if (patch.AccentColor != null && !accentHexRegex.IsMatch(patch.AccentColor))
return Results.BadRequest(ErrorDto.Of("主题色需为 #RRGGBB"));
if (patch.UpdateRepository != null && !IsAllowedRepository(patch.UpdateRepository))
return Results.BadRequest(ErrorDto.Of("更新仓库地址不受信任"));
services.Settings.Apply(s =>
{
if (patch.Language != null) s.Language = patch.Language;
if (patch.Theme != null) s.Theme = patch.Theme;
if (patch.AccentColor != null) s.AccentColor = patch.AccentColor.ToUpperInvariant();
if (patch.RenderFps.HasValue) s.RenderFps = Math.Clamp(patch.RenderFps.Value, 12, 120);
if (patch.MemoryMb.HasValue) s.MemoryMb = Math.Clamp(patch.MemoryMb.Value, 256, 16384);
if (patch.MemoryAuto.HasValue) s.MemoryAuto = patch.MemoryAuto.Value;
if (patch.AutoUpdateOnStartup.HasValue) s.AutoUpdateOnStartup = patch.AutoUpdateOnStartup.Value;
if (patch.RequireSignedManifest.HasValue) s.RequireSignedManifest = patch.RequireSignedManifest.Value;
if (patch.UpdateRepository != null) s.UpdateRepository = patch.UpdateRepository;
if (patch.UpdateLocalRoot != null) s.UpdateLocalRoot = patch.UpdateLocalRoot;
if (patch.ModelRootOverride != null) s.ModelRootOverride = patch.ModelRootOverride;
});
if (patch.Language != null) L.I.SetLanguage(patch.Language);
if (patch.MemoryMb.HasValue || patch.MemoryAuto.HasValue)
services.Memory.ApplyAuto(services.Settings.Current.MemoryAuto, services.Settings.Current.MemoryMb);
return Results.Ok(ToSettingsDto());
});
// ---- 模型源 ---------------------------------------------------------------
app.MapGet("/api/sources", () =>
Results.Ok(services.Settings.Current.Sources.Select(ToSourceDto).ToList()));
app.MapPost("/api/sources/select", async (ForceRequest? request) =>
{
var force = request?.Force ?? false;
try
{
var fastest = await services.Selector.PickFastestAsync(force, CancellationToken.None);
services.Updates.UseRemote(services.DownloadModule.CreateRemote(fastest));
return Results.Ok(new LatencyDto(
fastest.Id, fastest.Name,
services.Selector.LastLatency.TryGetValue(fastest.Id, out var ms) ? ms : 0));
}
catch (Exception ex)
{
Console.Error.WriteLine($"[sources] 切换模型源失败: {ex}");
return Results.Json(ErrorDto.Of("模型源切换失败"), statusCode: 503);
}
});
app.MapGet("/api/remote/models", async (string? sourceId, bool force) =>
{
var source = ResolveSource(sourceId);
if (source == null) return Results.NotFound(ErrorDto.Of("没有可用的模型源"));
var index = await services.Sources.FetchAsync(source, force, null, CancellationToken.None);
var installed = services.Models.Scan()
.ToDictionary(p => p.Id, p => p.Manifest.Version, StringComparer.OrdinalIgnoreCase);
return Results.Ok(new SourceIndexDto(
index.SourceId,
index.Root,
index.FromCache,
index.Error,
index.ResolvedFrom,
index.Models.Select(m => new RemoteModelDto(
m.Id,
m.LocalizedName,
m.LocalizedDescription,
m.Manifest.Version,
m.SizeBytes,
ModelScanner.HumanSize(m.SizeBytes),
m.SourceId,
installed.ContainsKey(m.Id),
installed.TryGetValue(m.Id, out var v) ? v : null)).ToList()));
});
// ---- 下载 -----------------------------------------------------------------
app.MapPost("/api/download", async (DownloadRequest? request) =>
{
if (request == null || string.IsNullOrWhiteSpace(request.ModelId))
return Results.BadRequest(ErrorDto.Of("缺少 modelId"));
var source = ResolveSource(request.SourceId);
if (source == null) return Results.NotFound(ErrorDto.Of("没有可用的模型源"));
var index = await services.Sources.FetchAsync(source, false, null, CancellationToken.None);
var model = index.Models.FirstOrDefault(m =>
m.Id.Equals(request.ModelId, StringComparison.OrdinalIgnoreCase));
if (model == null)
return Results.NotFound(ErrorDto.Of($"源里没有模型 {request.ModelId}"));
var job = services.Downloads.Enqueue(model);
return Results.Ok(ToJobDto(job));
});
app.MapGet("/api/download/jobs", () =>
Results.Ok(services.Downloads.Jobs.Select(ToJobDto).ToList()));
app.MapPost("/api/download/{id}/cancel", (string id) =>
ActOnJob(id, job => services.Downloads.Cancel(job)));
app.MapPost("/api/download/{id}/retry", (string id) =>
ActOnJob(id, job => services.Downloads.Retry(job)));
app.MapPost("/api/download/{id}/remove", (string id) =>
ActOnJob(id, job => services.Downloads.Remove(job)));
app.MapPost("/api/download/clear-finished", () =>
{
services.Downloads.ClearFinished();
return Results.Ok(new LaunchResultDto(true, "已清除完成的任务"));
});
// ---- 更新 -----------------------------------------------------------------
app.MapPost("/api/update/check", async (ForceRequest? request) =>
{
var force = request?.Force ?? true;
var messages = new List<string>();
try
{
var fastest = await services.Selector.PickFastestAsync(force, CancellationToken.None);
services.Updates.UseRemote(services.DownloadModule.CreateRemote(fastest));
}
catch (Exception ex)
{
Console.Error.WriteLine($"[update] 测速失败,沿用当前源: {ex.Message}");
}
string? launcherLatest = null;
try
{
launcherLatest = await services.LauncherUpdates.CheckAsync(
services.Updates.Remote, CancellationToken.None);
}
catch (Exception ex)
{
Console.Error.WriteLine($"[update] 启动器版本检查失败: {ex.Message}");
}
var progress = new Progress<UpdateProgress>(p =>
{
if (!string.IsNullOrWhiteSpace(p.Message)) messages.Add(p.Message);
});
var result = await services.Updates.RunAsync(force, progress, CancellationToken.None);
return Results.Ok(new UpdateCheckDto(
result.Outcome.ToString(),
result.Message,
result.UpdatedModels,
result.ModelNames,
result.LauncherMessage,
result.Error,
launcherLatest,
services.Updates.Remote.DisplayName,
services.Selector.LastLatency
.Select(kv => new LatencyDto(
kv.Key,
SourcePreset.Find(kv.Key)?.Name ?? kv.Key,
kv.Value))
.ToList()));
});
// ---- 重新下载启动器 -------------------------------------------------------
// 「关于」页的按钮:本地程序文件被误删 / 损坏后,重新拉一份发布包。
// DownloadAsync 内部会按清单里的 sha256 逐块校验,清单缺 sha256 直接拒绝下载,
// 所以「下载完确认完整性」是这条链路的固有动作,不是这里另加的一次比对。
app.MapPost("/api/launcher/redownload", async () =>
{
try
{
var fastest = await services.Selector.PickFastestAsync(false, CancellationToken.None);
services.Updates.UseRemote(services.DownloadModule.CreateRemote(fastest));
var steps = new List<string>();
var progress = new Progress<UpdateProgressInfo>(p =>
{
if (string.IsNullOrWhiteSpace(p.Stage)) return;
lock (steps) steps.Add(p.Stage);
});
var result = await services.LauncherUpdates.DownloadAsync(
services.Paths, services.Updates.Remote, progress, CancellationToken.None);
lock (steps)
{
return Results.Ok(new LauncherRedownloadDto(
result.State.ToString(),
result.Version,
result.Message,
steps.ToList()));
}
}
catch (Exception ex)
{
Console.Error.WriteLine($"[launcher] 重新下载失败: {ex}");
return Results.Json(
ErrorDto.Of($"重新下载启动器失败:{ex.Message}"),
statusCode: 503);
}
});
// ---- 关于 -----------------------------------------------------------------
app.MapGet("/api/about", async () =>
{
var repository = services.Settings.Current.UpdateRepository;
var contributors = new List<ContributorDto>();
try
{
foreach (var c in await ContributorsService.FetchAsync(repository, CancellationToken.None))
contributors.Add(new ContributorDto(c.DisplayName, c.Contributions, c.AvatarUrl));
}
catch (Exception ex)
{
Console.Error.WriteLine($"[about] 读取贡献者失败: {ex.Message}");
}
return Results.Ok(new AboutDto(
"Morris GC",
LauncherRuntimeInfo.CurrentLauncherVersion,
LauncherRuntimeInfo.CurrentRid,
repository,
contributors,
// 「关于」页展示的技术栈信息:源码语言与前端框架。
SourceLanguage: "C#",
Frontend: "Avalonia"));
});
// ---- 系统集成 -------------------------------------------------------------
app.MapPost("/api/shell/open-folder", (PathRequest? request) =>
{
var path = request?.Path;
if (string.IsNullOrWhiteSpace(path))
return Results.BadRequest(ErrorDto.Of("缺少 path"));
// 只允许打开启动器自己的目录,避免前端被当成任意路径执行器
if (!IsInsideKnownRoot(path!))
return Results.BadRequest(ErrorDto.Of("只允许打开启动器自己的目录"));
Shell.OpenFolder(path!);
return Results.Ok(new LaunchResultDto(true, "已打开目录"));
});
app.MapPost("/api/shell/open-url", (UrlRequest? request) =>
{
var url = request?.Url;
if (string.IsNullOrWhiteSpace(url) || url.Length > 2048 ||
!Uri.TryCreate(url, UriKind.Absolute, out var uri))
return Results.BadRequest(ErrorDto.Of("URL 无效"));
if (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps)
return Results.BadRequest(ErrorDto.Of("只允许 http/https 链接"));
if (!string.IsNullOrEmpty(uri.UserInfo))
return Results.BadRequest(ErrorDto.Of("URL 不允许携带账号密码"));
Shell.OpenUrl(url!);
return Results.Ok(new LaunchResultDto(true, "已打开链接"));
});
// ---- 启动 -----------------------------------------------------------------
WriteEndpointFile(services, port, sessionToken);
Console.WriteLine($"[GC-UI] 后端已启动: http://127.0.0.1:{port}");
Console.WriteLine($"[GC-UI] 模型库: {services.Paths.ModelRoot}");
return app;
// ---------------------------------------------------------------------------
// 局部辅助
// ---------------------------------------------------------------------------
static void WriteEndpointFile(AppServices services, int port, string? token)
{
try
{
var file = Path.Combine(services.Paths.HomeRoot, "ui-backend.json");
var payload = JsonSerializer.Serialize(new
{
port,
pid = Environment.ProcessId,
url = $"http://127.0.0.1:{port}",
version = LauncherRuntimeInfo.CurrentLauncherVersion,
platform = LauncherRuntimeInfo.CurrentRid,
startedAt = DateTimeOffset.UtcNow.ToString("o"),
// 令牌也写进来:前端如果是被 Finder 直接打开(没有继承环境变量),
// 只能从这里拿到会话令牌,否则每个 /api 都会 401 —— 表现为「无法连接后端」。
token
}, new JsonSerializerOptions { WriteIndented = true });
File.WriteAllText(file, payload);
if (!OperatingSystem.IsWindows())
{
// 同机其他用户不该读到会话令牌
try { File.SetUnixFileMode(file, UnixFileMode.UserRead | UnixFileMode.UserWrite); }
catch { /* 文件系统不支持时忽略 */ }
}
}
catch (Exception ex)
{
Console.Error.WriteLine($"[GC-UI] 写入端点文件失败: {ex.Message}");
}
}
/// <summary>按扩展名推断图片 MIME;模型封面允许 png / jpg / webp / gif。</summary>
static string GuessImageContentType(string path) => Path.GetExtension(path).ToLowerInvariant() switch
{
".jpg" or ".jpeg" => "image/jpeg",
".webp" => "image/webp",
".gif" => "image/gif",
".bmp" => "image/bmp",
".svg" => "image/svg+xml",
_ => "image/png"
};
ModelDto ToModelDto(ModelPackage package) => new( package.Id,
package.LocalizedName,
package.LocalizedDescription,
package.Manifest.Version,
package.Manifest.Author,
package.SizeBytes,
ModelScanner.HumanSize(package.SizeBytes),
package.Manifest.Tags ?? new List<string>(),
File.Exists(package.PreviewPath),
$"/api/models/{package.Id}/preview",
package.Directory,
package.DataDirectory);
SourceDto ToSourceDto(ModelSource source) => new(
source.Id,
string.IsNullOrWhiteSpace(source.Name) ? source.Id : source.Name,
source.Url,
source.Enabled,
source.BuiltIn,
source.DisplayHost);
SettingsDto ToSettingsDto() => new(
services.Settings.Current.Language,
services.Settings.Current.Theme,
services.Settings.Current.AccentColor,
services.Settings.Current.RenderFps,
services.Settings.Current.MemoryMb,
services.Settings.Current.MemoryAuto,
services.Settings.Current.AutoUpdateOnStartup,
services.Settings.Current.RequireSignedManifest,
services.Settings.Current.UpdateRepository,
services.Settings.Current.UpdateLocalRoot,
services.Settings.Current.ModelRootOverride,
services.Memory.BudgetMb,
services.Memory.UsageText,
services.Paths.ModelRoot,
services.Paths.DataRoot,
services.Paths.SettingsFile,
LauncherRuntimeInfo.CurrentLauncherVersion,
LauncherRuntimeInfo.CurrentRid,
services.Settings.Current.Sources.Select(ToSourceDto).ToList(),
L.Supported.Select(s => new LanguageDto(s.Code, s.Label)).ToList());
JobDto ToJobDto(IDownloadJob job) => new(
job.Id,
job.Model.Id,
job.Name,
job.Version,
job.State.ToString(),
job.Progress,
job.StatusText,
job.DetailText,
job.Error,
job.IsActive,
job.CanRetry,
job.IsDone);
ModelSource? ResolveSource(string? sourceId)
{
var sources = services.Settings.Current.Sources;
if (!string.IsNullOrWhiteSpace(sourceId))
{
var exact = sources.FirstOrDefault(s =>
s.Id.Equals(sourceId, StringComparison.OrdinalIgnoreCase));
if (exact != null) return exact;
}
return sources.FirstOrDefault(s => s.Enabled && !string.IsNullOrWhiteSpace(s.Url))
?? sources.FirstOrDefault();
}
IResult ActOnJob(string id, Action<IDownloadJob> action)
{
if (!IsSafeId(id)) return Results.BadRequest(ErrorDto.Of("任务标识无效"));
var job = services.Downloads.Jobs.FirstOrDefault(j =>
j.Id.Equals(id, StringComparison.OrdinalIgnoreCase));
if (job == null) return Results.NotFound(ErrorDto.Of($"没有找到任务 {id}"));
action(job);
return Results.Ok(ToJobDto(job));
}
bool IsInsideKnownRoot(string path)
{
try
{
var full = Path.GetFullPath(path);
var roots = new[]
{
services.Paths.ModelRoot,
services.Paths.DataRoot,
services.Paths.HomeRoot,
services.Paths.AppRoot
};
foreach (var root in roots)
{
if (string.IsNullOrWhiteSpace(root)) continue;
var rootFull = Path.GetFullPath(root);
if (full.Equals(rootFull, StringComparison.OrdinalIgnoreCase)) return true;
if (full.StartsWith(rootFull + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
return true;
}
}
catch
{
return false;
}
return false;
}
// 路由标识:只允许字母数字开头,后接字母数字/点/下划线/短横线,长度上限 64。
// 用于模型 id、任务 id,杜绝 `../` 之类的路径穿越尝试。
bool IsSafeId(string? id) => !string.IsNullOrEmpty(id) && safeIdRegex.IsMatch(id);
// 更新仓库地址:必须是 https、不带账号密码、不是回环/内网 IP。
// 防止把本地后端当成 SSRF 跳板去访问内网服务。
bool IsAllowedRepository(string value)
{
if (string.IsNullOrWhiteSpace(value)) return false;
if (!Uri.TryCreate(value, UriKind.Absolute, out var uri)) return false;
if (uri.Scheme != Uri.UriSchemeHttps) return false;
if (!string.IsNullOrEmpty(uri.UserInfo)) return false;
if (string.Equals(uri.Host, "localhost", StringComparison.OrdinalIgnoreCase)) return false;
if (System.Net.IPAddress.TryParse(uri.Host, out var ip) &&
(System.Net.IPAddress.IsLoopback(ip) || IsPrivateAddress(ip)))
return false;
return true;
}
static bool IsPrivateAddress(System.Net.IPAddress ip)
{
var bytes = ip.GetAddressBytes();
if (bytes.Length != 4) return false;
return bytes[0] == 10
|| (bytes[0] == 172 && bytes[1] >= 16 && bytes[1] <= 31)
|| (bytes[0] == 192 && bytes[1] == 168)
|| (bytes[0] == 169 && bytes[1] == 254);
}
}
public static int ResolvePort(string[] args)
{
// 优先用启动器传来的端口(GC_UI_PORT),保证前端拼出来的 baseUrl 和这里一致。
var env = Environment.GetEnvironmentVariable(GcUiContract.PortEnvVar);
if (int.TryParse(env, out var fromEnv) && fromEnv > 0 && fromEnv < 65536) return fromEnv;
for (var i = 0; i < args.Length; i++)
{
if (args[i] == "--port" && i + 1 < args.Length &&
int.TryParse(args[i + 1], out var next) && next > 0 && next < 65536)
return next;
const string prefix = "--port=";
if (args[i].StartsWith(prefix, StringComparison.Ordinal) &&
int.TryParse(args[i][prefix.Length..], out var inline) && inline > 0 && inline < 65536)
return inline;
}
return GcUiContract.DefaultPort;
}
}
-8
View File
@@ -1,8 +0,0 @@
using GC.UI.Server;
// 独立进程入口:`GC.UI.Server --port 17890`
// 启动器在进程内直接调用 BackendServer.Start,不会走到这里。
var app = BackendServer.StartFromCommandLine(args);
// 纯 HTTP 后端(供独立部署 / 外部客户端使用),跑起来常驻即可。
app.Run();
@@ -1,696 +0,0 @@
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;
}
}
-158
View File
@@ -1,158 +0,0 @@
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 { /* 已关闭 */ }
}
}
-208
View File
@@ -1,208 +0,0 @@
using System;
using System.Globalization;
using System.IO;
using System.Text;
namespace GC.Services;
/// <summary>
/// 双语文件日志。
///
/// 每条记录同时写两个文件(都在 <c>.GC/logs</c> 下,按天滚动):
/// <code>
/// gc-20261118.log 中文
/// gc-20261118.en.log 英文
/// </code>
/// 中英分开而不是写在一个文件里:用户排查时不用在一行里找自己看得懂的那半句;
/// 也给反馈问题时直接发对应语言的文件即可。
///
/// 写入方式:常驻 <see cref="StreamWriter"/>(<c>AutoFlush</c> 打开,崩溃也不丢最后几行),
/// 不再每行 open/append/close 一遍 —— 那条路径每写一行要开两个文件句柄,
/// 在下载 / 启动高峰期会明显拖慢调用方。
///
/// 保留策略:<see cref="RetentionDays"/> 天之前的日志在初始化与跨天滚动时删除;
/// 总量超过 <see cref="MaxTotalBytes"/> 时从最旧的开始删。日志目录不会无限长。
///
/// 日志失败绝不影响主流程(磁盘满、只读目录都只是少一份日志)。
/// </summary>
public static class GcLog
{
/// <summary>日志保留天数。</summary>
/// <remarks>14 天对日常排障够用,但双语言 + 高活跃度时容易触及总量上限导致批量删除;
/// 7 天更合理:用户反馈问题时最近 3 天就够,7 天能覆盖一周内的连续问题。</remarks>
public const int RetentionDays = 7;
/// <summary>日志目录总量上限(中英两份合计)。</summary>
public const long MaxTotalBytes = 64L * 1024 * 1024;
private static readonly object Gate = new();
private const string FilePrefix = "gc-";
private static string? _dir;
private static string _day = "";
private static StreamWriter? _zh;
private static StreamWriter? _en;
public static bool Enabled
{
get { lock (Gate) return _dir != null; }
}
/// <summary>绑定日志目录(通常是 <c>.GC/logs</c>)。重复调用会切到新目录。</summary>
public static void Init(string dir)
{
try
{
Directory.CreateDirectory(dir);
}
catch
{
// 目录都建不了就退化成只写控制台
return;
}
lock (Gate)
{
CloseWriters();
_dir = dir;
_day = "";
PruneOldFiles(dir);
}
}
public static void Info(string zh, string en) => Write("INFO ", zh, en);
public static void Warn(string zh, string en) => Write("WARN ", zh, en);
public static void Error(string zh, string en) => Write("ERROR", zh, en);
private static void Write(string level, string zh, string en)
{
var now = DateTime.Now;
var prefix = $"{now:yyyy-MM-dd HH:mm:ss} [{level}] ";
try { Console.WriteLine(prefix + zh); } catch { /* 无控制台 */ }
lock (Gate)
{
if (_dir == null) return;
var day = now.ToString("yyyyMMdd");
if (day != _day)
{
// 跨天换文件;顺便清一次旧日志,长时间挂机的进程也不会攒满磁盘
CloseWriters();
_day = day;
PruneOldFiles(_dir);
}
if (_zh == null)
{
_zh = OpenWriter(Path.Combine(_dir, $"{FilePrefix}{day}.log"));
_en = OpenWriter(Path.Combine(_dir, $"{FilePrefix}{day}.en.log"));
}
Append(_zh, prefix + zh);
Append(_en, prefix + en);
}
}
private static StreamWriter? OpenWriter(string path)
{
try
{
var stream = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
return new StreamWriter(stream, new UTF8Encoding(false)) { AutoFlush = true };
}
catch
{
// 写不了就不写;下一次跨天会再试一次
return null;
}
}
private static void Append(StreamWriter? writer, string line)
{
if (writer == null) return;
try
{
writer.WriteLine(line);
}
catch
{
// 磁盘满 / 文件被删:关掉写入器,下次跨天重建
try { writer.Dispose(); } catch { }
if (ReferenceEquals(writer, _zh)) _zh = null; else _en = null;
}
}
private static void CloseWriters()
{
try { _zh?.Dispose(); } catch { }
try { _en?.Dispose(); } catch { }
_zh = null;
_en = null;
}
/// <summary>
/// 清理过期与超量日志。只动本模块自己写的 <c>gc-YYYYMMDD[.en].log</c>,
/// 目录里用户放的其他文件一概不碰。
/// </summary>
private static void PruneOldFiles(string dir)
{
try
{
var files = new DirectoryInfo(dir).GetFiles(FilePrefix + "*.log");
if (files.Length == 0) return;
var cutoff = DateTime.Now.Date.AddDays(-RetentionDays);
var alive = new System.Collections.Generic.List<FileInfo>(files.Length);
foreach (var file in files)
{
if (!TryReadDate(file.Name, out var date))
{
// 名字不是我们的格式,忽略(既不删也不计入配额)
continue;
}
if (date < cutoff)
{
try { file.Delete(); } catch { }
continue;
}
alive.Add(file);
}
long total = 0;
foreach (var file in alive) total += file.Length;
if (total <= MaxTotalBytes) return;
alive.Sort((a, b) => a.LastWriteTimeUtc.CompareTo(b.LastWriteTimeUtc));
foreach (var file in alive)
{
if (total <= MaxTotalBytes) break;
try
{
total -= file.Length;
file.Delete();
}
catch { }
}
}
catch
{
// 清理失败不影响写日志
}
}
private static bool TryReadDate(string name, out DateTime date)
{
date = default;
// gc-20261118.log / gc-20261118.en.log
if (!name.StartsWith(FilePrefix, StringComparison.Ordinal)) return false;
var rest = name.Substring(FilePrefix.Length);
var dot = rest.IndexOf('.');
if (dot != 8) return false;
return DateTime.TryParseExact(rest.Substring(0, 8), "yyyyMMdd",
CultureInfo.InvariantCulture, DateTimeStyles.None, out date);
}
}
@@ -1,47 +0,0 @@
using System;
using System.Net;
using System.Net.Http;
namespace GC.Services;
/// <summary>
/// 共享 HttpClient 工厂:统一管理连接池,避免每个类创建独立的 HttpClient 实例。
///
/// .NET Core 3.1+ 的 HttpClientHandler 内部使用连接池,但每个 HttpClient 实例仍会创建
/// 独立的 Socket 连接池。多个静态 HttpClient 实例(尤其是不同超时配置)会导致端口耗尽
/// 或连接无法及时释放。通过单一实例 + 共享 Handler 解决此问题。
///
/// 注意:不同场景对超时要求差异较大(探测 6s、下载 5min),通过构造参数传递超时,
/// 但底层 Handler 共享,避免重复创建 Socket。
/// </summary>
public static class SharedHttpClientFactory
{
/// <summary>默认 HTTP 客户端(短超时,用于探测和快速请求)。</summary>
private static readonly HttpClient DefaultClient = CreateClient(TimeSpan.FromSeconds(20));
/// <summary>长超时 HTTP 客户端(用于大文件下载)。</summary>
private static readonly HttpClient LongTimeoutClient = CreateClient(TimeSpan.FromMinutes(5));
private static HttpClient CreateClient(TimeSpan timeout)
{
var handler = new HttpClientHandler
{
AutomaticDecompression = DecompressionMethods.GZip |
DecompressionMethods.Deflate,
// 限制最大重定向次数,防止重定向循环
MaxAutomaticRedirections = 5
};
var client = new HttpClient(handler, disposeHandler: false)
{
Timeout = timeout
};
client.DefaultRequestHeaders.UserAgent.ParseAdd("GC/1.0");
return client;
}
/// <summary>获取默认超时(20秒)的 HttpClient,用于常规 API 请求。</summary>
public static HttpClient GetDefault() => DefaultClient;
/// <summary>获取长超时(5分钟)的 HttpClient,用于大文件下载。</summary>
public static HttpClient GetLongTimeout() => LongTimeoutClient;
}
-120
View File
@@ -1,120 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace GC.Services;
/// <summary>
/// 内置下载源。
///
/// 当前启用 Xhmcl(Gitea)与 GitHub 两个镜像,指向同一份仓库内容;
/// 启动 / 下载 / 更新前并发测速(2 秒超时),取最快且可用的那个。
/// GitCode 的 preset 与下载实现仍保留在代码中,但不参与测速 / 下载 / 更新。
/// </summary>
public sealed class SourcePreset
{
public string Id { get; init; } = "";
public string Name { get; init; } = "";
/// <summary>仓库主页(用于展示与打开)。</summary>
public string HomeUrl { get; init; } = "";
/// <summary>API 根地址(Gitea: /api/v1,GitCode: /api/v5)。</summary>
public string ApiBase { get; init; } = "";
/// <summary>原始文件下载前缀(用于拼 raw 地址)。</summary>
public string RawBase { get; init; } = "";
/// <summary>后端类型:gitea / gitcode。</summary>
public string Kind { get; init; } = "";
public string Owner { get; init; } = "";
public string Repo { get; init; } = "";
public string Branch { get; init; } = "main";
/// <summary>raw 地址风格:gitea 用 raw/branch/{b},gitcode 用 raw/{b}。</summary>
public string RawStyle { get; init; } = "branch";
public string Repository => HomeUrl;
/// <summary>拼 raw 文件下载地址(各平台的 URL 结构不同)。</summary>
public string RawUrl(string path) => RawStyle switch
{
// GitHub:raw.githubusercontent.com/{owner}/{repo}/{branch}/{path}
"raw" => $"{RawBase}/{Owner}/{Repo}/{Branch}/{path.TrimStart('/')}",
// GitCode:raw/{branch}/{path}
"plain" => $"{RawBase}/{Owner}/{Repo}/raw/{Branch}/{path.TrimStart('/')}",
// Gitea:raw/branch/{branch}/{path}
_ => $"{RawBase}/{Owner}/{Repo}/raw/branch/{Branch}/{path.TrimStart('/')}"
};
public static readonly SourcePreset Xhmcl = new()
{
Id = "xhmcl",
Name = "Xhmcl",
HomeUrl = "https://git.xhmcl.com/Morris/GC",
ApiBase = "https://git.xhmcl.com/api/v1",
RawBase = "https://git.xhmcl.com",
Kind = "gitea",
RawStyle = "branch",
Owner = "Morris",
Repo = "GC",
Branch = "main"
};
/// <summary>
/// GitHub 镜像:与 Xhmcl 指向同一份仓库内容(模型清单 + Release 附件)。
/// API 与 Gitea 高度兼容(contents / releases 同构),因此复用同一个 remote 实现,
/// 仅在 URL 拼装与分页参数上区分。
/// </summary>
public static readonly SourcePreset GitHub = new()
{
Id = "github",
Name = "GitHub",
HomeUrl = "https://github.com/Morris-morris-cloud/GC",
ApiBase = "https://api.github.com",
RawBase = "https://raw.githubusercontent.com",
Kind = "github",
RawStyle = "raw",
Owner = "Morris-morris-cloud",
Repo = "GC",
Branch = "main"
};
public static readonly SourcePreset GitCode = new()
{
Id = "gitcode",
Name = "GitCode",
HomeUrl = "https://gitcode.com/Morris_1/GC",
ApiBase = "https://api.gitcode.com/api/v5",
RawBase = "https://gitcode.com",
Kind = "gitcode",
RawStyle = "plain",
Owner = "Morris_1",
Repo = "GC",
Branch = "main"
};
/// <summary>
/// 当前启用的源:Xhmcl 与 GitHub 是同一份仓库的两个镜像,启动时并发测速取最快。
/// GitCode 的定义与实现仍保留在代码里,但不参与测速、下载与更新
/// (需要恢复时把 GitCode 加回这个数组即可)。
/// </summary>
public static readonly SourcePreset[] All = { Xhmcl, GitHub };
public static SourcePreset? Find(string? id) =>
All.FirstOrDefault(p => string.Equals(p.Id, id, StringComparison.OrdinalIgnoreCase));
/// <summary>把任意仓库地址 / 源名映射到启用的内置源(用于兼容旧配置与调用方取值)。</summary>
public static SourcePreset Detect(string? url)
{
if (!string.IsNullOrWhiteSpace(url))
{
if (url!.Contains("github.com", StringComparison.OrdinalIgnoreCase) ||
url.Equals("GitHub", StringComparison.OrdinalIgnoreCase) ||
url.Equals("github", StringComparison.OrdinalIgnoreCase))
return GitHub;
if (url.Contains("xhmcl.com", StringComparison.OrdinalIgnoreCase) ||
url.Equals("Xhmcl", StringComparison.OrdinalIgnoreCase) ||
url.Equals("xhmcl", StringComparison.OrdinalIgnoreCase))
return Xhmcl;
}
// 旧配置里的 GitCode 地址不再作为下载源,统一落到 Xhmcl。
return Xhmcl;
}
}
-50
View File
@@ -1,50 +0,0 @@
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);
}
}
@@ -1,293 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using GC.Savedog;
namespace GC.Savedog.Tests;
/// <summary>
/// GC-SAVEDOG 的应用器测试:更新真正落盘的那一段(整目录替换 / .GC/bin 合并 / 失败回滚)。
///
/// 为什么单独一个工程:<c>GC.Tests</c> 引用的是启动器程序集,而 GC-SAVEDOG 为了保持
/// 「安全逻辑只有一份实现」把 <c>GC/src/Security</c> 与 <c>Json.cs</c> 以源码链接的方式
/// 编进了自己 —— 两个程序集里存在同名类型。同一个测试工程里同时引用两者会撞类型,
/// 所以应用器测试单独放这里,只引用守护进程。
///
/// 为什么需要这组用例:<c>--update-test</c> 覆盖的是「怎么判断该不该更新」,
/// <see cref="Applier"/> 才是会动用户安装目录的代码 —— 它出错就是用户目录被删空。
/// 全部在临时目录里跑,不碰真实安装、不联网。
/// </summary>
internal static class ApplierTests
{
private static int _failed;
private static string _root = "";
public static int Main()
{
_root = Path.Combine(Path.GetTempPath(), "gc-applier-" + Guid.NewGuid().ToString("N")[..8]);
Directory.CreateDirectory(_root);
Console.WriteLine("Applier 测试目录: " + _root);
try
{
CaseRefusesTraversalPackageName();
CaseRefusesShaMismatch();
CaseRefusesSourceTree();
CaseDryRunKeepsInstallUntouched();
CaseRollbackRestoresOldFiles();
CaseSuccessMergesGcBinAndKeepsUserData();
}
finally
{
try { Directory.Delete(_root, true); } catch { }
}
Console.WriteLine(_failed == 0
? "Applier 测试全部通过"
: $"Applier 测试失败 {_failed} 项");
return _failed == 0 ? 0 : 1;
}
// ------------------------------------------------------------------ 用例
/// <summary>包名带 ../ 时必须拒绝(路径穿越的第一道闸)。</summary>
private static void CaseRefusesTraversalPackageName()
{
var (install, update) = Sandbox("traversal");
WritePackage(update, new Dictionary<string, string>
{
["GCL-9.9.9-test-amd64.exe"] = "new"
});
WriteRequest(update, "../evil.exe", sha: null);
var code = Apply(update, install, dryRun: true);
Check("路径穿越的包名被拒绝", code == 3, $"exit={code}(期望 3)");
}
/// <summary>zip 内容与清单 sha256 不符时必须丢弃。</summary>
private static void CaseRefusesShaMismatch()
{
var (install, update) = Sandbox("sha");
WritePackage(update, new Dictionary<string, string>
{
["GCL-9.9.9-test-amd64.exe"] = "new"
});
WriteRequest(update, "GCL-9.9.9-test-amd64.exe", sha: new string('a', 64));
var code = Apply(update, install, dryRun: true);
Check("sha256 不符的包被丢弃", code == 5, $"exit={code}(期望 5)");
}
/// <summary>安装目录里有 GC.sln 时拒绝替换 —— 防止误在源码树里跑更新。</summary>
private static void CaseRefusesSourceTree()
{
var (install, update) = Sandbox("srctree");
File.WriteAllText(Path.Combine(install, "GC.sln"), "fake solution");
var zip = WritePackage(update, new Dictionary<string, string>
{
["GCL-9.9.9-test-amd64.exe"] = "new"
});
WriteRequest(update, "GCL-9.9.9-test-amd64.exe", Sha256File(zip));
var code = Apply(update, install, dryRun: false);
Check("源码目录被拒绝替换", code == 4, $"exit={code}(期望 4)");
Check("源码目录里的文件没被动过",
File.ReadAllText(Path.Combine(install, "GC.sln")) == "fake solution",
"GC.sln 内容变了");
}
/// <summary>dry-run 只校验不落盘:安装目录必须一个字节都不变。</summary>
private static void CaseDryRunKeepsInstallUntouched()
{
var (install, update) = Sandbox("dryrun");
File.WriteAllText(Path.Combine(install, "GCL-1.0.0-test-amd64.exe"), "old");
File.WriteAllText(Path.Combine(install, "only-in-old.txt"), "keep me");
var zip = WritePackage(update, new Dictionary<string, string>
{
["GCL-9.9.9-test-amd64.exe"] = "new",
["GC-UI.exe"] = "ui"
});
WriteRequest(update, "GCL-9.9.9-test-amd64.exe", Sha256File(zip));
var code = Apply(update, install, dryRun: true);
var names = Directory.GetFileSystemEntries(install).Select(Path.GetFileName).OrderBy(n => n).ToArray();
Check("dry-run 返回 0", code == 0, $"exit={code}");
Check("dry-run 不改安装目录",
names.SequenceEqual(new[] { "GCL-1.0.0-test-amd64.exe", "only-in-old.txt" }),
"安装目录变成: " + string.Join(", ", names));
}
/// <summary>
/// 新版本启动不健康 → 回滚:旧文件原样回来,新包独有的文件被删掉,zip 与申请被清理。
/// </summary>
private static void CaseRollbackRestoresOldFiles()
{
var (install, update) = Sandbox("rollback");
var oldExe = Path.Combine(install, "GCL-1.0.0-test-amd64.exe");
var oldOnly = Path.Combine(install, "only-in-old.txt");
File.WriteAllText(oldExe, "old-binary");
File.WriteAllText(oldOnly, "old-only");
// 新版什么都不做直接退出:健康标记不会出现,必然回滚
var zip = WritePackage(update, new Dictionary<string, string>
{
["GCL-9.9.9-test-amd64.exe"] = "#!/bin/sh\nexit 1\n",
["only-in-new.txt"] = "new-only"
});
WriteRequest(update, "GCL-9.9.9-test-amd64.exe", Sha256File(zip));
var code = Apply(update, install, dryRun: false, timeoutSeconds: 5);
Check("启动失败后回滚(exit=8)", code == 8, $"exit={code}(期望 8)");
Check("旧启动器被还原",
File.Exists(oldExe) && File.ReadAllText(oldExe) == "old-binary",
"旧启动器没回来");
Check("旧版独有文件被还原",
File.Exists(oldOnly) && File.ReadAllText(oldOnly) == "old-only",
"旧版独有文件没回来");
Check("新包独有文件被删除", !File.Exists(Path.Combine(install, "only-in-new.txt")),
"only-in-new.txt 残留");
Check("更新包与申请已清理",
!File.Exists(Path.Combine(update, "package.zip")) &&
!File.Exists(Path.Combine(update, "apply-request.json")),
"update 目录里还有残留");
}
/// <summary>正常路径:新文件就位、.GC/bin 被合并、.GC 下的用户数据原地不动。</summary>
private static void CaseSuccessMergesGcBinAndKeepsUserData()
{
var (install, update) = Sandbox("success");
var updateDirFull = Path.GetFullPath(update);
// 用户数据:设置、模型、守护进程源文件
Directory.CreateDirectory(Path.Combine(install, ".GC", "config"));
Directory.CreateDirectory(Path.Combine(install, ".GC", "model", "earth-rotation"));
Directory.CreateDirectory(Path.Combine(install, ".GC", "bin"));
File.WriteAllText(Path.Combine(install, ".GC", "config", "settings.json"), "{\"theme\":\"dark\"}");
File.WriteAllText(Path.Combine(install, ".GC", "model", "earth-rotation", "a.bin"), "model");
File.WriteAllText(Path.Combine(install, ".GC", "bin", "GC-SAVEDOG.exe"), "old-savedog");
// 假启动器:写健康标记后退出,模拟「新版本起来了」
var launcher =
"#!/bin/sh\n" +
"cat > '" + Path.Combine(updateDirFull, "health.json") + "' <<'JSON'\n" +
"{\"version\":\"9.9.9\",\"pid\":4242,\"at\":\"2026-01-01T00:00:00Z\",\"ok\":true}\n" +
"JSON\n" +
"exit 0\n";
var zip = WritePackage(update, new Dictionary<string, string>
{
["GCL-9.9.9-test-amd64.exe"] = launcher,
[".GC/bin/GC-SAVEDOG.exe"] = "new-savedog",
["GC-UI.exe"] = "ui"
});
WriteRequest(update, "GCL-9.9.9-test-amd64.exe", Sha256File(zip));
var code = Apply(update, install, dryRun: false, timeoutSeconds: 10);
Check("启动健康后更新成功(exit=0)", code == 0, $"exit={code}");
Check("新启动器就位",
File.Exists(Path.Combine(install, "GCL-9.9.9-test-amd64.exe")), "新启动器缺失");
Check("新前端就位", File.Exists(Path.Combine(install, "GC-UI.exe")), "GC-UI.exe 缺失");
Check(".GC/bin 被合并",
File.ReadAllText(Path.Combine(install, ".GC", "bin", "GC-SAVEDOG.exe")) == "new-savedog",
".GC/bin/GC-SAVEDOG.exe 没被替换");
Check("用户设置原样保留",
File.ReadAllText(Path.Combine(install, ".GC", "config", "settings.json")) == "{\"theme\":\"dark\"}",
"settings.json 被覆盖");
Check("模型目录原样保留",
File.Exists(Path.Combine(install, ".GC", "model", "earth-rotation", "a.bin")),
"模型文件被删除");
}
// ------------------------------------------------------------------ 辅助
private static int Apply(string updateDir, string installDir, bool dryRun, int timeoutSeconds = 10)
{
var log = new Log(Path.Combine(updateDir, "logs"));
var applier = new Applier(new ApplyOptions
{
UpdateDir = updateDir,
InstallDir = installDir,
DryRun = dryRun,
TimeoutSeconds = timeoutSeconds,
RequireSignature = false, // 用例不生成签名清单;验签本身由 --update-test 覆盖
Force = false
}, log);
return applier.Run();
}
private static (string Install, string Update) Sandbox(string name)
{
var baseDir = Path.Combine(_root, name);
var install = Path.Combine(baseDir, "app");
var update = Path.Combine(baseDir, "update");
Directory.CreateDirectory(install);
Directory.CreateDirectory(update);
File.WriteAllText(Path.Combine(update, "version.json"), "{\"launcher\":{\"version\":\"9.9.9\"}}");
return (install, update);
}
private static string WritePackage(string updateDir, IDictionary<string, string> files)
{
var zipPath = Path.Combine(updateDir, "package.zip");
try { File.Delete(zipPath); } catch { }
using (var archive = ZipFile.Open(zipPath, ZipArchiveMode.Create))
{
foreach (var (name, text) in files)
{
var entry = archive.CreateEntry(name.Replace('\\', '/'), CompressionLevel.Fastest);
using var stream = entry.Open();
var bytes = Encoding.UTF8.GetBytes(text);
stream.Write(bytes, 0, bytes.Length);
}
}
return zipPath;
}
/// <summary>手写申请文件:不引用 Json 序列化助手(同名类型在两个程序集里都有)。</summary>
private static void WriteRequest(string updateDir, string packageName, string? sha)
{
var zipPath = Path.Combine(updateDir, "package.zip");
var size = File.Exists(zipPath) ? new FileInfo(zipPath).Length : 0;
var json = new StringBuilder()
.Append("{\n")
.Append(" \"schema\": 1,\n")
.Append(" \"version\": \"9.9.9\",\n")
.Append(" \"rid\": \"test-amd64\",\n")
.Append(" \"platformLabel\": \"test-amd64\",\n")
.Append(" \"packageName\": ").Append(Quote(packageName)).Append(",\n")
.Append(" \"payloadDir\": \"payload\",\n")
.Append(" \"installRelative\": \"../app\",\n")
.Append(" \"manifestPath\": \"version.json\",\n")
.Append(" \"packageZip\": \"package.zip\",\n")
.Append(" \"packageSha256\": ").Append(sha == null ? "null" : Quote(sha)).Append(",\n")
.Append(" \"packageSize\": ").Append(size).Append(",\n")
.Append(" \"requireSignature\": false\n")
.Append("}\n")
.ToString();
File.WriteAllText(Path.Combine(updateDir, "apply-request.json"), json);
}
private static string Quote(string value) => "\"" + value.Replace("\\", "\\\\").Replace("\"", "\\\"") + "\"";
private static string Sha256File(string path)
{
using var stream = File.OpenRead(path);
return Convert.ToHexString(SHA256.HashData(stream)).ToLowerInvariant();
}
private static void Check(string label, bool ok, string detail)
{
if (ok)
{
Console.WriteLine(" ✓ " + label);
return;
}
_failed++;
Console.WriteLine($" ✗ {label} —— {detail}");
}
}
@@ -1,21 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
应用器测试:只引用 GC-SAVEDOG。
不并入 GC.Tests 的原因见 ApplierTests.cs 顶部注释 —— 守护进程把 GC/src/Security
以源码链接编进了自己,与启动器程序集存在同名类型,同一工程内同时引用会撞类型。
-->
<PropertyGroup>
<OutputType>Exe</OutputType>
<Nullable>enable</Nullable>
<RootNamespace>GC.Savedog.Tests</RootNamespace>
<AssemblyName>GC.Savedog.Tests</AssemblyName>
<InvariantGlobalization>true</InvariantGlobalization>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="../../../../../GC-SAVEDOG/GC-SAVEDOG.csproj" />
</ItemGroup>
</Project>
-158
View File
@@ -1,158 +0,0 @@
# GC 1.1.2 更新日志
**版本范围**:1.1.1 → 1.1.2
**发布日期**:2026-11-21
**规模**:18 个功能提交(含合并共 28 个),184 个文件,+15,556 / −15,135
---
## 概览
这一版的核心是**把界面从 Avalonia 整体迁到 Flutter**,同时补上了账号体系与自动化发布链路。
- 全平台界面重写为 Flutter,模型不再另开窗口,直接在应用内渲染
- 新增本地用户系统:注册登录(带人机验证)、每日签到、积分、主题色购买
- 等高线课件以 WebView 形式完整离线内置
- 新增 GitHub 镜像下载源,与 Xhmcl 并发测速自动择优
- 新增 GitHub Actions:夜间构建、评论触发编译、PR 自动审查
---
## 新增功能
### 用户系统
| 能力 | 说明 |
| --- | --- |
| 注册 / 登录 | 用户名唯一(1–20 字符、不含空格);密码只存 `sha512(密码 + 随机盐)`,不存明文 |
| 人机验证 | 注册需回答算术题,5 分钟有效、一次性、答错作废 |
| 每日签到 | 30 天一循环,断签重置连续天数 |
| 积分 | 只能通过签到获得,**不提供任何充值渠道** |
| 主题色 | 默认蓝免费,预置色 50 积分,自定义色 150 积分;购买后 1 小时内换色退 80% |
| 人品值 | 0–100 随机 + 分档评语,每天不限次数,纯娱乐不影响积分 |
| 二选一 | 填两个选项,随机帮你选一个 |
签到积分表:
| 连续天数 | 1–6 | 7 | 8–13 | 14 | 15–20 | 21 | 22–27 | 28 | 29 | 30 |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| 积分 | 10 | 30 | 15 | 40 | 20 | 50 | 25 | 60 | 40 | 100 |
数据落盘在 `.GC/user/`:
```
.GC/user/user.yaml 当前登录(用户名 + 会话令牌),启动自动登录
.GC/user/<用户名>/pw.yaml 用户名、积分、签到、主题色
```
### 等高线课件
- 原课件的 HTML / JS / CSS / 图片 / 视频完整搬入 Flutter assets,**完全离线可用**
- 用本地 HttpServer(支持 Range)承载,绕开 `file://` 与 CSP 限制
- 侧栏新增「等高线课件」入口,后端未就绪也能打开
### 模型全面 Flutter 化
- **等高线地形图**:五大地貌(平原 / 丘陵 / 山地 / 高原 / 盆地),拖动旋转、滚轮缩放、法线光照、四周裙边侧壁
- **四步实验动画**:等高切割 → 形成交线 → 垂直投影 → 疏密判坡,俯视 / 立体一键切换
- **地球地理**:五带划分、七大洲轮廓、图层开关、回归线与极圈标注
- **地球公转 / 自转**、**比例尺计算器**同步重写
- 模型在内容区内嵌渲染,侧栏与标题栏保持可用,不再弹独立窗口
### 下载源
- 新增 GitHub 镜像源(`Morris-morris-cloud/GC`),与 Xhmcl 并发测速
- 单源探测超时 **2 秒**,取最快且可用的源,结果缓存 3 分钟
- 一个源不可用时自动切到另一个
### 自动化
| 工作流 | 触发 | 产出 |
| --- | --- | --- |
| `nightly-prerelease` | 每天 21:00(Asia/Shanghai) | 三平台编译,发布 `nightly` 预发布 |
| `build-bot` | Issue/PR 评论 `@build-bot build <mac\|win-amd\|win-arm\|all>` | 发布 `ip-prerelease` 预发布 |
| `build-release` | Issue/PR 评论 `@build-release-bot build <版本号>` | 发布正式 Release(带 `SHA256SUMS.txt`) |
| `pr-review` | PR 新建 / 推送 | 检查能否编译、静态分析、合并冲突、是否落后 main |
---
## 改进
- **下载页**显示模型下载进度条,下载源读取速度明显提升
- **关于页**新增「重新下载启动器」,下载后做 sha256 完整性校验
- 标题栏支持最小化 / 最大化 / 关闭,颜色跟随主题
- 修复浅色主题下标题栏不跟随主题色的问题
- 主题色统一由账号决定,设置页不再单独设置颜色
- 模型清单加载改为「内置默认 + i18n 文件覆盖」,此前完全忽略语言包
- `GcLog` 日志保留天数 14 → 7 天
- 后端端口扫描范围 10 → 30,端口被占用时更容易找到可用端口
---
## 修复
| 问题 | 原因 |
| --- | --- |
| macOS Release 版启动后「无法连接后端」 | `Release.entitlements` 缺 `network.client / network.server`,App Sandbox 拦掉了发往 127.0.0.1 的请求 |
| macOS 点「启动模型」进程崩溃 | AppKit 要求 `NSApplication` 在主线程运行,此前在后建线程跑事件循环 |
| 等高线渲染三处缺陷 | 等高线被切成虚线(`Chain()` 只向尾部延伸)、判坡整片红(坡度归一化写死)、切割只叠半透明板(山尖仍在) |
| 模型安装可写到模型库外 | 模型 Id 未限制路径分隔符 / 绝对路径 / 符号链接 |
| 本地目录源可被同机伪造后端利用 | 健康检查改为一次性会话令牌双向校验;包 URL 只允许 http(s) 公网地址,拦截 `file:` / 私有 IP / 环回 / 元数据地址 |
| 多个源全部失败时报「已是最新」 | 改为明确输出错误,不再把失败当成功 |
| macOS 部署目标过低 | 10.14 → 12.0,兼容新版 Xcode |
| 仓库误提交构建产物与临时脚本 | 清理并补充 `.gitignore`(含 79MB 课件产物) |
---
## 移除 / 不兼容
- **Avalonia 整套界面与窗口宿主已移除**,模型只通过 Flutter 渲染
- **百宝箱页面已删除**(今日人品等能力并入用户页)
- **设置页的主题色选择已删除**,改用账号主题色
- `.GC/user/<用户名>.yaml` 旧布局会在启动时**自动迁移**到 `<用户名>/pw.yaml`
---
## 升级说明
- **Windows**:`GCL-1.1.2-win-amd64.zip` / `GCL-1.1.2-win-arm64.zip`
- **macOS**:`GCL-1.1.2-mac-arm64.zip`
- macOS 包为 **ad-hoc 签名**(无开发者证书),首次打开需右键 →「打开」,或在「系统设置 → 隐私与安全性」里放行
- 从 1.1.1 覆盖安装即可,`.GC/` 下的账号、模型、设置都会保留
- 升级后每个包都会校验 sha256(来自已签名清单),不一致会拒绝安装
---
## 已知问题
- 主题色退款可被反复利用:买 A(−50)→ 退 40 → 净支出 10 分即可换一次色,1 小时内可连续操作。当前按「1 小时内退 80%」的规则实现,属预期行为
- `nightly` / `ip-prerelease` 两个预发布的 tag 不是版本号,客户端升级逻辑会跳过它们,不会被误推给用户
- CI 里**不会**重新生成 `version.json`(需要 SAVEDOG 签名私钥),发布清单仍需本地 `./build.sh stamp`
---
<details>
<summary>提交清单(18 个)</summary>
```
38781c9 refactor(ui): 删除百宝箱页;设置页去掉主题色
ecb71ad feat(user): 用户系统重做——人机验证、30 天签到、主题色购买与退款、人品值
e7c1429 feat(ci): 新增 @build-release-bot build <版本号>
5b82a88 fix(build-bot): report job 加 GH_REPO;已合并 PR 改为编默认分支
936ef83 fix: macOS 构建去掉 --no-codesign;build-bot 失败也回帖结果
ab0cee8 ci: build-bot 增加「开始编译」回执;macOS runner 改用 macos-latest
f64f270 ci: 修 pr-review 日志路径不一致导致「(无日志)」
0d383f9 ci: 修正 pr-review 的冲突判断与静态分析阈值
ea1fa6b feat: 全面迁移到 Flutter + 新增 GitHub 源与 CI 流水线
b9cb56c fix: 清理误提交的构建产物和临时脚本,补充 .gitignore
2640de0 build: macOS 发布包编译完成
4872505 feat: rewrite all models in Flutter
9cd4fa6 fix: 修复 15 项优化与 bug
46ed844 fix(security): 加固模型安装与本地目录源,防止同机后端伪装
355ca89 feat(courseware): Flutter WebView 还原等高线课件并去除授权验证
5b62897 feat(contour-map): 重写为可交互 3D 等高线模型,新增五大地貌专题
ead63e8 fix(macos): 模型窗口改由主线程承载,修复启动模型失败与后端崩溃
3efdf74 fix(macos): Release 版补 network 权限,修复启动后无法连接后端
```
</details>
-77
View File
@@ -1,77 +0,0 @@
#!/bin/sh
# ---------------------------------------------------------------------------
# GC 构建入口(薄封装)
#
# ./build.sh build 完整发布(当前主机对应的全部平台)
# ./build.sh build --targets=mac 只出 macOS(跳过 Windows 交叉编译)
# ./build.sh build --targets=win,linux 只出 Windows / Linux
# ./build.sh build -version=1.1.3 指定版本号(写回 Directory.Build.props)
# ./build.sh check 验证:编译 + 产物
# ./build.sh models 编译模型 dll + 封面 + 版本戳
# ./build.sh stamp 重新生成 version.json
# ./build.sh run / pack-models / pack-launcher
# ./build.sh clean 清理构建产物
# ./build.sh doctor dotnet 信息
# ./build.sh dist 列出产物
#
# 环境变量:
# GC_VERBOSE=1 显示细节(各步骤日志尾部、产物路径)
# GC_QUIET=1 只显示警告与错误
# GC_NO_PROGRESS=1 关闭进度条(保留步骤行)
#
# 实际代码都在 buildsh/ 里,本文件只负责加载模块与分发。
# ---------------------------------------------------------------------------
set -eu
# Avalonia 遥测任务在只读用户目录/CI/沙箱会因写日志失败中断编译(MSB4018)
export AVALONIA_TELEMETRY_OPTOUT=1
ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
cd "$ROOT_DIR"
export GC_ROOT="$ROOT_DIR"
APP_PROJ="GC-BOOT/GC-BOOT.csproj"
SAVEDOG_PROJ="GC-SAVEDOG/GC-SAVEDOG.csproj"
STAMP_PROJ="model/_engine/VersionStamp/VersionStamp.csproj"
SLN="GC.sln"
VERSION=$(sed -n 's/.*<Version>\(.*\)<\/Version>.*/\1/p' Directory.Build.props | head -1)
[ -n "$VERSION" ] || VERSION="1.0.0"
TASK="${1:-build}"
shift 2>/dev/null || true
# 解析 -version= / --version= / --targets= / --allow-no-ui
CLI_VERSION=""
for arg in "$@"; do
case "$arg" in
-version=*|--version=*) CLI_VERSION="${arg#*=}" ;;
-targets=*|--targets=*|--only=*) export GC_TARGETS="${arg#*=}" ;;
esac
done
if [ -n "$CLI_VERSION" ]; then
VERSION="$CLI_VERSION"
# 写回 Directory.Build.props,让程序集版本与关于页显示一致
if [ -f Directory.Build.props ]; then
sed -i.bak "s|<Version>[^<]*</Version>|<Version>${VERSION}</Version>|" Directory.Build.props
rm -f Directory.Build.props.bak
fi
printf '==> 版本号设为 %s\n' "$VERSION"
fi
mkdir -p "$ROOT_DIR/build/logs"
# 加载模块(顺序即依赖顺序)
for _m in log progress publish core package; do
. "$ROOT_DIR/buildsh/lib/$_m.sh"
done
unset _m
. "$ROOT_DIR/buildsh/build.sh"
. "$ROOT_DIR/buildsh/check.sh"
. "$ROOT_DIR/buildsh/tools.sh"
. "$ROOT_DIR/buildsh/release.sh"
case "$TASK" in
build) bs_build "$ROOT_DIR" ;;
check) bs_check "$ROOT_DIR" ;;
release-verify) bs_verify_release "$ROOT_DIR" "$@" ;;
*) bs_tools "$ROOT_DIR" "$TASK" "$@" ;;
esac
-210
View File
@@ -1,210 +0,0 @@
#!/bin/sh
# buildsh/build.sh —— 完整发布
#
# 所有界面统一由 Avalonia 承载(主窗口 / 模型窗口 / 课件),不再有 Flutter 前端。
#
# 目标平台(默认按构建主机推断,可用 --targets= 覆盖):
# macOS 主机 : mac-arm64(原生) + win-amd64 / win-arm64(mingw 交叉)
# Linux 主机 : win-amd64 / win-arm64(mingw 交叉)
# Linux 产物默认不构建;需要时 GC_BUILD_LINUX=1 显式开启
# Windows 主机: win-amd64 / win-arm64(原生)
#
# ./build.sh build 全平台
# ./build.sh build --targets=mac 只出 macOS
# ./build.sh build --targets=win 只出 Windows
# ---------------------------------------------------------------- 目标与权重
_resolve_targets() {
BUILD_MAC=0; BUILD_WIN=0; BUILD_LINUX=0
case "$(uname -s)" in
Darwin) _host="mac" ;;
MINGW*|MSYS*|CYGWIN*) _host="windows" ;;
*) _host="linux" ;;
esac
GC_HOST="$_host"
_want="${GC_TARGETS:-}"
if [ -z "$_want" ]; then
case "$_host" in
mac) _want="mac,win" ;;
windows) _want="win" ;;
*) _want="win" ;;
esac
fi
_ifs=$IFS; IFS=','
for _t in $_want; do
case "$_t" in
''|' ') continue ;;
mac|macos|darwin) BUILD_MAC=1 ;;
win|windows) BUILD_WIN=1 ;;
linux) BUILD_LINUX=1 ;;
all) BUILD_MAC=1; BUILD_WIN=1; BUILD_LINUX=1 ;;
*) IFS=$_ifs; err "未知目标 '$_t'(可用:mac / win / linux / all)"; return 1 ;;
esac
done
IFS=$_ifs
if [ "$BUILD_MAC" = 1 ] && [ "$_host" != mac ]; then
err "macOS 产物只能在 macOS 上编译(当前 $(uname -s))"; return 1
fi
# Linux 产物:必须是 aarch64 主机且显式开启
if [ "$BUILD_LINUX" = 1 ]; then
case "${GC_BUILD_LINUX:-0}" in
1|true|yes) ;;
*) BUILD_LINUX=0; detail "跳过 Linux 产物(需要时 GC_BUILD_LINUX=1)" ;;
esac
if [ "$BUILD_LINUX" = 1 ]; then
case "$(uname -m)" in
aarch64|arm64) ;;
*) BUILD_LINUX=0
warn "已请求 Linux 产物,但当前主机是 $(uname -m)(linux-arm64 需要 aarch64 主机)" ;;
esac
fi
fi
# 发布计划:RID:标签
_PLAN=""
[ "$BUILD_MAC" = 1 ] && _PLAN="$_PLAN osx-arm64:mac-arm64"
[ "$BUILD_WIN" = 1 ] && _PLAN="$_PLAN win-x64:win-amd64 win-arm64:win-arm64"
[ "$BUILD_LINUX" = 1 ] && _PLAN="$_PLAN linux-arm64:linux-arm64"
[ -n "$_PLAN" ] || { err "没有要构建的目标"; return 1; }
# 打包阶段只处理本次构建的平台,避免把 dist 里其它平台的旧残留也重新打包
GC_PACK_LABELS=""
for _t in $_PLAN; do GC_PACK_LABELS="$GC_PACK_LABELS ${_t##*:}"; done
export GC_PACK_LABELS
}
_init_weights() {
_ws="3 60 7 27 3" # 准备 / 编译发布 / 组装 / 打包 / 收尾
_tot=0
for _w in $_ws; do _tot=$((_tot + _w)); done
progress_init "$_tot" $_ws
}
# 编译阶段预估秒数(只用于进度条推进,不影响正确性)
_est_compile() {
_n=0
for _t in $_PLAN; do _n=$((_n + 1)); done
printf '%s' $((_n * 70))
}
# ---------------------------------------------------------------- 脚本自检
# `$VAR` 紧跟全角字符(如 ")")时,变量名会把多字节字符一起吃进去,
# set -u 下直接报 "_plat?: unbound variable"。这个坑历史上出现过两次,
# 交给机器每轮查一遍比靠人眼可靠(找不到 python3 就跳过)。
_lint_scripts() {
command -v python3 >/dev/null 2>&1 || { detail "无 python3,跳过脚本自检"; return 0; }
python3 - "$GC_ROOT" <<'PY'
import re, sys, glob, os
root = sys.argv[1]
pat = re.compile(r'(?<!\$\{)\$([A-Za-z_][A-Za-z0-9_]*)([^\x00-\x7f])')
files = [os.path.join(root, 'build.sh')]
files += glob.glob(os.path.join(root, 'buildsh', '**', '*.sh'), recursive=True)
bad = []
for f in files:
try:
lines = open(f, encoding='utf-8').read().splitlines()
except OSError:
continue
for i, line in enumerate(lines, 1):
if line.lstrip().startswith('#'): # 整行注释里的 $符号不会参与解析
continue
for m in pat.finditer(line):
bad.append('%s:%d: $%s 后接 %r' % (os.path.relpath(f, root), i, m.group(1), m.group(2)))
if bad:
sys.stderr.write(' 脚本里变量名后紧跟全角字符(请改成 ${VAR}):\n')
for b in bad:
sys.stderr.write(' ' + b + '\n')
sys.exit(1)
PY
}
# ---------------------------------------------------------------- 阶段
# 各 RID 发布:Avalonia 界面编进 GC 主程序,无需单独的前端构建阶段
_phase_compile() {
for _t in $_PLAN; do
publish_rid "${_t%%:*}" "${_t##*:}" || return 1
done
}
_phase_assemble() {
for _l in win-amd64 win-arm64 linux-arm64; do
prepare_runtime_layout "$GC_STAGE/$_l"
done
if [ -d "$GC_STAGE/mac-arm64" ]; then
prepare_runtime_layout "$GC_STAGE/mac-arm64"
package_mac_app "$GC_STAGE/mac-arm64" || return 1
step_ok "GC.app 组装完成"
fi
}
_summary() {
_span=$(timer_span "$_t_all")
printf '\n'
say "完成,用时 ${_span}"
_found=0
for _z in "$GC_ROOT"/dist/*/*.zip; do
[ -f "$_z" ] || continue
_found=1
printf ' %6s %s\n' "$(_hsize "$_z")" "$(_rel "$_z")"
done
[ "$_found" = 1 ] || note "(dist 下没有产物)"
}
# ---------------------------------------------------------------- 入口
bs_build() {
ROOT_DIR="$1"
GC_ROOT="$ROOT_DIR"; export GC_ROOT
GC_STAGE="$ROOT_DIR/build/stage"; export GC_STAGE
: "${APP_PROJ:?}" "${VERSION:?}"
_resolve_targets || return 1
preflight || return 1
_init_weights
_t_all=$(timer_start)
# ---- 准备:清暂存区 + 生成清单(不签名,打包结束后统一签一次)
progress_step "准备"
mkdir -p "$GC_ROOT/build/logs" "$GC_ROOT/build/cache"
if [ -d "$GC_ROOT/build/trash" ]; then
mv "$GC_ROOT/build/trash" "${TMPDIR:-/tmp}/gc-trash-$(date +%s)" 2>/dev/null || true
fi
_trash "$GC_STAGE"
mkdir -p "$GC_STAGE"
_trash "$GC_ROOT/build/pkg"
detail "目标:$(printf '%s' "$_PLAN" | tr ' ' '\n' | cut -d: -f2 | tr '\n' ' ')"
_lint_scripts || return 1
stamp_versions --no-sign || return 1
progress_tick 100
# ---- 编译:各 RID 发布(Avalonia 已编进主程序)
progress_step "编译"
_run_phase "$(_est_compile)" _phase_compile || return 1
# ---- 组装:运行目录布局 + mac .app
progress_step "组装"
_phase_assemble || return 1
progress_tick 100
# ---- 打包:zip + 清单 sha256 + 签名
progress_step "打包"
pack_launcher || return 1
progress_tick 100
# ---- 收尾
progress_step "收尾"
progress_done
_summary
}
-44
View File
@@ -1,44 +0,0 @@
#!/bin/sh
# buildsh/check.sh —— 验证:编译 + 产物完整性
#
# 原先的「模型自检」和「离屏渲染」两项依赖已移除的截图工程;
# 这里只保证 C# 侧编译干净、发布包齐备。
#
# 步骤权重:编译(60) 产物(40)
bs_check() {
ROOT_DIR="$1"
GC_ROOT="${GC_ROOT:-$ROOT_DIR}"; export GC_ROOT
mkdir -p "$GC_ROOT/build/logs"
progress_init 100 60 40
_fail=0
progress_step "编译"
if run_logged "$GC_ROOT/build/logs/check-build.log" "解决方案编译 " \
dotnet build "$SLN" -c Release --nologo -v:q; then
progress_tick 100
else
_fail=1; progress_tick 100
fi
progress_step "产物"
_n=0
for _z in "$ROOT_DIR"/dist/*/GCL-"$VERSION"-*.zip; do
[ -f "$_z" ] && _n=$((_n + 1))
done
if [ "$_n" -ge 1 ]; then
detail "共 ${_n} 个发布包"
else
_fail=1; warn "dist 下没有发布包(先跑 ./build.sh build)"
fi
progress_tick 100
progress_done
if [ "$_fail" -eq 0 ]; then
step_ok "全部通过"
else
err "有失败项"
fi
return "$_fail"
}
@@ -1,39 +0,0 @@
# 在 Linux / macOS 上交叉编译 Flutter Windows 桌面应用的 CMake 工具链。
#
# 原理:Flutter 的 Windows 嵌入层(windows/runner/*.cpp + cpp_client_wrapper)
# 是纯 Win32 + 标准 C++,只通过 C ABI 调用 flutter_windows.dll。因此用
# mingw-w64(GCC,posix 线程模型)即可产出与官方 toolchain 等价的 PE 产物,
# 不需要 Windows 机器,也不需要 MSVC。
#
# 用法:
# cmake -B build -G Ninja -DCMAKE_TOOLCHAIN_FILE=.../toolchain-mingw.cmake ...
set(CMAKE_SYSTEM_NAME Windows)
set(CMAKE_SYSTEM_VERSION 10.0)
set(CMAKE_SYSTEM_PROCESSOR x86_64)
set(MINGW_PREFIX "x86_64-w64-mingw32" CACHE STRING "目标三元组前缀")
# 必须用 posix 线程模型:Flutter 的 C++ wrapper 依赖 std::mutex / std::thread,
# win32 线程模型下的 libstdc++ 不提供这些类型。
find_program(MINGW_C NAMES ${MINGW_PREFIX}-gcc-posix ${MINGW_PREFIX}-gcc REQUIRED)
find_program(MINGW_CXX NAMES ${MINGW_PREFIX}-g++-posix ${MINGW_PREFIX}-g++ REQUIRED)
find_program(MINGW_RC NAMES ${MINGW_PREFIX}-windres REQUIRED)
set(CMAKE_C_COMPILER "${MINGW_C}")
set(CMAKE_CXX_COMPILER "${MINGW_CXX}")
set(CMAKE_RC_COMPILER "${MINGW_RC}")
set(CMAKE_FIND_ROOT_PATH "/usr/${MINGW_PREFIX}")
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)
# 静态链接 libgcc / libstdc++ / winpthread,产物只依赖 flutter_windows.dll
# 和系统 DLL,拷到干净机器上也能跑。
set(CMAKE_CXX_FLAGS_INIT "-DUNICODE -D_UNICODE -DNOMINMAX -D_HAS_EXCEPTIONS=1")
set(CMAKE_EXE_LINKER_FLAGS_INIT "-static -static-libgcc -static-libstdc++")
# GCC 16 兼容性
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-compound-token-split-by-macro -Wno-deprecated-attributes")
-16
View File
@@ -1,16 +0,0 @@
#!/bin/sh
# buildsh/lib/build_funcs.sh —— 兼容入口
#
# 原先是单文件函数库,现按职责拆成:
# log.sh 输出层(say / step_ok / note / detail / warn / err / run_logged)
# progress.sh 进度显示(终端进度条 / 非终端逐行)
# publish.sh 环境预检、工具程序集缓存、dotnet 发布、阶段执行
# core.sh 版本清单、签名、模型构建
# package.sh 组装 .app、生成发布 zip
#
# 保留本文件是为了老的 `source buildsh/lib/build_funcs.sh` 用法继续可用。
_bf_root="${GC_ROOT:-${ROOT_DIR:?build_funcs.sh 需要先设置 ROOT_DIR 或 GC_ROOT}}"
for _bf_m in log progress publish core package; do
. "$_bf_root/buildsh/lib/$_bf_m.sh"
done
unset _bf_m _bf_root
-75
View File
@@ -1,75 +0,0 @@
#!/bin/sh
# buildsh/lib/core.sh —— 版本清单 / 签名 / 模型构建
#
# 这些步骤原来全用 dotnet run --project,每次都要走一遍 MSBuild(还不算输出噪音)。
# 现在统一走 dt_tool:首次构建工具程序集,之后直接跑 dll。
# 只在清单需要重算时生成;--no-sign 用于完整构建的中途(打包结束后统一签一次)
stamp_versions() {
say "生成 version.json"
run_logged "$GC_ROOT/build/logs/stamp.log" "生成 version.json " \
dt_tool stamp "$STAMP_PROJ" VersionStamp "$GC_ROOT" "$VERSION" || return 1
step_ok "version.json(${VERSION})"
case "${1:-}" in
--no-sign) detail "跳过中途签名,打包结束后统一签一次" ;;
*) sign_manifest ;;
esac
}
# 打完 zip 后只刷新启动器段(path / dir / name / sha256 / size)。
# 模型指纹涉及几百 MB 文件,没必要再算一遍。
stamp_launcher_only() {
say "刷新包信息(sha256 / 体积)"
run_logged "$GC_ROOT/build/logs/stamp-launcher.log" "刷新包信息 " \
dt_tool stamp "$STAMP_PROJ" VersionStamp "$GC_ROOT" "$VERSION" --launcher-only || return 1
sign_manifest
}
# 用 .signing/ 里的私钥签 version.json(私钥不入库)。没有私钥只警告:
# 清单不带 signature,客户端按「未签名」处理。
#
# keyId 必须与私钥真正对应,否则签出来的清单自己都验不过(客户端更会拒):
# 本地私钥可能是上一代 gc-2026-11,而默认值写的是 gc-2026-12。
# 所以这里从 SignatureKeyring.cs 取出所有已注册 keyId 逐个试签,第一个通过验签的胜出。
sign_manifest() {
_key="$GC_ROOT/.signing/gc-signing.pem"
if [ ! -f "$_key" ]; then
warn "未找到签名私钥 .signing/gc-signing.pem,version.json 未签名(客户端会拒绝更新)"
note "生成密钥:dotnet run --project GC-SAVEDOG -- keygen"
return 0
fi
_ids="${GC_SIGNING_KEY_ID:-}"
if [ -z "$_ids" ]; then
_kr="$GC_ROOT/GC/src/Security/SignatureKeyring.cs"
[ -f "$_kr" ] && _ids=$(grep -oE '"gc-[0-9]{4}-[0-9]{2}"' "$_kr" | tr -d '"' | sort -u | tr '\n' ' ')
fi
[ -n "$_ids" ] || _ids="gc-2026-12"
_tmp="$GC_ROOT/build/tmp/version.signed.json"
mkdir -p "$(dirname "$_tmp")"
for _id in $_ids; do
if dt_tool savedog "$SAVEDOG_PROJ" GC-SAVEDOG sign \
--manifest "$GC_ROOT/version.json" --key "$_key" \
--key-id "$_id" --out "$_tmp" >"$GC_ROOT/build/logs/sign.log" 2>&1; then
mv "$_tmp" "$GC_ROOT/version.json"
# model/version.json 必须与根清单完全一致(同一签名),否则走 model 地址的源会验签失败
cp "$GC_ROOT/version.json" "$GC_ROOT/model/version.json"
step_ok "已签名(${_id})"
return 0
fi
detail "keyId ${_id} 与本地私钥不匹配,换下一个"
done
err "签名失败:本地私钥与内置公钥环里的 keyId 都对不上"
note "可用 GC_SIGNING_KEY_ID=<id> 指定;或用 keygen 重新生成并登记公钥"
return 1
}
# 模型程序集由各模型的 src/ 单独编译(./build.sh models),
# 这里只刷新清单里的模型指纹。
build_models() {
say "模型清单"
note "只刷新清单;需要重编模型请用 ./build.sh models"
stamp_versions
}
-83
View File
@@ -1,83 +0,0 @@
#!/bin/sh
# buildsh/lib/log.sh —— 统一输出层
#
# 设计:默认只显示「步骤 / 结论」,细节进日志文件;需要细节时开 GC_VERBOSE=1。
#
# GC_VERBOSE=1 额外显示细节(日志尾部、跳过项、产物路径)
# GC_QUIET=1 只显示警告与错误(后台任务用,避免打乱进度条)
# NO_COLOR=1 关闭颜色(写在前面:重定向到文件时自动关闭)
#
# 提供:
# say <文本> 主步骤 ==> 文本
# step_ok <文本> 步骤完成 ✓ 文本
# note <文本> 一般信息(缩进)
# detail <文本> 细节(仅 GC_VERBOSE)
# warn / err <文本> 警告 / 错误(不受 GC_QUIET 影响)
# run_logged <日志> <标签> <命令...>
# 输出全部进日志;失败时回显尾部,成功时静默
GC_VERBOSE=${GC_VERBOSE:-0}
GC_QUIET=${GC_QUIET:-0}
GC_ROOT=${GC_ROOT:-}
if [ -t 1 ] && [ -z "${NO_COLOR:-}" ]; then
_C_STEP=$(printf '\033[36m')
_C_OK=$(printf '\033[32m')
_C_WARN=$(printf '\033[33m')
_C_ERR=$(printf '\033[31m')
_C_DIM=$(printf '\033[2m')
_C_OFF=$(printf '\033[0m')
else
_C_STEP=''; _C_OK=''; _C_WARN=''; _C_ERR=''; _C_DIM=''; _C_OFF=''
fi
# 路径转相对(日志里少一长串前缀)
_rel() {
if [ -n "$GC_ROOT" ]; then printf '%s' "${1#"$GC_ROOT"/}"; else printf '%s' "$1"; fi
}
say() { [ "$GC_QUIET" = 1 ] && return 0; printf '%s==>%s %s\n' "$_C_STEP" "$_C_OFF" "$*"; }
step_ok() { [ "$GC_QUIET" = 1 ] && return 0; printf '%s ✓%s %s\n' "$_C_OK" "$_C_OFF" "$*"; }
note() { [ "$GC_QUIET" = 1 ] && return 0; printf ' %s\n' "$*"; }
detail() { [ "$GC_VERBOSE" = 1 ] && [ "$GC_QUIET" != 1 ] || return 0
printf '%s %s%s\n' "$_C_DIM" "$*" "$_C_OFF"; }
warn() { printf '%s !!%s %s\n' "$_C_WARN" "$_C_OFF" "$*" >&2; }
err() { printf '%s xx%s %s\n' "$_C_ERR" "$_C_OFF" "$*" >&2; }
# 跑命令:输出全部写进日志文件。
# - 成功:静默(GC_VERBOSE 时回显最后几行)
# - 失败:回显日志尾部,让人不用翻文件也能看到原因
run_logged() {
_rl_log="$1"; _rl_label="$2"; shift 2
mkdir -p "$(dirname "$_rl_log")" 2>/dev/null || true
"$@" >"$_rl_log" 2>&1
_rl_st=$?
if [ "$_rl_st" -ne 0 ]; then
err "${_rl_label}失败(日志:$(_rel "$_rl_log"))"
if [ -s "$_rl_log" ]; then
# 只挑有信息量的行:跳过空行;超长行(编译器把整条命令行打进日志)截断,
# 否则一屏全是 3000 字符的 swiftc 参数,真正的原因反而被淹掉。
grep -vE '^[[:space:]]*$' "$_rl_log" | tail -12 \
| cut -c1-200 | sed 's/^/ /' >&2
fi
else
detail "${_rl_label}完成($(_rel "$_rl_log"))"
fi
return "$_rl_st"
}
# 人类可读大小。不用 du:某些环境(沙箱/迷你工具箱)的 du 会报块占用而非文件大小
_hsize() {
_hb=$(wc -c < "$1" 2>/dev/null | tr -d ' ')
[ -n "$_hb" ] || _hb=0
if [ "$_hb" -ge 1048576 ]; then printf '%dM' $((_hb / 1048576))
elif [ "$_hb" -ge 1024 ]; then printf '%dK' $((_hb / 1024))
else printf '%dB' "$_hb"; fi
}
# 计时(秒):_t0=$(timer_start) ... timer_span "$_t0" -> 3m12s
timer_start() { date +%s; }
timer_span() {
_ts=$(( $(date +%s) - $1 ))
if [ "$_ts" -ge 60 ]; then printf '%dm%02ds' $((_ts / 60)) $((_ts % 60)); else printf '%ds' "$_ts"; fi
}
-255
View File
@@ -1,255 +0,0 @@
#!/bin/sh
# buildsh/lib/package.sh —— 组装 .app / 生成发布 zip
#
# 打包策略(相对旧实现的收益):
# 旧:publish 到 dist/<平台> → cp -R 整个目录到暂存区 → zip → rm -rf 两处
# 每个平台白白多搬一份 200MB,还要删两次上万文件。
# 新:publish 到 build/stage/<平台> → 就地改名/裁剪 → 直接从 stage 压缩
# → 目录挪进 trash。零冗余复制,删除也不再是批量递归删。
# 剔除与目标平台无关 / 只在调试时才加载的组件。
# Windows 用 Kestrel 自托管,不经 IIS/HttpSys;Avalonia 在 Windows 上只走 Win32 后端;
# DAC/DBI/DiaSymReader 只在调试器与读 PDB 时需要,而发布包 DebugType=none、不带 PDB。
prune_package() {
_dir="$1"; _plat="$2"
[ -d "$_dir" ] || return 0
rm -f "$_dir"/mscordaccore*.dll \
"$_dir"/mscordbi.dll \
"$_dir"/Microsoft.DiaSymReader.Native*.dll \
"$_dir"/web.config \
"$_dir"/aspnetcorev2_inprocess.dll \
"$_dir"/Microsoft.AspNetCore.Server.IIS.dll \
"$_dir"/Microsoft.AspNetCore.Server.IISIntegration.dll \
"$_dir"/Microsoft.AspNetCore.Server.HttpSys.dll
case "$_plat" in
win)
# ProjectReference 会把后端 exe 的 runtimeconfig 一起拷过来;后端已编入启动器
rm -f "$_dir"/GC.UI.Server.exe "$_dir"/GC.UI.Server.dll \
"$_dir"/GC.UI.Server.deps.json "$_dir"/GC.UI.Server.runtimeconfig.json
rm -f "$_dir"/Avalonia.X11.dll "$_dir"/Avalonia.Native.dll \
"$_dir"/Avalonia.FreeDesktop.dll "$_dir"/Tmds.DBus.Protocol.dll
;;
linux)
rm -f "$_dir"/Avalonia.Win32.dll "$_dir"/Avalonia.Win32.Automation.dll
;;
esac
}
# 发布目录只放程序本体:.GC 与 model 都由首次启动自行创建(AppPaths.EnsureCreated)
prepare_runtime_layout() {
_dir="$1"
[ -d "$_dir" ] || return 0
rm -rf "$_dir/model" "$_dir/examples" "$_dir/.GC"
}
_zip_dir() { # <父目录> <目录名> <zip>
if [ "$(uname -s)" = Darwin ] && command -v ditto >/dev/null 2>&1; then
ditto -c -k --sequesterRsrc --keepParent "$1/$2" "$3" # 保留权限与符号链接
else
( cd "$1" && zip -qryX "$3" "$2" -x "*.DS_Store" )
fi
}
_zip_file() { # <文件> <zip>
( cd "$(dirname "$1")" && zip -qX "$2" "$(basename "$1")" )
}
# 组装 GC.app:把 stage 目录里的所有产物收进 Contents/MacOS(Avalonia 界面已编进 GC 主程序)
package_mac_app() {
_dist="$1"
_app="$_dist/GC.app"
_trash "$_app"
mkdir -p "$_app/Contents/MacOS" "$_app/Contents/Resources"
cat > "$_app/Contents/Info.plist" <<PLIST
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleName</key><string>GC</string>
<key>CFBundleDisplayName</key><string>GC</string>
<key>CFBundleIdentifier</key><string>com.xhmcl.GC</string>
<key>CFBundleVersion</key><string>${VERSION}</string>
<key>CFBundleShortVersionString</key><string>${VERSION}</string>
<key>CFBundlePackageType</key><string>APPL</string>
<key>CFBundleExecutable</key><string>GC</string>
<key>CFBundleInfoDictionaryVersion</key><string>6.0</string>
<key>LSMinimumSystemVersion</key><string>11.0</string>
<key>NSHighResolutionCapable</key><true/>
<!-- Avalonia 主界面就在这个进程里,需要出现在 Dock -->
</dict>
</plist>
PLIST
for _f in "$_dist"/*; do
_base=$(basename "$_f")
case "$_base" in GC.app|.DS_Store) continue ;; esac
mv "$_f" "$_app/Contents/MacOS/"
done
# 图标:从 icon-1024.png 生成 .icns。生成一次就缓存(原来每次构建都跑十几遍 sips)
_icon="$GC_ROOT/GC/src/Assets/icon-1024.png"
_icns="$GC_ROOT/build/cache/AppIcon.icns"
if [ -f "$_icon" ] && command -v iconutil >/dev/null 2>&1; then
if [ ! -f "$_icns" ] || [ "$_icon" -nt "$_icns" ]; then
_set="$GC_ROOT/build/cache/AppIcon.iconset"
rm -rf "$_set"; mkdir -p "$_set"
for _sz in 16 32 64 128 256 512; do
sips -z "$_sz" "$_sz" "$_icon" --out "$_set/icon_${_sz}x${_sz}.png" >/dev/null 2>&1
_d=$((_sz * 2))
sips -z "$_d" "$_d" "$_icon" --out "$_set/icon_${_sz}x${_sz}@2x.png" >/dev/null 2>&1
done
mkdir -p "$GC_ROOT/build/cache"
iconutil -c icns "$_set" -o "$_icns" 2>/dev/null || true
rm -rf "$_set"
detail "生成 AppIcon.icns"
else
detail "复用缓存 AppIcon.icns"
fi
if [ -f "$_icns" ]; then
cp "$_icns" "$_app/Contents/Resources/AppIcon.icns"
/usr/libexec/PlistBuddy -c "Delete :CFBundleIconFile" "$_app/Contents/Info.plist" 2>/dev/null || true
/usr/libexec/PlistBuddy -c "Add :CFBundleIconFile string AppIcon" "$_app/Contents/Info.plist" 2>/dev/null || true
fi
fi
# .GC 由首次启动创建;包里只保留 pack_launcher 后补的 .GC/bin
rm -rf "$_app/Contents/MacOS/.GC"
chmod +x "$_app/Contents/MacOS/GC" 2>/dev/null || true
}
# 生成全部发布 zip。数据源是 build/stage/<平台>;
# 若 stage 不存在则回落到 dist/<平台>(支持单独跑 ./build.sh pack-launcher)
pack_launcher() {
say "生成发布包"
_pkgroot="$GC_ROOT/build/pkg"
_trash "$_pkgroot"
mkdir -p "$_pkgroot"
# ---------- Windows / Linux:整目录打包 ----------
# 只打包本次构建的「非 mac」平台;mac 走下面的 .app 流程。
# 单独跑 pack-launcher 时(没有 GC_PACK_LABELS)按全部标签处理。
_labels=""
for _l in ${GC_PACK_LABELS:-win-amd64 win-arm64 linux-arm64}; do
case "$_l" in mac-*) continue ;; esac
_labels="$_labels $_l"
done
for _label in $_labels; do
_src="$GC_STAGE/$_label"
_name="GCL-${VERSION}-${_label}"
_pkg="$_pkgroot/$_name"
if [ -d "$_src" ]; then
mv "$_src" "$_pkg" 2>/dev/null || cp -R "$_src" "$_pkg" # 同分区 rename,零拷贝
elif [ -z "${GC_PACK_LABELS:-}" ] && [ -d "$GC_ROOT/dist/$_label" ]; then
cp -R "$GC_ROOT/dist/$_label" "$_pkg" # 兼容旧布局
else
continue
fi
rm -f "$_pkg"/*.zip "$_pkg"/.DS_Store 2>/dev/null || true
case "$_label" in
win-*) prune_package "$_pkg" win ;;
linux-*) prune_package "$_pkg" linux ;;
esac
# 启动器改名成包名;后端与前端是随包产物,不能当成启动器
_exe="$_pkg/GC.exe"
[ -f "$_exe" ] || _exe=$(ls "$_pkg"/*.exe 2>/dev/null | grep -v 'GC-SAVEDOG\|GC.UI.Server\|GC-UI' | head -1)
if [ -n "$_exe" ] && [ -f "$_exe" ]; then
mv "$_exe" "$_pkg/$_name.exe"
chmod +x "$_pkg/$_name.exe" 2>/dev/null || true
elif [ -f "$_pkg/GC" ]; then
mv "$_pkg/GC" "$_pkg/$_name"
chmod +x "$_pkg/$_name" 2>/dev/null || true
else
_trash "$_pkg"; continue
fi
# 非本体文件统一收进 .GC/bin:安装目录根只留 GC 本体(首次启动复制到 .GC/safedog)
for _osd in GC-SAVEDOG.exe GC-SAVEDOG; do
if [ -f "$_pkg/$_osd" ]; then
mkdir -p "$_pkg/.GC/bin"
mv "$_pkg/$_osd" "$_pkg/.GC/bin/"
fi
done
[ -f "$_pkg/GC-SAVEDOG.exe" ] || [ -f "$_pkg/.GC/bin/GC-SAVEDOG" ] || \
[ -f "$_pkg/.GC/bin/GC-SAVEDOG.exe" ] || warn "$_label 缺少守护进程,该平台将退回旧脚本更新"
_zip="$GC_ROOT/dist/$_label/$_name.zip"
mkdir -p "$GC_ROOT/dist/$_label"
# 旧布局会在 dist/<平台>/ 里留裸产物(GC、GC-SAVEDOG、GC-UI.app…),只保留 zip
for _old in "$GC_ROOT/dist/$_label"/*; do
[ -e "$_old" ] || continue
case "$_old" in *.zip) continue ;; esac
_trash "$_old"
done
rm -f "$_zip"
case "$_label" in
win-*) _zip_dir "$_pkgroot" "$_name" "$_zip" || return 1 ;;
*) ( cd "$_pkgroot" && zip -qryX "$_zip" "$_name" ) || return 1 ;;
esac
[ -s "$_zip" ] || { err "$_label 压缩产物为空"; return 1; }
_trash "$_pkg"
step_ok "dist/$_label/$_name.zip($(_hsize "$_zip"))"
done
# ---------- macOS:.app 目录 + ditto 压缩 ----------
_want_mac=1
if [ -n "${GC_PACK_LABELS:-}" ]; then
_want_mac=0
case " ${GC_PACK_LABELS} " in *" mac-arm64 "*) _want_mac=1 ;; esac
fi
_stage_mac="$GC_STAGE/mac-arm64"
if [ "$_want_mac" = 1 ] && [ -d "$_stage_mac/GC.app" ]; then
_name="GCL-${VERSION}-mac-arm64"
_app="$_pkgroot/$_name.app"
mv "$_stage_mac/GC.app" "$_app" 2>/dev/null || cp -R "$_stage_mac/GC.app" "$_app"
chmod +x "$_app/Contents/MacOS/GC" 2>/dev/null || true
_plist="$_app/Contents/Info.plist"
if [ -f "$_plist" ]; then
/usr/libexec/PlistBuddy -c "Set :CFBundleName Morris GC" "$_plist" 2>/dev/null || true
/usr/libexec/PlistBuddy -c "Set :CFBundleDisplayName Morris GC" "$_plist" 2>/dev/null || true
fi
# 与 Windows 布局一致:守护进程收进 .GC/bin,首次启动复制到 .GC/safedog
if [ -f "$_app/Contents/MacOS/GC-SAVEDOG" ]; then
mkdir -p "$_app/Contents/MacOS/.GC/bin"
mv "$_app/Contents/MacOS/GC-SAVEDOG" "$_app/Contents/MacOS/.GC/bin/"
chmod +x "$_app/Contents/MacOS/.GC/bin/GC-SAVEDOG" 2>/dev/null || true
fi
xattr -cr "$_app" 2>/dev/null || true
_zip="$GC_ROOT/dist/mac-arm64/$_name.zip"
mkdir -p "$GC_ROOT/dist/mac-arm64"
for _old in "$GC_ROOT/dist/mac-arm64"/*; do
[ -e "$_old" ] || continue
case "$_old" in *.zip) continue ;; esac
_trash "$_old"
done
rm -f "$_zip"
_zip_dir "$_pkgroot" "$_name.app" "$_zip" || return 1
[ -s "$_zip" ] || { err "压缩产物为空"; return 1; }
_trash "$_app"
step_ok "dist/mac-arm64/$_name.zip($(_hsize "$_zip"))"
fi
# stage 里剩下的(UI 副本、已搬空的平台目录)一次性挪走
for _left in "$GC_STAGE"/*; do
[ -e "$_left" ] || continue
_trash "$_left"
done
find "$GC_ROOT/dist" -name ".DS_Store" -delete >/dev/null 2>&1 || true
stamp_launcher_only
}
# 把 model/ 里的模型数据单独打包(与启动器分开分发)
pack_models() {
_zip="$GC_ROOT/dist/models-$VERSION.zip"
mkdir -p "$GC_ROOT/dist"
rm -f "$_zip"
say "打包模型数据"
( cd "$GC_ROOT" && zip -qrX "$_zip" model -x "*.DS_Store" "*/bin/*" "*/obj/*" "*.user" ) || return 1
step_ok "dist/models-$VERSION.zip($(_hsize "$_zip"))"
}
-108
View File
@@ -1,108 +0,0 @@
#!/bin/sh
# buildsh/lib/progress.sh —— 进度显示
#
# 终端:底部单行实时进度条 [####....] 编译Mac 45% 30% 1m20s
# 非终端(重定向 / CI / 日志):逐行打印步骤,不打 \r,不刷屏
#
# progress_init <总权重> <每步权重...>
# progress_step <步骤名>
# progress_tick <0-100> # 当前步骤完成度
# progress_done
#
# GC_NO_PROGRESS=1 可强制关闭进度条(但保留步骤行)
PROGRESS_TOTAL=1
PROGRESS_WEIGHTS=""
PROGRESS_IDX=0
PROGRESS_CUR=0
PROGRESS_STARTED=0
PROGRESS_TASK="准备"
_P_OVERALL=0
_P_ETA="--"
GC_PROGRESS_TTY=0
if [ -t 1 ] && [ -z "${GC_NO_PROGRESS:-}" ] && [ "${GC_QUIET:-0}" != 1 ]; then
GC_PROGRESS_TTY=1
fi
# 一次算出整体百分比 + 剩余时间(原来每帧要循环两遍、fork 三次 date)
_progress_refresh() {
_sum=0; _i=1
for _w in $PROGRESS_WEIGHTS; do
if [ "$_i" -lt "$PROGRESS_IDX" ]; then
_sum=$((_sum + _w))
elif [ "$_i" -eq "$PROGRESS_IDX" ]; then
_sum=$((_sum + _w * PROGRESS_CUR / 100))
fi
_i=$((_i + 1))
done
_P_OVERALL=$((_sum * 100 / PROGRESS_TOTAL))
[ "$_P_OVERALL" -gt 100 ] && _P_OVERALL=100
_t=$(( $(date +%s) - PROGRESS_STARTED ))
if [ "$_P_OVERALL" -le 3 ] || [ "$_t" -le 0 ]; then
_sec=240 # 前期按经验值粗估 4 分钟
else
_sec=$(( _t * (100 - _P_OVERALL) / _P_OVERALL ))
fi
if [ "$_sec" -ge 60 ]; then
_P_ETA="$((_sec / 60))m$((_sec % 60))s"
else
_P_ETA="${_sec}s"
fi
}
_progress_bar() {
_filled=$((_P_OVERALL * 20 / 100))
_bar=""; _i=0
while [ "$_i" -lt 20 ]; do
if [ "$_i" -lt "$_filled" ]; then _bar="$_bar#"; else _bar="$_bar."; fi
_i=$((_i + 1))
done
printf '%s' "$_bar"
}
progress_draw() {
[ "$GC_PROGRESS_TTY" = 1 ] || return 0
_progress_refresh
printf '\r\033[K[%s] %-16s %3d%% %3d%% %s' \
"$(_progress_bar)" "$PROGRESS_TASK" "$PROGRESS_CUR" "$_P_OVERALL" "$_P_ETA"
}
progress_init() {
PROGRESS_TOTAL=$1; shift
PROGRESS_WEIGHTS="$*"
PROGRESS_IDX=0
PROGRESS_CUR=0
PROGRESS_STARTED=$(date +%s)
PROGRESS_TASK="准备"
progress_draw
}
progress_step() {
PROGRESS_TASK="$1"
PROGRESS_CUR=0
PROGRESS_IDX=$((PROGRESS_IDX + 1))
if [ "$GC_PROGRESS_TTY" = 1 ]; then
progress_draw
else
# 非终端:一行一步,冒号后给个序号,日志里能看清阶段划分
[ "${GC_QUIET:-0}" = 1 ] && return 0
printf '==> [%d] %s\n' "$PROGRESS_IDX" "$1"
fi
}
progress_tick() {
# 非终端不需要刷新,直接返回(省掉每秒几次无用计算)
[ "$GC_PROGRESS_TTY" = 1 ] || return 0
PROGRESS_CUR=$1
progress_draw
}
progress_done() {
PROGRESS_CUR=100
if [ "$GC_PROGRESS_TTY" = 1 ]; then
progress_draw
printf '\n'
fi
}
-150
View File
@@ -1,150 +0,0 @@
#!/bin/sh
# buildsh/lib/publish.sh —— 环境预检 / 工具程序集缓存 / dotnet 发布
#
# 两个关键设计:
# 1. dt_tool:工具类程序(VersionStamp / PreviewGen / GC-SAVEDOG 签名)只 build 一次,
# 之后直接 dotnet <dll> 运行。原来每次 dotnet run 都要走一遍 MSBuild 评估
# (即便没有任何改动),一次构建里能省下好几秒和一屏还原输出。
# 2. _trash:大目录一律"挪进 build/trash"而不是递归删除。几百个文件的 rm -rf
# 既慢又不可逆,挪走更安全(下次构建开始时会整体移到 TMPDIR)。
# ---------------------------------------------------------------- 环境预检
need() { command -v "$1" >/dev/null 2>&1; }
# 一次性检查所有依赖,缺什么全部列出来立刻退出。
# 目的:不要跑到第 5 步(交叉编译)才发现没装 cmake,白白浪费前面几分钟。
preflight() {
_miss=""
_add() { _miss="$_miss
- $1($2)"; }
need dotnet || _add dotnet "安装 .NET 8 SDK:https://dot.net"
need zip || _add zip "Linux: apt install zip;macOS: 系统自带"
# Windows 交叉编译(非 Windows 主机)
if [ "$BUILD_WIN" = 1 ] && [ "$GC_HOST" != windows ]; then
need cmake || _add cmake "Linux: apt install cmake;macOS: brew install cmake"
need ninja || _add ninja "Linux: apt install ninja-build;macOS: brew install ninja"
need unzip || _add unzip "Linux: apt install unzip"
need curl || _add curl "Linux: apt install curl"
need x86_64-w64-mingw32-windres \
|| _add mingw-w64 "Linux: apt install g++-mingw-w64-x86-64-posix;macOS: brew install mingw-w64"
need wine || need wine64 \
|| _add wine "Linux: apt install wine;macOS: 见 buildsh/cross/build-ui-win-cross.sh 顶部说明"
fi
if [ -n "$_miss" ]; then
err "构建环境不完整,缺少:$_miss"
note "装好后重试。只需要 macOS 版可用:./build.sh build --targets=mac"
return 1
fi
}
# ---------------------------------------------------------------- 工具程序集
# 源码比产物新?用于决定是否重新构建工具
_any_newer() {
[ -n "$(find "$1" \( -name bin -o -name obj \) -prune -o \
\( -name '*.cs' -o -name '*.csproj' -o -name '*.props' \) \
-newer "$2" -print -quit 2>/dev/null)" ]
}
# dt_tool <缓存名> <项目相对路径> <程序集名> [参数...]
dt_tool() {
_tn="$1"; _tp="$2"; _ta="$3"; shift 3
_tout="$GC_ROOT/build/tools/$_tn"
_tdll="$_tout/$_ta.dll"
mkdir -p "$GC_ROOT/build/tools"
if [ ! -f "$_tdll" ] || _any_newer "$GC_ROOT/$(dirname "$_tp")" "$_tdll"; then
detail "构建工具 $_tn"
run_logged "$GC_ROOT/build/logs/tool-$_tn.log" "构建 $_tn" \
dotnet build "$GC_ROOT/$_tp" -c Release -o "$_tout" --nologo -v:q || return 1
fi
dotnet "$_tdll" "$@"
}
# ---------------------------------------------------------------- 目录清理
# 把目录挪进 build/trash(同分区 rename,几乎零成本),避免批量递归删除
_trash() {
[ -e "$1" ] || return 0
_tr="$GC_ROOT/build/trash"
mkdir -p "$_tr" 2>/dev/null || true
mv "$1" "$_tr/$(basename "$1")-$(date +%s)-$$" 2>/dev/null || rm -rf "$1"
return 0
}
# ---------------------------------------------------------------- 发布
# publish_rid <RID> <标签>
# 产物落 build/stage/<标签>/,后续打包直接就地改名 + 压缩,
# 不再 dist → 暂存目录 的整份复制(原来每个平台白白多搬 200MB)。
publish_rid() {
_rid="$1"; _label="$2"
_out="$GC_STAGE/$_label"
_trash "$_out"
mkdir -p "$_out"
run_logged "$GC_ROOT/build/logs/publish-$_label.log" "$_rid 启动器 " \
dotnet publish "$GC_ROOT/$APP_PROJ" \
-c Release -r "$_rid" --self-contained true \
-p:Version="$VERSION" -p:DebugType=none \
-p:PublishSingleFile=true \
-p:IncludeNativeLibrariesForSelfExtract=true \
-p:EnableCompressionInSingleFile=true \
-p:PublishTrimmed=false \
--nologo -v:m -o "$_out" || return 1
# 守护进程:单独的发布目录,只把单文件本体取出来放进包
# (同目录发布会把两套运行时文件混在一起,也没法并行)
if [ -n "${SAVEDOG_PROJ:-}" ] && [ -f "$GC_ROOT/$SAVEDOG_PROJ" ]; then
_sd="$GC_ROOT/build/tmp/savedog-$_label"
_trash "$_sd"
mkdir -p "$_sd"
# 裁剪 + 压缩单文件:70MB -> 14MB。JSON 全走源生成(GC-SAVEDOG/SavedogJson.cs),
# 新增类型忘注册只会在发布产物里炸,所以 update-test 会跑一次真实 apply 兜底。
run_logged "$GC_ROOT/build/logs/publish-savedog-$_label.log" "$_rid 守护进程 " \
dotnet publish "$GC_ROOT/$SAVEDOG_PROJ" \
-c Release -r "$_rid" --self-contained true \
-p:Version="$VERSION" -p:DebugType=none \
-p:PublishSingleFile=true \
-p:IncludeNativeLibrariesForSelfExtract=true \
-p:EnableCompressionInSingleFile=true \
-p:PublishTrimmed=true -p:TrimMode=full \
-p:JsonSerializerIsReflectionEnabledByDefault=false \
--nologo -v:m -o "$_sd" || return 1
for _f in "$_sd/GC-SAVEDOG" "$_sd/GC-SAVEDOG.exe"; do
[ -f "$_f" ] && cp "$_f" "$_out/"
done
_trash "$_sd"
fi
# 等高线课件(Avalonia WebView 通过可执行文件旁 courseware/ 加载)
if [ -d "$GC_ROOT/GC/src/Assets/courseware" ]; then
mkdir -p "$_out/courseware"
cp -R "$GC_ROOT/GC/src/Assets/courseware/." "$_out/courseware/"
fi
rm -rf "$_out/model" "$_out/examples"
step_ok "$_rid"
}
# _run_phase <预估秒数> <函数> [参数...]
# 在后台跑一个阶段,前台每秒刷新进度条;阶段退出码如实返回。
_run_phase() {
_rp_est="$1"; shift
( "$@" ) &
_rp_pid=$!
_rp_t0=$(date +%s)
while kill -0 "$_rp_pid" 2>/dev/null; do
_rp_p=$(( ($(date +%s) - _rp_t0) * 100 / _rp_est ))
[ "$_rp_p" -gt 96 ] && _rp_p=96
progress_tick "$_rp_p"
sleep 1
done
wait "$_rp_pid" || return 1
progress_tick 100
}
-211
View File
@@ -1,211 +0,0 @@
#!/usr/bin/env python3
"""核对「仓库清单 ↔ Release 资产」是否对得上。
为什么需要它:清单里的 sha256 是客户端验证下载包的唯一依据。一旦 Release 上的资产
和清单不是同一份(换过一次构建、上传了别的产物、tag 指到了旧提交),客户端会验签
失败或直接回滚 —— 用户看到的是「更新失败了」,而服务端一切正常。
检查项:
1. tag 指向的 version.json 里的 launcher.version 等于 tag 名;
2. 清单里带 sha256 的平台,Release 上有同名资产,且体积 / sha256 完全一致;
3. 清单里没有 sha256 的平台(本次没构建)不要求有资产,但会列出;
4. Release 上多出来的资产(清单里没有)单独提示;
5. 本地清单与 tag 上的清单是否字节一致。
只用标准库,Linux / macOS / Windows 上都能跑。
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import sys
import urllib.error
import urllib.request
DEFAULT_BASE = os.environ.get("GC_GITEA_URL", "https://git.xhmcl.com")
DEFAULT_REPO = os.environ.get("GC_GITEA_REPO", "Morris/GC")
def log(msg: str = "") -> None:
print(msg, flush=True)
def http_json(url: str, token: str | None) -> dict:
req = urllib.request.Request(url)
req.add_header("Accept", "application/json")
if token:
req.add_header("Authorization", "token " + token)
with urllib.request.urlopen(req, timeout=60) as resp:
return json.loads(resp.read().decode("utf-8"))
def download_sha256(url: str, token: str | None, dest: str) -> tuple[int, str]:
req = urllib.request.Request(url)
if token:
req.add_header("Authorization", "token " + token)
digest = hashlib.sha256()
size = 0
with urllib.request.urlopen(req, timeout=600) as resp, open(dest, "wb") as out:
while True:
chunk = resp.read(1 << 20)
if not chunk:
break
size += len(chunk)
digest.update(chunk)
out.write(chunk)
return size, digest.hexdigest()
def main() -> int:
parser = argparse.ArgumentParser(description="核对清单与 Release 资产")
parser.add_argument("--tag", required=True, help="要核对的 tag,例如 1.1.0")
parser.add_argument("--manifest", default="version.json", help="本地清单路径(用于对比)")
parser.add_argument("--base-url", default=DEFAULT_BASE)
parser.add_argument("--repo", default=DEFAULT_REPO)
parser.add_argument("--token", default=os.environ.get("GC_GITEA_TOKEN"))
parser.add_argument("--workdir", default=None, help="下载临时目录(默认系统临时目录)")
parser.add_argument("--skip-download", action="store_true",
help="只核对清单体积与资产列表,不下载算哈希")
parser.add_argument("--dump-manifest", default=None,
help="把 tag 上的清单原样写到这个路径(供 GC-SAVEDOG verify 验签)")
args = parser.parse_args()
tag = args.tag.strip()
if tag.startswith("v"):
tag = tag[1:]
api = f"{args.base_url}/api/v1/repos/{args.repo}"
workdir = args.workdir or os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "build", "release-verify")
workdir = os.path.abspath(workdir)
os.makedirs(workdir, exist_ok=True)
failures: list[str] = []
warnings: list[str] = []
# ---- 1. tag 上的清单 ----
try:
remote = http_json(f"{api}/raw/version.json?ref={tag}", args.token)
except urllib.error.HTTPError as exc:
log(f"!! 取不到 tag {tag} 的 version.json(HTTP {exc.code})")
return 1
if args.dump_manifest:
os.makedirs(os.path.dirname(os.path.abspath(args.dump_manifest)), exist_ok=True)
with open(args.dump_manifest, "w", encoding="utf-8") as fh:
json.dump(remote, fh, ensure_ascii=False, indent=2)
launcher = remote.get("launcher") or {}
remote_version = str(launcher.get("version") or "")
log(f"tag : {tag}")
log(f"清单版本 : {remote_version or '(空)'}")
if remote_version != tag:
failures.append(f"tag 指向的清单版本是 {remote_version!r},与 tag {tag} 不一致")
# 签名状态:交给 GC-SAVEDOG verify 判定(这里只提示有没有签名段)
if not remote.get("signature"):
failures.append("tag 上的清单没有签名段")
else:
log(f"清单签名 : {remote['signature'].get('keyId', '?')}")
# ---- 2. Release 与资产 ----
try:
release = http_json(f"{api}/releases/tags/{tag}", args.token)
except urllib.error.HTTPError as exc:
log(f"!! 取不到 Release {tag}(HTTP {exc.code})")
return 1
assets = {a["name"]: a for a in release.get("assets") or []}
log(f"Release : id={release.get('id')} prerelease={release.get('prerelease')}")
log(f"资产数量 : {len(assets)}")
packages = launcher.get("packages") or {}
declared: set[str] = set()
log("")
log(f"{'平台':<12} {'包':<32} {'结果'}")
log("-" * 78)
for rid, pkg in packages.items():
name = str(pkg.get("name") or "")
want_sha = str(pkg.get("sha256") or "")
want_size = int(pkg.get("size") or 0)
if not name:
warnings.append(f"{rid}: 清单条目没有 name")
continue
declared.add(name)
asset = assets.get(name)
if not want_sha:
log(f"{rid:<12} {name:<32} 未构建(清单无 sha256)")
if asset:
warnings.append(f"{rid}: 清单没记录哈希,但 Release 上有 {name}")
continue
if not asset:
log(f"{rid:<12} {name:<32} ✗ 资产缺失")
failures.append(f"{rid}: Release 上找不到 {name}")
continue
if int(asset.get("size") or 0) != want_size:
log(f"{rid:<12} {name:<32} ✗ 体积不符 {asset.get('size')} != {want_size}")
failures.append(f"{rid}: {name} 体积 {asset.get('size')},清单 {want_size}")
continue
if args.skip_download:
log(f"{rid:<12} {name:<32} ✓ 体积一致(未下载)")
continue
url = asset.get("browser_download_url") or f"{args.base_url}/{args.repo}/releases/download/{tag}/{name}"
dest = os.path.join(workdir, name)
try:
size, sha = download_sha256(url, args.token, dest)
os.remove(dest)
except Exception as exc: # noqa: BLE001 - 下载失败一律按失败上报
log(f"{rid:<12} {name:<32} ✗ 下载失败: {exc}")
failures.append(f"{rid}: 下载 {name} 失败: {exc}")
continue
if size != want_size or sha != want_sha:
log(f"{rid:<12} {name:<32} ✗ sha256 不符")
log(f" 期望 {want_sha}")
log(f" 实际 {sha}")
failures.append(f"{rid}: {name} sha256 与清单不符")
else:
log(f"{rid:<12} {name:<32} ✓ {size:,} B sha {sha[:16]}…")
extra = sorted(set(assets) - declared)
if extra:
warnings.append("Release 上有清单未声明的资产: " + ", ".join(extra))
# ---- 3. 本地清单对比 ----
if os.path.isfile(args.manifest):
with open(args.manifest, "rb") as fh:
local_raw = fh.read()
local = json.loads(local_raw.decode("utf-8"))
local_packages = (local.get("launcher") or {}).get("packages") or {}
if local_packages != packages:
warnings.append("本地清单的 packages 与 tag 上的不一致(本地可能是未发布的构建)")
else:
log("")
log("本地清单与 tag 上的 packages 一致")
# ---- 汇总 ----
log("")
for w in warnings:
log("警告: " + w)
if failures:
for f in failures:
log("失败: " + f)
log("")
log("结论: 不一致 —— 客户端会拒绝或回滚这次更新")
return 1
log("结论: 一致 —— 清单、tag、资产三者对得上")
return 0
if __name__ == "__main__":
sys.exit(main())
-37
View File
@@ -1,37 +0,0 @@
#!/bin/sh
# buildsh/release.sh —— 发布一致性核对
#
# ./build.sh release-verify # 核对当前版本号对应的 tag
# ./build.sh release-verify 1.1.0 # 核对指定 tag
# ./build.sh release-verify 1.1.0 --skip-download # 只看体积,不下载
#
# 检查的是「tag 指向的清单 / Release 上的资产 / 清单里的 sha256」三者是否互相对得上。
# 客户端的升级判断完全依赖这三者:任何一处错位,用户侧就是验签失败或安全回滚。
bs_verify_release() {
ROOT_DIR="$1"; shift
GC_ROOT="${GC_ROOT:-$ROOT_DIR}"; export GC_ROOT
TAG="${1:-$VERSION}"
if [ "$#" -gt 0 ]; then shift; fi
WORK="$ROOT_DIR/build/release-verify"
mkdir -p "$WORK"
say "核对 Release ${TAG}"
_rc=0
python3 "$ROOT_DIR/buildsh/lib/verify_release.py" \
--tag "$TAG" \
--manifest "$ROOT_DIR/version.json" \
--dump-manifest "$WORK/$TAG.json" \
"$@" || _rc=$?
[ "$_rc" -eq 0 ] || return "$_rc"
# 资产对得上还不够:清单本身必须是我签的,否则客户端一样会拒
say "校验 tag 清单签名"
if dt_tool savedog "$SAVEDOG_PROJ" GC-SAVEDOG verify --manifest "$WORK/$TAG.json"; then
step_ok "签名可信,可以发布 / 已经发布正确"
return 0
fi
err "签名校验未通过,客户端会拒绝这次更新"
return 1
}
-48
View File
@@ -1,48 +0,0 @@
#!/bin/sh
# buildsh/tools.sh —— 实用工具:模型、版本戳、打包、清理、运行、医生
bs_tools() {
ROOT_DIR="$1"; TASK="${2:-}"
GC_ROOT="${GC_ROOT:-$ROOT_DIR}"; export GC_ROOT
GC_STAGE="${GC_STAGE:-$ROOT_DIR/build/stage}"; export GC_STAGE
case "$TASK" in
models)
build_models ;;
stamp)
stamp_versions ;;
pack-models)
build_models; pack_models ;;
pack-launcher)
# 单独打包:数据源优先 build/stage,缺失时回落到 dist
mkdir -p "$GC_ROOT/build/logs"
pack_launcher ;;
run)
# 开发运行:进程内 Avalonia 界面;课件资源指向源码目录(发布包则由
# publish_rid 拷到可执行文件旁)。额外参数原样透传给程序。
export GC_COURSEWARE_DIR="$ROOT_DIR/GC/src/Assets/courseware"
say "启动 GC(Avalonia 界面)"
dotnet run --project "$APP_PROJ" -c Debug -- "$@" ;;
clean)
say "清理构建产物"
_trash "$ROOT_DIR/build"
_trash "$ROOT_DIR/dist"
find "$ROOT_DIR/src" -type d \( -name bin -o -name obj \) -prune -exec rm -rf {} + >/dev/null 2>&1 || true
step_ok "已清理" ;;
doctor)
dotnet --info | head -20 ;;
dist)
say "dist 产物"
_found=0
for _z in "$ROOT_DIR"/dist/*/*.zip; do
[ -f "$_z" ] || continue
_found=1
printf ' %6s %s\n' "$(_hsize "$_z")" "$(_rel "$_z")"
done
[ "$_found" = 1 ] || note "(暂无产物)" ;;
*)
err "未知工具:${TASK:-(空)}"
note "可用:models / stamp / pack-models / pack-launcher / run / clean / doctor / dist"
return 1 ;;
esac
}
-30
View File
@@ -1,30 +0,0 @@
{
"id": "contour-map",
"nameI18n": {
"zh-CN": "等高线地形图",
"en": "Contour Map"
},
"descriptionI18n": {
"zh-CN": "可旋转 3D 地形 + 等高切割/交线/投影/判坡四步动画,判读山峰、山脊、山谷、鞍部、陡崖五大典型地貌。",
"en": "Rotatable 3D terrain with a four-step animation of contour cutting, lines, projection and slope; identify five classic landforms."
},
"author": "Morris GC",
"tags": [
"geography",
"map",
"contour",
"terrain"
],
"assembly": "ContourMapModel.dll",
"type": "GC.ContourMap.ContourMapFactory",
"version": "1.2",
"chrome": {
"titleBar": "#0C1828",
"titleBorder": "#1B2740",
"titleText": "#EAF2FF",
"button": "#9FB4D4",
"frame": "#0A1524"
},
"build": "d18eb85c8d",
"updatedAt": "2026-11-21T10:55:36Z"
}
@@ -1,118 +0,0 @@
{
"zh-CN": {
"title": "如何使用 · 等高线地形与五大典型地貌",
"sections": [
{
"h": "开始使用(跟着做)",
"lines": [
"第 1 步:点右下角「开始实验」,在立体地形里观察水平切面下降、交线形成、垂直投影与疏密判坡四步动画。",
"第 2 步:在立体地形上按住鼠标拖动可旋转视角,滚轮缩放;这是可交互的 3D 地形。",
"第 3 步:点画布上方「五大典型地貌」标签(山峰/山脊/山谷/鞍部/陡崖),画面换成对应的专门地形并叠加完整等高线,观察各自的等高线特征。",
"第 4 步:点底部「俯视图 / 立体图」在等高线地图与 3D 地形间切换;鼠标悬停任意位置,底部显示该点海拔与地形部位。",
"第 5 步:点「上色 / 取消上色」对比分层设色与纯等高线;点「全屏」进入全屏演示。"
]
},
{
"h": "键盘快捷键",
"lines": [
"空格:播放 / 暂停实验。",
"数字 1 – 5:依次切换到山峰、山脊、山谷、鞍部、陡崖。"
]
},
{
"h": "四步实验流程",
"lines": [
"等高切割:一个水平面从山顶向下移动,与山体在同一海拔相交。",
"形成交线:每个水平切面留下一条闭合交线,多层交线共同描述山体起伏。",
"投影成图:各高度的交线沿垂线投影到同一平面,累积成完整等高线图。",
"疏密判坡:坡度着色叠加等高线,陡处线密、缓处线疏。"
]
},
{
"h": "五大典型地貌的判读",
"lines": [
"山峰:等高线闭合,数值由中心向四周递减(若向内降低则为洼地)。",
"山脊:等高线向海拔低处凸出(凸低为脊),脊线是分水线。",
"山谷:等高线向海拔高处凸出(凸高为谷),谷线是集水线,常发育河流。",
"鞍部:两座山峰之间相对低洼,俯视轮廓呈马鞍状收腰。",
"陡崖:等高线密集甚至重合,近乎垂直;n 条线重合时 (n−1)d ≤ ΔH < (n+1)d。"
]
},
{
"h": "等高线基础",
"lines": [
"同一条等高线上各点海拔相等;相邻等高线之间的高差叫等高距(本图 100 米)。",
"等高线越密坡越陡,越疏坡越缓。",
"每 5 条加粗一条叫计曲线,标注海拔便于读数。",
"海拔:某地高出海平面的垂直距离;相对高度:两点海拔之差。"
]
},
{
"h": "地图符号",
"lines": [
"分层设色按固定高程档位套固定色阶(深绿→浅绿→绿→浅黄→黄→浅褐→褐→白)。",
"山峰用 ▲ 加高程数字标注;河流用蓝色线沿谷底绘制;陡崖用红色锯齿线表示。",
"指北针在图幅右上,比例尺在左下,分层设色图例在右下,地形剖面图在底部。"
]
}
]
},
"en": {
"title": "How to use · Contour Lines & Five Landforms",
"sections": [
{
"h": "Getting started (follow along)",
"lines": [
"Step 1: press Start to watch the four-step animation — contour cutting, line formation, vertical projection and slope reading.",
"Step 2: drag with the mouse to rotate the 3D terrain, scroll to zoom; it is fully interactive.",
"Step 3: click a landform tab above the canvas (peak / ridge / valley / saddle / cliff) to load its dedicated terrain with its full contour pattern.",
"Step 4: toggle Top view / 3D view at the bottom; hover anywhere to read elevation and terrain feature.",
"Step 5: use Colour / No colour to compare hypsometric tint with pure contour lines; use Fullscreen for presentation."
]
},
{
"h": "Keyboard shortcuts",
"lines": [
"Space: play / pause the experiment.",
"Numbers 1 – 5: switch to peak, ridge, valley, saddle, cliff."
]
},
{
"h": "The four experiment steps",
"lines": [
"Contour cutting: a horizontal plane descends from the summit and intersects the mountain at one elevation.",
"Forming lines: each slice leaves a closed intersection line; stacked lines describe the relief.",
"Projection: intersection lines are projected vertically onto one plane, building the contour map.",
"Slope density: slope shading over contours — dense lines mean steep, sparse lines mean gentle."
]
},
{
"h": "Reading the five landforms",
"lines": [
"Peak: closed contours, values decrease outward (if they decrease inward it is a depression).",
"Ridge: contours bulge toward lower ground; a watershed line.",
"Valley: contours bulge toward higher ground; a drainage line, often a stream.",
"Saddle: low ground between two peaks, pinched like a saddle in plan view.",
"Cliff: contours crowd or overlap, nearly vertical; n overlapping lines: (n−1)d ≤ ΔH < (n+1)d."
]
},
{
"h": "Contour basics",
"lines": [
"All points on one contour share the same elevation; the gap between neighbours is the contour interval (100 m here).",
"Closer contours mean steeper slopes; wider spacing means gentler slopes.",
"Every 5th contour is bolded as an index contour and labelled with elevation.",
"Elevation is height above sea level; relative height is the difference between two elevations."
]
},
{
"h": "Map symbols",
"lines": [
"Hypsometric tint uses fixed colour bands (dark green → light green → green → pale yellow → yellow → light brown → brown → white).",
"Peaks are marked with ▲ plus elevation; rivers are blue lines along valleys; cliffs use a red saw-tooth line.",
"North arrow top-right, scale bar bottom-left, tint legend bottom-right, terrain profile along the bottom."
]
}
]
}
}
@@ -1,4 +0,0 @@
{
"app.title": "Contour Lines · Five Classic Landforms",
"app.subtitle": "Grade 7 · From 3D relief to contour maps: peaks, ridges, valleys, saddles and cliffs"
}
@@ -1,4 +0,0 @@
{
"app.title": "等高线地形 · 五大典型地貌判读",
"app.subtitle": "七年级上册 · 从立体地形到平面等高线,判读山峰/山脊/山谷/鞍部/陡崖"
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 65 KiB

-721
View File
@@ -1,721 +0,0 @@
using System;
using System.Collections.Generic;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Layout;
using Avalonia.Media;
namespace GC.ContourMap;
/// <summary>
/// 等高线模型界面(完整复刻 HTML 课件功能):
/// 顶部标题 + 全屏;左侧可交互 3D 画布;右侧实验流程/五大地貌/判读要点观察面板;
/// 底部播放控制、俯视切换、上色开关、实时读数;支持键盘 1-5 / 空格快捷键。
/// </summary>
public sealed class ContourPage
{
private static readonly Color CAppBg = Color.Parse("#0B1524");
private static readonly Color CPanel = Color.Parse("#101E31");
private static readonly Color CPanel2 = Color.Parse("#16263C");
private static readonly Color CLine = Color.Parse("#1E3350");
private static readonly Color CInk = Color.Parse("#EAF2FF");
private static readonly Color CInkDim = Color.Parse("#93A8C6");
private static readonly Color CInkFaint = Color.Parse("#6A80A0");
private static readonly Color CAccent = Color.Parse("#4D8CFF");
private static readonly Color CWarn = Color.Parse("#FFB454");
private static readonly Color CGood = Color.Parse("#5FD69B");
private readonly Dictionary<string, string> _texts;
private readonly Dictionary<LandformKind, TerrainField> _landformCache = new();
private TerrainField _experimentField;
private ContourView? _view;
private TextBlock? _readout;
private TextBlock? _featureText;
private TextBlock? _hintText;
private TextBlock? _playLabel;
private TextBlock? _observeHeading;
private TextBlock? _observeSummary;
private StackPanel? _featureList;
private TextBlock? _viewToggleLabel;
private readonly List<Border> _flowButtons = new();
private readonly List<Border> _landformButtons = new();
private Border? _playBtn;
private Border? _backBtn;
private Border? _colorBtn;
private TextBlock? _colorBtnText;
private ProgressBar? _progress;
private int _step = 0;
private LandformKind? _selectedLandform;
private bool _disposed;
private TopLevel? _topLevel;
private static readonly LandformKind[] LandformOrder =
{ LandformKind.Peak, LandformKind.Ridge, LandformKind.Valley, LandformKind.Saddle, LandformKind.Cliff };
public ContourPage(Dictionary<string, string> texts)
{
_texts = texts;
_experimentField = new TerrainField(TerrainKind.Mountain, 192);
}
private string T(string key) => _texts.TryGetValue(key, out var v) ? v : key;
private string T(string key, params object[] args)
{
var s = T(key);
try { return string.Format(System.Globalization.CultureInfo.InvariantCulture, s, args); }
catch { return s; }
}
private static SolidColorBrush B(Color c) => new(c);
private TerrainField GetLandformField(LandformKind kind)
{
if (!_landformCache.TryGetValue(kind, out var f))
{
f = new TerrainField(kind, 192);
_landformCache[kind] = f;
}
return f;
}
public Control Build()
{
var root = new Grid { Background = B(CAppBg) };
root.RowDefinitions.Add(new RowDefinition(GridLength.Auto));
root.RowDefinitions.Add(new RowDefinition(GridLength.Star));
root.RowDefinitions.Add(new RowDefinition(GridLength.Auto));
root.Children.Add(BuildHeader());
var body = new Grid { Margin = new Thickness(12, 8, 12, 6) };
body.ColumnDefinitions.Add(new ColumnDefinition(GridLength.Star));
body.ColumnDefinitions.Add(new ColumnDefinition(new GridLength(344)));
body.RowDefinitions.Add(new RowDefinition(GridLength.Auto));
body.RowDefinitions.Add(new RowDefinition(GridLength.Star));
_view = new ContourView(_experimentField, T);
_view.HoverChanged += OnHover;
_view.StepChanged += OnStepChanged;
_view.ProgressChanged += OnProgressChanged;
_view.PlaybackFinished += OnPlaybackFinished;
var canvasHolder = new Border
{
Background = B(Color.Parse("#08111E")),
BorderBrush = B(CLine),
BorderThickness = new Thickness(1),
CornerRadius = new CornerRadius(12),
ClipToBounds = true,
Child = _view
};
Grid.SetRow(canvasHolder, 1);
body.Children.Add(canvasHolder);
// ── 五大典型地貌标签(横向,像课件的选项卡)──
var tabs = new WrapPanel
{
Orientation = Orientation.Horizontal,
Margin = new Thickness(0, 0, 0, 8)
};
_backBtn = MakePillButton(T("btn.backExperiment"), CAccent);
_backBtn.IsVisible = false;
_backBtn.PointerPressed += (_, _) => BackToExperiment();
tabs.Children.Add(_backBtn);
foreach (var kind in LandformOrder)
{
var btn = MakeLandformButton(kind);
_landformButtons.Add(btn);
tabs.Children.Add(btn);
}
body.Children.Add(tabs);
var side = BuildSidePanel();
Grid.SetColumn(side, 1);
Grid.SetRow(side, 0);
Grid.SetRowSpan(side, 2);
body.Children.Add(side);
// 窄窗口(封面缩略图、小屏)隐藏右侧栏,画布优先;宽窗口才展示流程与观察面板
void ApplyResponsive(double width)
{
var narrow = width < 980;
side.IsVisible = !narrow;
body.ColumnDefinitions[1].Width = narrow ? new GridLength(0) : new GridLength(344);
}
root.SizeChanged += (_, e) => ApplyResponsive(e.NewSize.Width);
Grid.SetRow(body, 1);
root.Children.Add(body);
var footer = BuildFooter();
Grid.SetRow(footer, 2);
root.Children.Add(footer);
root.AttachedToVisualTree += (_, _) =>
{
_topLevel = TopLevel.GetTopLevel(root);
};
root.KeyDown += OnKeyDown;
root.Focusable = true;
return root;
}
/// <summary>窗口关闭时释放视图计时器,避免持有控件。</summary>
public void Dispose()
{
if (_disposed) return;
_disposed = true;
_view?.DisposeView();
}
private Control BuildHeader()
{
var title = new TextBlock
{
Text = T("app.title"),
Foreground = B(CInk),
FontSize = 18,
FontWeight = FontWeight.SemiBold
};
var sub = new TextBlock
{
Text = T("app.subtitle"),
Foreground = B(CInkDim),
FontSize = 11.5
};
var stack = new StackPanel { Spacing = 2 };
stack.Children.Add(title);
stack.Children.Add(sub);
var fsLabel = new TextBlock { Text = T("btn.fullscreen"), Foreground = B(CInk), FontSize = 11.5 };
var fsBtn = new Border
{
Background = B(CPanel2),
BorderBrush = B(CLine),
BorderThickness = new Thickness(1),
CornerRadius = new CornerRadius(8),
Padding = new Thickness(12, 6),
Cursor = new Avalonia.Input.Cursor(Avalonia.Input.StandardCursorType.Hand),
Child = fsLabel
};
fsBtn.PointerPressed += (_, _) => ToggleFullscreen(fsLabel);
var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") };
grid.Children.Add(stack);
Grid.SetColumn(fsBtn, 1);
grid.Children.Add(fsBtn);
return new Border
{
Background = B(CPanel),
BorderBrush = B(CLine),
BorderThickness = new Thickness(0, 0, 0, 1),
Padding = new Thickness(18, 11, 18, 12),
Child = grid
};
}
private Control BuildSidePanel()
{
var panel = new StackPanel { Spacing = 8, Margin = new Thickness(12, 0, 0, 0) };
// ── 实验流程四步 ──
panel.Children.Add(Section(T("flow.title")));
for (var i = 0; i < 4; i++)
{
var btn = MakeFlowButton(i);
_flowButtons.Add(btn);
panel.Children.Add(btn);
}
panel.Children.Add(Divider());
// ── 观察面板 ──
_observeHeading = new TextBlock
{
Text = T("observe.title"),
Foreground = B(CWarn),
FontSize = 12.5,
FontWeight = FontWeight.SemiBold
};
_observeSummary = new TextBlock
{
Text = T("observe.default"),
Foreground = B(CInkDim),
FontSize = 10.5,
TextWrapping = TextWrapping.Wrap,
LineHeight = 16
};
_featureList = new StackPanel { Spacing = 3 };
RenderObservation(null);
panel.Children.Add(_observeHeading);
panel.Children.Add(_observeSummary);
panel.Children.Add(_featureList);
// ── 判读要点 ──
panel.Children.Add(Section(T("side.rules")));
panel.Children.Add(Bullet(T("rule.interval")));
panel.Children.Add(Bullet(T("rule.dense")));
panel.Children.Add(Bullet(T("rule.index")));
panel.Children.Add(Bullet(T("rule.height")));
var scroll = new ScrollViewer
{
Content = new Border
{
Background = B(CPanel),
BorderBrush = B(CLine),
BorderThickness = new Thickness(1),
CornerRadius = new CornerRadius(12),
Padding = new Thickness(14, 12),
Child = panel
},
VerticalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto
};
return scroll;
}
private Border MakeFlowButton(int index)
{
var name = new TextBlock
{
Text = $"{index + 1}. {T("flow.step." + index)}",
Foreground = B(CInk),
FontSize = 12.5,
FontWeight = FontWeight.SemiBold
};
var desc = new TextBlock
{
Text = T("flow.desc." + index),
Foreground = B(CInkFaint),
FontSize = 11,
TextWrapping = TextWrapping.Wrap,
LineHeight = 15
};
var stack = new StackPanel { Spacing = 1 };
stack.Children.Add(name);
stack.Children.Add(desc);
var border = new Border
{
Background = B(CPanel2),
BorderBrush = B(CLine),
BorderThickness = new Thickness(1),
CornerRadius = new CornerRadius(8),
Padding = new Thickness(9, 6),
Cursor = new Avalonia.Input.Cursor(Avalonia.Input.StandardCursorType.Hand),
Child = stack,
Tag = index
};
border.PointerPressed += (_, _) =>
{
BackToExperiment();
_view?.SetStep((ExperimentStep)index);
UpdateFlowStyles();
};
return border;
}
private Border MakeLandformButton(LandformKind kind)
{
var key = kind.ToString().ToLowerInvariant();
var name = new TextBlock
{
Text = T("landform." + key),
Foreground = B(CInk),
FontSize = 12.5,
FontWeight = FontWeight.SemiBold
};
var sub = new TextBlock
{
Text = T("landform." + key + ".sub"),
Foreground = B(CInkFaint),
FontSize = 10.5,
VerticalAlignment = VerticalAlignment.Center
};
var stack = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 7 };
stack.Children.Add(name);
stack.Children.Add(sub);
var border = new Border
{
Background = B(CPanel2),
BorderBrush = B(CLine),
BorderThickness = new Thickness(1),
CornerRadius = new CornerRadius(18),
Padding = new Thickness(14, 7),
Margin = new Thickness(0, 0, 8, 4),
Cursor = new Avalonia.Input.Cursor(Avalonia.Input.StandardCursorType.Hand),
Child = stack,
Tag = kind
};
border.PointerPressed += (_, _) => SelectLandform(kind);
return border;
}
private void SelectLandform(LandformKind kind)
{
_selectedLandform = kind;
_view?.Pause();
_view?.SetField(GetLandformField(kind));
_view?.SetMode(ViewMode.Perspective);
_view?.ShowContourPattern(); // 地貌专题先看完整的等高线形态
UpdateLandformStyles();
UpdateViewToggleLabel();
var key = kind.ToString().ToLowerInvariant();
if (_observeHeading != null) _observeHeading.Text = T("landform." + key) + " · " + T("landform." + key + ".sub");
if (_observeSummary != null) _observeSummary.Text = T("landform." + key + ".summary");
RenderFeatureList(key);
if (_backBtn != null) _backBtn.IsVisible = true;
if (_hintText != null) _hintText.Text = T("landform." + key + ".hint");
SetPlayLabel(T("btn.replay"));
}
private void BackToExperiment()
{
if (_selectedLandform == null) return;
_selectedLandform = null;
_view?.SetField(_experimentField);
_view?.SetMode(ViewMode.Perspective);
_view?.Reset();
UpdateLandformStyles();
UpdateViewToggleLabel();
RenderObservation(null);
if (_backBtn != null) _backBtn.IsVisible = false;
if (_hintText != null) _hintText.Text = T("hint.play");
SetPlayLabel(T("btn.play"));
}
private void RenderObservation(LandformKind? kind)
{
if (_observeHeading == null || _observeSummary == null || _featureList == null) return;
if (kind == null)
{
_observeHeading.Text = T("observe.title");
_observeSummary.Text = T("observe.default");
_featureList.Children.Clear();
_featureList.Children.Add(Bullet(T("observe.default.f1")));
_featureList.Children.Add(Bullet(T("observe.default.f2")));
}
else
{
var key = kind.Value.ToString().ToLowerInvariant();
_observeHeading.Text = T("landform." + key) + " · " + T("landform." + key + ".sub");
_observeSummary.Text = T("landform." + key + ".summary");
RenderFeatureList(key);
}
}
private void RenderFeatureList(string key)
{
if (_featureList == null) return;
_featureList.Children.Clear();
for (var i = 1; i <= 3; i++)
{
var k = $"landform.{key}.f{i}";
if (_texts.ContainsKey(k)) _featureList.Children.Add(Bullet(T(k)));
}
}
private Control BuildFooter()
{
// 播放 / 重置
_playLabel = new TextBlock { Text = T("btn.play"), Foreground = B(Colors.White), FontSize = 11.5, FontWeight = FontWeight.SemiBold };
_playBtn = new Border
{
Background = B(CAccent),
CornerRadius = new CornerRadius(8),
Padding = new Thickness(14, 7),
Cursor = new Avalonia.Input.Cursor(Avalonia.Input.StandardCursorType.Hand),
Child = _playLabel
};
_playBtn.PointerPressed += (_, _) => TogglePlay();
var resetBtn = MakePillButton(T("btn.reset"), Color.Parse("#2A3B55"));
resetBtn.PointerPressed += (_, _) =>
{
BackToExperiment();
_view?.Reset();
if (_progress != null) _progress.Value = 0;
if (_hintText != null) _hintText.Text = T("hint.play");
SetPlayLabel(T("btn.play"));
};
// 俯视 / 立体切换
_viewToggleLabel = new TextBlock { Text = T("btn.viewTop"), Foreground = B(CInk), FontSize = 11.5 };
var viewBtn = new Border
{
Background = B(CPanel2),
BorderBrush = B(CLine),
BorderThickness = new Thickness(1),
CornerRadius = new CornerRadius(8),
Padding = new Thickness(11, 6),
Cursor = new Avalonia.Input.Cursor(Avalonia.Input.StandardCursorType.Hand),
Child = _viewToggleLabel
};
viewBtn.PointerPressed += (_, _) =>
{
_view?.ToggleMode();
UpdateViewToggleLabel();
};
// 上色开关
_colorBtnText = new TextBlock { Text = T("btn.colorOn"), Foreground = B(Colors.White), FontSize = 11.5 };
_colorBtn = new Border
{
Background = B(CAccent),
CornerRadius = new CornerRadius(8),
Padding = new Thickness(11, 6),
Cursor = new Avalonia.Input.Cursor(Avalonia.Input.StandardCursorType.Hand),
Child = _colorBtnText
};
_colorBtn.PointerPressed += (_, _) => ToggleColor();
var controls = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8 };
controls.Children.Add(_playBtn);
controls.Children.Add(resetBtn);
controls.Children.Add(viewBtn);
controls.Children.Add(_colorBtn);
_progress = new ProgressBar
{
Minimum = 0,
Maximum = 100,
Value = 0,
Height = 4,
VerticalAlignment = VerticalAlignment.Center,
Foreground = B(CAccent),
Background = B(Color.Parse("#1E3350"))
};
_hintText = new TextBlock { Text = T("hint.play"), Foreground = B(CInkDim), FontSize = 11.5 };
_readout = new TextBlock { Text = T("footer.hint"), Foreground = B(CInk), FontSize = 11.5 };
_featureText = new TextBlock
{
Text = "",
Foreground = B(CGood),
FontSize = 11.5,
FontWeight = FontWeight.SemiBold,
HorizontalAlignment = HorizontalAlignment.Right
};
var info = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") };
info.Children.Add(_readout);
Grid.SetColumn(_featureText, 1);
info.Children.Add(_featureText);
var leftStack = new StackPanel { Spacing = 4, VerticalAlignment = VerticalAlignment.Center };
leftStack.Children.Add(_hintText);
leftStack.Children.Add(info);
var progStack = new StackPanel { Spacing = 6, VerticalAlignment = VerticalAlignment.Center };
progStack.Children.Add(leftStack);
progStack.Children.Add(_progress);
var row = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") };
row.Children.Add(progStack);
Grid.SetColumn(controls, 1);
row.Children.Add(controls);
return new Border
{
Background = B(CPanel),
BorderBrush = B(CLine),
BorderThickness = new Thickness(0, 1, 0, 0),
Padding = new Thickness(16, 9),
Child = row
};
}
private void TogglePlay()
{
if (_view == null) return;
if (_selectedLandform != null) BackToExperiment();
_view.TogglePlay();
SetPlayLabel(_view.IsPlaying ? T("btn.pause") : T("btn.play"));
if (_hintText != null)
_hintText.Text = _view.IsPlaying ? T("hint.playing") : T("hint.paused");
}
private void ToggleColor()
{
if (_view == null) return;
_view.Colored = !_view.Colored;
if (_colorBtn != null) _colorBtn.Background = B(_view.Colored ? CAccent : Color.Parse("#2A3B55"));
if (_colorBtnText != null) _colorBtnText.Text = _view.Colored ? T("btn.colorOn") : T("btn.color");
}
private void SetPlayLabel(string text) { if (_playLabel != null) _playLabel.Text = text; }
private void UpdateViewToggleLabel()
{
if (_viewToggleLabel == null || _view == null) return;
_viewToggleLabel.Text = _view.Mode == ViewMode.Top ? T("btn.view3d") : T("btn.viewTop");
}
private void UpdateFlowStyles()
{
for (var i = 0; i < _flowButtons.Count; i++)
{
var b = _flowButtons[i];
var active = i == _step && _selectedLandform == null;
var done = i < _step && _selectedLandform == null;
StylePill(b, active ? CAccent : done ? Color.Parse("#1C3A5E") : CPanel2,
active ? Colors.White : done ? CGood : CInkDim);
}
}
private void UpdateLandformStyles()
{
for (var i = 0; i < _landformButtons.Count; i++)
{
var b = _landformButtons[i];
var kind = LandformOrder[i];
var active = _selectedLandform == kind;
StylePill(b, active ? CAccent : CPanel2, active ? Colors.White : CInkDim);
}
}
private static void StylePill(Border b, Color bg, Color fg)
{
b.Background = B(bg);
if (b.Child is TextBlock tb) tb.Foreground = B(fg);
else if (b.Child is StackPanel sp)
foreach (var c in sp.Children)
if (c is TextBlock t) t.Foreground = B(fg);
}
private void OnStepChanged(ExperimentStep step)
{
_step = (int)step;
UpdateFlowStyles();
if (_selectedLandform == null && _observeSummary != null)
_observeSummary.Text = T("flow.desc." + _step);
}
private void OnProgressChanged(ExperimentStep step, double value)
=> _progress?.Value = value * 100;
private void OnPlaybackFinished()
{
SetPlayLabel(T("btn.replay"));
if (_hintText != null) _hintText.Text = T("hint.done");
}
private void OnHover(double u, double v, float height, TerrainFeature feature)
{
if (_readout == null || _featureText == null) return;
var field = _view?.Field ?? _experimentField;
var relative = height - field.MinHeight;
_readout.Text = T("footer.readout", (int)height, (int)relative);
_featureText.Text = FeatureName(feature);
_featureText.Foreground = B(feature switch
{
TerrainFeature.Peak => Color.Parse("#FFD166"),
TerrainFeature.Cliff => Color.Parse("#FF7B7B"),
TerrainFeature.Saddle => Color.Parse("#C08CFF"),
TerrainFeature.Ridge => Color.Parse("#5FD69B"),
TerrainFeature.Valley => Color.Parse("#5BC8FF"),
_ => CInkDim
});
}
private string FeatureName(TerrainFeature f) => f switch
{
TerrainFeature.Peak => T("feature.peak"),
TerrainFeature.Ridge => T("feature.ridge"),
TerrainFeature.Valley => T("feature.valley"),
TerrainFeature.Saddle => T("feature.saddle"),
TerrainFeature.Cliff => T("feature.cliff"),
TerrainFeature.Slope => T("feature.slope"),
_ => ""
};
private void OnKeyDown(object? sender, KeyEventArgs e)
{
// 空格:播放/暂停
if (e.Key == Key.Space)
{
e.Handled = true;
TogglePlay();
return;
}
// 1-5:切换五大地貌
var idx = -1;
switch (e.Key)
{
case Key.D1: case Key.NumPad1: idx = 0; break;
case Key.D2: case Key.NumPad2: idx = 1; break;
case Key.D3: case Key.NumPad3: idx = 2; break;
case Key.D4: case Key.NumPad4: idx = 3; break;
case Key.D5: case Key.NumPad5: idx = 4; break;
}
if (idx >= 0 && idx < LandformOrder.Length)
{
e.Handled = true;
SelectLandform(LandformOrder[idx]);
}
}
private void ToggleFullscreen(TextBlock label)
{
if (_topLevel is not Window window) return;
if (window.WindowState == WindowState.FullScreen)
{
window.WindowState = WindowState.Normal;
label.Text = T("btn.fullscreen");
}
else
{
window.WindowState = WindowState.FullScreen;
label.Text = T("btn.exitFullscreen");
}
}
// ── 控件工厂
private static TextBlock Section(string text) => new()
{
Text = text,
Foreground = BConst(CInk),
FontSize = 12.5,
FontWeight = FontWeight.SemiBold,
Margin = new Thickness(0, 2, 0, 2)
};
private static Border Divider() => new()
{
Height = 1,
Background = BConst(CLine),
Margin = new Thickness(0, 4, 0, 2)
};
private static TextBlock Bullet(string text) => new()
{
Text = "• " + text,
Foreground = BConst(CInkDim),
FontSize = 11.5,
TextWrapping = TextWrapping.Wrap,
LineHeight = 17
};
private Border MakePillButton(string label, Color bg)
{
var tb = new TextBlock { Text = label, Foreground = B(Colors.White), FontSize = 11.5, HorizontalAlignment = HorizontalAlignment.Center };
return new Border
{
Background = B(bg),
CornerRadius = new CornerRadius(8),
Padding = new Thickness(11, 6),
Cursor = new Avalonia.Input.Cursor(Avalonia.Input.StandardCursorType.Hand),
Child = tb
};
}
private static SolidColorBrush BConst(Color c) => new(c);
}
File diff suppressed because it is too large. Load diff
-225
View File
@@ -1,225 +0,0 @@
using System.Collections.Generic;
namespace GC.ContourMap;
/// <summary>内置全量文案兜底:没有语言包也能完整显示(复刻 HTML 课件全部文案)。</summary>
internal static class DefaultTexts
{
public static readonly Dictionary<string, string> Zh = new()
{
// 标题
["app.title"] = "等高线地形 · 五大典型地貌判读",
["app.subtitle"] = "七年级上册 · 从立体地形到平面等高线,判读山峰/山脊/山谷/鞍部/陡崖",
// 实验流程四步
["flow.title"] = "实验流程",
["flow.step.0"] = "等高切割",
["flow.step.1"] = "形成交线",
["flow.step.2"] = "投影成图",
["flow.step.3"] = "疏密判坡",
["flow.desc.0"] = "观察水平面与山体在同一海拔相交,形成连续闭合线。",
["flow.desc.1"] = "每个水平切面都会留下同高交线,多层交线共同描述山体起伏。",
["flow.desc.2"] = "把各高度交线垂直投影到同一平面,得到完整等高线地形图。",
["flow.desc.3"] = "等高线越密,坡度越陡;等高线越疏,坡度越缓。",
// 观察面板
["observe.title"] = "实验演示",
["observe.default"] = "点击开始实验,在立体地形中观察等高切割与交线形成,再通过四步图解理解投影与判坡。",
["observe.features"] = "判读要点",
["observe.default.f1"] = "同一条等高线上海拔相等",
["observe.default.f2"] = "相邻等高线高差保持一致",
// 五大典型地貌
["side.landforms"] = "五大典型地貌",
["landform.peak"] = "山峰",
["landform.ridge"] = "山脊",
["landform.valley"] = "山谷",
["landform.saddle"] = "鞍部",
["landform.cliff"] = "陡崖",
["landform.peak.sub"] = "闭合等高线",
["landform.ridge.sub"] = "凸低为脊",
["landform.valley.sub"] = "凸高为谷",
["landform.saddle.sub"] = "两峰之间",
["landform.cliff.sub"] = "密集或重合",
["landform.peak.summary"] = "山峰四周较低、中心突起;等高线闭合成环,海拔数值由外向内逐渐升高。",
["landform.ridge.summary"] = "等高线弯曲部分向海拔低处凸出,脊线常成为两侧水系的分水岭。",
["landform.valley.summary"] = "等高线弯曲部分向海拔高处凸出,谷底低洼并容易汇水形成河流。",
["landform.saddle.summary"] = "鞍部位于相邻两座山峰之间,是沿山脊方向相对低洼的过渡地带。",
["landform.cliff.summary"] = "陡崖坡面近直立,不同高程的等高线会高度密集,局部可投影到同一位置而重合。",
["landform.peak.f1"] = "中心海拔高、四周海拔低",
["landform.peak.f2"] = "闭合线越向内,数值越大",
["landform.peak.f3"] = "若数值向内降低,则应判为洼地",
["landform.ridge.f1"] = "等高线凸向低值方向",
["landform.ridge.f2"] = "脊线由高处向低处延伸",
["landform.ridge.f3"] = "雨水沿脊线两侧分流",
["landform.valley.f1"] = "等高线凸向高值方向",
["landform.valley.f2"] = "V 形尖端指向上游高处",
["landform.valley.f3"] = "谷底常发育河流",
["landform.saddle.f1"] = "两组闭合等高线相邻",
["landform.saddle.f2"] = "中部线条收窄,形似马鞍",
["landform.saddle.f3"] = "常是翻越山岭的低垭口",
["landform.cliff.f1"] = "密集表示陡坡,重合才是陡崖特征",
["landform.cliff.f2"] = "单位水平距离内高差很大",
["landform.cliff.f3"] = "n 条线重合时:(n−1)d ≤ ΔH < (n+1)d",
["landform.peak.hint"] = "山峰:闭合曲线,数值向中心升高",
["landform.ridge.hint"] = "山脊:等高线向低处凸出,凸低为脊",
["landform.valley.hint"] = "山谷:等高线向高处凸出,凸高为谷",
["landform.saddle.hint"] = "鞍部:两峰之间相对低洼,俯视轮廓呈收腰形",
["landform.cliff.hint"] = "陡崖:等高线密集或重合,坡度极陡",
// 按钮
["btn.play"] = "开始实验",
["btn.pause"] = "暂停实验",
["btn.replay"] = "重新实验",
["btn.reset"] = "重置",
["btn.view3d"] = "立体图",
["btn.viewTop"] = "俯视图",
["btn.color"] = "上色",
["btn.colorOn"] = "取消上色",
["btn.fullscreen"] = "全屏",
["btn.exitFullscreen"] = "退出全屏",
["btn.backExperiment"] = "返回实验",
// 侧栏判读要点(通用地形)
["side.features"] = "五种地形部位",
["feature.peak"] = "山峰",
["feature.peakDesc"] = "等高线闭合,数值由中心向四周递减。",
["feature.ridge"] = "山脊",
["feature.ridgeDesc"] = "等高线凸向低处,脊线是分水线。",
["feature.valley"] = "山谷",
["feature.valleyDesc"] = "等高线凸向高处,谷线是集水线,常发育河流。",
["feature.saddle"] = "鞍部",
["feature.saddleDesc"] = "两个山峰之间的低地,形如马鞍。",
["feature.cliff"] = "陡崖",
["feature.cliffDesc"] = "等高线重叠或非常密集,近乎垂直。",
["feature.slope"] = "坡面",
// 判读规则
["side.rules"] = "判读要点",
["rule.interval"] = "等高距:相邻两条等高线的高度差,本图 100 米。",
["rule.dense"] = "等高线越密坡越陡,越疏坡越缓。",
["rule.index"] = "每 5 条加粗一条计曲线,标注海拔便于读数。",
["rule.height"] = "海拔:某地高出海平面的垂直距离;相对高度:两点海拔之差。",
// 底部读数 / 图例
["footer.hint"] = "拖动立体地形旋转、滚轮缩放;鼠标悬停可查看该点海拔与地形部位",
["footer.readout"] = "海拔 {0} m 相对高度 {1} m",
["legend.title"] = "分层设色",
["profile.title"] = "地形剖面图",
["slope.gentle"] = "缓坡(线疏)",
["slope.steep"] = "陡坡(线密)",
["hint.play"] = "点击“开始实验”,观察等高切割与交线形成",
["hint.playing"] = "实验播放中",
["hint.paused"] = "实验已暂停 · 点击继续恢复播放",
["hint.done"] = "实验流程播放完成 · 可重新实验或选择典型地貌观察"
};
public static readonly Dictionary<string, string> En = new()
{
["app.title"] = "Contour Lines · Five Classic Landforms",
["app.subtitle"] = "Grade 7 · From 3D relief to contour maps: peaks, ridges, valleys, saddles and cliffs",
["flow.title"] = "Experiment flow",
["flow.step.0"] = "Contour cutting",
["flow.step.1"] = "Forming lines",
["flow.step.2"] = "Projection",
["flow.step.3"] = "Slope density",
["flow.desc.0"] = "Watch a horizontal plane intersect the mountain at one elevation, forming closed lines.",
["flow.desc.1"] = "Each horizontal slice leaves an equal-height line; stacked lines describe the relief.",
["flow.desc.2"] = "Project every intersection line vertically onto one plane to build the contour map.",
["flow.desc.3"] = "Contours closer together mean a steeper slope; wider apart mean a gentler one.",
["observe.title"] = "Experiment demo",
["observe.default"] = "Press play to watch contour cutting and line formation, then use the four steps to learn projection and slope reading.",
["observe.features"] = "Key points",
["observe.default.f1"] = "All points on one contour share the same elevation",
["observe.default.f2"] = "Neighbouring contours keep a constant height interval",
["side.landforms"] = "Five classic landforms",
["landform.peak"] = "Peak",
["landform.ridge"] = "Ridge",
["landform.valley"] = "Valley",
["landform.saddle"] = "Saddle",
["landform.cliff"] = "Cliff",
["landform.peak.sub"] = "Closed contours",
["landform.ridge.sub"] = "Bulges toward low ground",
["landform.valley.sub"] = "Bulges toward high ground",
["landform.saddle.sub"] = "Between two peaks",
["landform.cliff.sub"] = "Dense or overlapping",
["landform.peak.summary"] = "A peak rises in the centre with lower ground around it; contours close into rings and values increase inward.",
["landform.ridge.summary"] = "Contours bulge toward lower ground; a ridge line often divides two drainage systems.",
["landform.valley.summary"] = "Contours bulge toward higher ground; valleys are low and collect water into streams.",
["landform.saddle.summary"] = "A saddle lies between two adjacent peaks, a relatively low pass along the ridge.",
["landform.cliff.summary"] = "A cliff face is nearly vertical, so contours crowd tightly or even overlap.",
["landform.peak.f1"] = "High centre, low surroundings",
["landform.peak.f2"] = "Closed lines grow in value inward",
["landform.peak.f3"] = "If values drop inward, it is a depression",
["landform.ridge.f1"] = "Contours bulge toward lower values",
["landform.ridge.f2"] = "Ridge line runs from high to low",
["landform.ridge.f3"] = "Rain drains to either side of the ridge",
["landform.valley.f1"] = "Contours bulge toward higher values",
["landform.valley.f2"] = "V tip points upstream to high ground",
["landform.valley.f3"] = "Streams often form along the valley floor",
["landform.saddle.f1"] = "Two neighbouring closed contour groups",
["landform.saddle.f2"] = "Contours pinch in the middle like a saddle",
["landform.saddle.f3"] = "Often a low mountain pass",
["landform.cliff.f1"] = "Dense means steep; overlap means cliff",
["landform.cliff.f2"] = "Large elevation change over a short distance",
["landform.cliff.f3"] = "n overlapping lines: (n−1)d ≤ ΔH < (n+1)d",
["landform.peak.hint"] = "Peak: closed curves, values rise toward the centre",
["landform.ridge.hint"] = "Ridge: contours bulge toward low ground",
["landform.valley.hint"] = "Valley: contours bulge toward high ground",
["landform.saddle.hint"] = "Saddle: low ground between two peaks",
["landform.cliff.hint"] = "Cliff: contours dense or overlapping, very steep",
["btn.play"] = "Start experiment",
["btn.pause"] = "Pause experiment",
["btn.replay"] = "Replay experiment",
["btn.reset"] = "Reset",
["btn.view3d"] = "3D view",
["btn.viewTop"] = "Top view",
["btn.color"] = "Colour",
["btn.colorOn"] = "No colour",
["btn.fullscreen"] = "Fullscreen",
["btn.exitFullscreen"] = "Exit fullscreen",
["btn.backExperiment"] = "Back to experiment",
["side.features"] = "Five terrain features",
["feature.peak"] = "Peak",
["feature.peakDesc"] = "Closed contours; values decrease outward from the centre.",
["feature.ridge"] = "Ridge",
["feature.ridgeDesc"] = "Contours bulge toward lower ground; a watershed line.",
["feature.valley"] = "Valley",
["feature.valleyDesc"] = "Contours bulge toward higher ground; a drainage line, often a stream.",
["feature.saddle"] = "Saddle",
["feature.saddleDesc"] = "Low ground between two peaks, shaped like a saddle.",
["feature.cliff"] = "Cliff",
["feature.cliffDesc"] = "Contours overlap or crowd tightly — nearly vertical.",
["feature.slope"] = "Slope",
["side.rules"] = "Key rules",
["rule.interval"] = "Contour interval: height gap between neighbours (100 m here).",
["rule.dense"] = "Closer contours = steeper slope; wider spacing = gentler.",
["rule.index"] = "Every 5th contour is bolded and labelled as an index contour.",
["rule.height"] = "Elevation above sea level; relative height is the difference of two elevations.",
["footer.hint"] = "Drag the 3D terrain to rotate, scroll to zoom; hover to read elevation and terrain feature",
["footer.readout"] = "Elevation {0} m Relative height {1} m",
["legend.title"] = "Hypsometric tint",
["profile.title"] = "Terrain profile",
["slope.gentle"] = "Gentle (sparse lines)",
["slope.steep"] = "Steep (dense lines)",
["hint.play"] = "Press start to watch contour cutting and line formation",
["hint.playing"] = "Experiment playing",
["hint.paused"] = "Experiment paused · press to resume",
["hint.done"] = "Experiment finished · replay or choose a landform"
};
}
@@ -1,30 +0,0 @@
{
"id": "earth-geography",
"nameI18n": {
"zh-CN": "地球地理",
"en": "Earth Geography"
},
"descriptionI18n": {
"zh-CN": "五带划分、七大洲四大洋轮廓、六大板块与洲界,纯线稿教学图。",
"en": "Climate zones, continent/ocean outlines, plates and borders — clean line art."
},
"assembly": "EarthGeographyModel.dll",
"type": "GC.EarthModels.GeographyModelFactory",
"author": "Morris GC",
"tags": [
"geography",
"earth",
"atlas"
],
"dataDir": "earth-geography.model",
"version": "1.9",
"chrome": {
"titleBar": "#0C1828",
"titleBorder": "#1B2740",
"titleText": "#EAF2FF",
"button": "#9FB4D4",
"frame": "#0A1524"
},
"build": "cc68b8863b",
"updatedAt": "2026-11-21T10:55:36Z"
}
@@ -1,37 +0,0 @@
{
"schemaVersion": 1,
"id": "scale-calculator",
"name": "Scale Calculator",
"nameI18n": {
"zh-CN": "比例尺计算器",
"en": "Scale Calculator"
},
"author": "Morris GC",
"description": "把比例尺变成可以拖、可以量的可视化标尺",
"descriptionI18n": {
"zh-CN": "三种求解模式、图上/实地双条对比、线段式比例尺自动换挡、比例尺光谱、真实地标实地尺与练习闯关。",
"en": "Three solve modes, dual map/real bars, auto-ranging graphic scale, scale spectrum, real-world landmarks and practice quizzes."
},
"tags": [
"geography",
"map",
"scale",
"calculator"
],
"entry": "scales.json",
"license": "MIT",
"assembly": "ScaleCalculatorModel.dll",
"type": "GC.ScaleCalculator.ScaleCalculatorFactory",
"preview": "preview.png",
"apiVersion": 1,
"version": "1.6",
"chrome": {
"titleBar": "#FFFFFF",
"titleBorder": "#E3E8F3",
"titleText": "#111A2E",
"button": "#5B6A86",
"frame": "#F4F6FB"
},
"build": "105653737d",
"updatedAt": "2026-11-21T10:55:36Z"
}
-101
View File
@@ -1,101 +0,0 @@
{
"schema": 1,
"generated": "2026-11-19T10:20:00Z",
"repository": "https://git.xhmcl.com/Morris/GC",
"branch": "main",
"modelDir": "model",
"launcher": {
"version": "1.1.1",
"revision": "",
"packages": {
"win-x64": {
"path": "dist/win-amd64/GCL-1.1.1-win-amd64.zip",
"dir": "dist/win-amd64",
"name": "GCL-1.1.1-win-amd64.zip",
"url": "https://git.xhmcl.com/Morris/GC/releases/download/1.1.1/GCL-1.1.1-win-amd64.zip",
"sha256": "a03532606121280a1553ea73e56d6f9e8cc6cd9eefaf49f8c62857733199c10f",
"size": 74993562
},
"win-arm64": {
"path": "dist/win-arm64/GCL-1.1.1-win-arm64.zip",
"dir": "dist/win-arm64",
"name": "GCL-1.1.1-win-arm64.zip",
"url": "https://git.xhmcl.com/Morris/GC/releases/download/1.1.1/GCL-1.1.1-win-arm64.zip",
"sha256": "0cd3e045fbc2415bb170e545bb720841eb4c5ebc01a98e03105618a2b7bace46",
"size": 72535103
},
"osx-arm64": {
"path": "dist/mac-arm64/GCL-1.1.1-mac-arm64.zip",
"dir": "dist/mac-arm64",
"name": "GCL-1.1.1-mac-arm64.zip",
"url": "https://git.xhmcl.com/Morris/GC/releases/download/1.1.1/GCL-1.1.1-mac-arm64.zip"
},
"osx-x64": {
"path": "dist/mac-x64/GCL-1.1.1-mac-x64.zip",
"dir": "dist/mac-x64",
"name": "GCL-1.1.1-mac-x64.zip",
"url": "https://git.xhmcl.com/Morris/GC/releases/download/1.1.1/GCL-1.1.1-mac-x64.zip"
},
"linux-arm64": {
"path": "dist/linux-arm64/GCL-1.1.1-linux-arm64.zip",
"dir": "dist/linux-arm64",
"name": "GCL-1.1.1-linux-arm64.zip",
"url": "https://git.xhmcl.com/Morris/GC/releases/download/1.1.1/GCL-1.1.1-linux-arm64.zip"
}
}
},
"models": [
{
"id": "contour-map",
"version": "1.1",
"build": "773ab2161d",
"manifestSha256": "ac3231d55175757b4c477ad6a3c398c041db9511061f0c650d2c10efca881103",
"filesSha256": "a6bdf9b4273aabee50c3c94ceab4d0abee15f0df1af90c58bdbb796e0d2d5699",
"files": 5,
"dir": "model/contour-map"
},
{
"id": "earth-geography",
"version": "1.9",
"build": "cc68b8863b",
"manifestSha256": "f69ceb758c643701480af441da26dfa64e190c9e583073deba211bac3e2a6e1a",
"filesSha256": "c018ba481831e23d3183a38ac47251f19754c7464baa5d85b47cea7a49fcfa95",
"files": 11,
"dir": "model/earth-geography"
},
{
"id": "earth-revolution",
"version": "1.7",
"build": "53b7a0fbc3",
"manifestSha256": "ab257669cd2bc57289d7e86b361064034d6040e85603b65069a93aec8d457b0b",
"filesSha256": "4cd45b0324a77574a0da3a939c2a6faebc785c5a24cb50136d62a78a6ea2e9b1",
"files": 7,
"dir": "model/earth-revolution"
},
{
"id": "earth-rotation",
"version": "1.7",
"build": "ecd52665f9",
"manifestSha256": "d463d85e08fd7f0525f8e08a5e9ec49c0005b3d8ca97a7f9497e95bdbb0697cb",
"filesSha256": "594b005a6a9f36cd0b5d4e4a7a0b1ab42d53c8032832545b71c3915493d56c8e",
"files": 7,
"dir": "model/earth-rotation"
},
{
"id": "scale-calculator",
"version": "1.6",
"build": "105653737d",
"manifestSha256": "2ac714eafb9acb4e4f11567b61848441de0f65ac41eb4260bc2d868c9500f56d",
"filesSha256": "732dd26406e0f1e836970499d7ea644def332ce909d7f8aa0a403bbe7337e604",
"files": 6,
"dir": "model/scale-calculator"
}
],
"signature": {
"alg": "ECDSA-P256-SHA256",
"keyId": "gc-2026-12",
"value": "U6j86/9PIUe5ZIqLRUlSIFf6EhODc7Dar1KvL7MecYujzNJ+ZnRrUg7aUT1rvktVwz4nyRacf9RYM2JQFb+qKw==",
"contentSha256": "585f22236fa1a50d4e99581c676b8ad694c5e352b12fe1bfed30c342b1f38690",
"signedAt": "2026-11-19T10:21:32Z"
}
}
-83
View File
@@ -1,83 +0,0 @@
#!/usr/bin/env bash
# 跨语言一致性校验:对 6 个版本跑同一组命令,对比输出是否逐字一致。
# 兼容 macOS 自带 bash 3.2(不用关联数组)。
set -uo pipefail
cd "$(dirname "$0")"
LANGS="Go Rust Java Zig Cpp C"
exe_of() {
case "$1" in
Go) echo "GC-Go/gcctl" ;;
Rust) echo "GC-Rust/gcctl" ;;
Java) echo "GC-Java/gcctl" ;;
Zig) echo "GC-Zig/gcctl" ;;
Cpp) echo "GC-C++/gcctl" ;;
C) echo "GC-C/gcctl" ;;
esac
}
CASES=(
"version-normalize|GCL-v1.0.6-beta"
"version-compare|v1.0.6|1.0.7"
"human-size|1536"
"model|scale|solve|real|3|0|100000"
"model|scale|human|300000"
"model|scale|grade|100000"
"model|scale|grade|500000"
"model|scale|grade|10000000"
"model|scale|spectrum|1000"
"model|scale|segment|100000|3|120"
"model|contour|build|mountain:32"
"model|contour|sample|mountain:32|0.34|0.34"
"model|contour|classify|mountain:32|0.34|0.34"
"model|contour|color|1200"
"model|rotation|subsolar|90|23.5"
"model|rotation|date|90"
"model|revolution|season|90"
"model|revolution|step|20|0|0.016|1"
"model|geo|declination|40"
"model|geo|declination|0"
"model|geo|latlon|40|116"
)
echo "=== 可执行文件存在性 ==="
for L in $LANGS; do
e=$(exe_of "$L")
if [ -x "$e" ]; then echo " [OK] $L -> $e"; else echo " [MISS] $L -> $e"; fi
done
echo
echo "=== 自检结果 ==="
for L in $LANGS; do
e=$(exe_of "$L")
if [ -x "$e" ]; then
out=$("$e" selftest 2>&1)
pass=$(printf '%s\n' "$out" | grep -c 'PASS')
fail=$(printf '%s\n' "$out" | grep -c 'FAIL')
echo " $L: PASS=$pass FAIL=$fail"
fi
done
echo
echo "=== 输出一致性(以 Go 为基准)==="
baseexe=$(exe_of Go)
mismatch=0
for c in "${CASES[@]}"; do
IFS='|' read -ra argv <<< "$c"
base=$("$baseexe" "${argv[@]}" 2>&1)
label="${argv[*]}"
for L in $LANGS; do
[ "$L" = "Go" ] && continue
e=$(exe_of "$L")
[ -x "$e" ] || continue
out=$("$e" "${argv[@]}" 2>&1)
if [ "$out" != "$base" ]; then
echo " [DIFF] $L :: $label"
echo " Go: $base"
echo " $L: $out"
mismatch=$((mismatch+1))
fi
done
done
if [ "$mismatch" -eq 0 ]; then echo " 全部一致"; else echo " 共 $mismatch 处差异"; fi
@@ -13,12 +13,16 @@
<LangVersion>latest</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
<MvvmVersion>8.2.2</MvvmVersion>
<!-- 模型窗口仍由 Avalonia 承载(模型契约返回 Avalonia Control),
所有界面由 Avalonia 承载。Avalonia.BuildServices 的遥测会向用户目录写日志,
在只读目录 / CI 里会直接让编译失败,build.sh / build.ps1 已默认关闭。 -->
<!--
Avalonia.BuildServices 的遥测任务会向用户目录写 buildtasks.log。
在只读用户目录 / CI / 沙箱里该写入抛 UnauthorizedAccessException(MSB4018),
直接让整个解决方案编译失败(实测)。官方开关是环境变量
AVALONIA_TELEMETRY_OPTOUT=1(MSBuild 属性对 11.3.2 无效),
build.sh / build.ps1 已默认导出;IDE 直接编译时无需此变量。
-->
<AvaloniaVersion>11.3.9</AvaloniaVersion>
<Version>1.1.2</Version>
<MvvmVersion>8.2.2</MvvmVersion>
<Version>1.0.10</Version>
<Company>Morris</Company>
<Product>GC</Product>
<NeutralLanguage>zh-Hans</NeutralLanguage>
File renamed without changes.
+197
View File
@@ -0,0 +1,197 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace GC;
/// <summary>
/// 新界面启动壳。
///
/// 发布包同时带 <c>GC.UI.Server</c>(本地 HTTP 后端 + 模型窗口宿主)和
/// <c>GC-UI</c>(Flutter 前端)时,启动器只做三件事:
/// 1. 拉起后端并等 <c>/api/health</c> 就绪;
/// 2. 拉起 Flutter 窗口;
/// 3. 界面退出后关掉后端。
///
/// 两个产物缺任意一个就返回 <c>false</c>,由调用方回退到内置 Avalonia 界面——
/// 这样 `dotnet run`、只编了启动器的开发场景、以及交叉编译缺前端产物的包都能正常打开。
/// </summary>
internal static class FlutterShell
{
/// <summary>与前端、后端共用的默认端口(定义在 GC.Services.GcUiContract)。</summary>
private const int Port = Services.GcUiContract.DefaultPort;
private static readonly HttpClient Http = new() { Timeout = TimeSpan.FromSeconds(1.5) };
private static Process? _backend;
public static bool TryRun(string[] args)
{
var dir = AppContext.BaseDirectory;
var backendPath = FindBackend(dir);
var uiPath = FindUi(dir);
if (backendPath == null || uiPath == null) return false;
// 用户可能重复启动:已有后端在跑就直接复用,退出时也不要关掉别人的进程。
var port = Port;
if (!IsHealthy(port))
{
// 端口可能被别的程序占用:17890 起向后试几个,选第一个能起来且健康的。
var start = Environment.GetEnvironmentVariable(Services.GcUiContract.PortEnvVar) is { Length: > 0 }
? Services.GcUiContract.PortFromEnvironment()
: Port;
for (var candidate = start; candidate < start + Services.GcUiContract.PortScanRange; candidate++)
{
var process = Start(backendPath, $"--port {candidate}", dir);
if (process == null) continue;
if (WaitHealthy(candidate, process, TimeSpan.FromSeconds(25)))
{
port = candidate;
_backend = process;
break;
}
Stop(process);
}
if (_backend == null) return false;
}
AppDomain.CurrentDomain.ProcessExit += (_, _) => Stop(_backend);
var ui = Start(uiPath, null, dir, port);
if (ui == null)
{
Stop(_backend);
_backend = null;
return false;
}
ui.WaitForExit();
Stop(_backend);
_backend = null;
return true;
}
// ---------------------------------------------------------------- 产物定位
private static string? FindBackend(string dir)
{
foreach (var name in OperatingSystem.IsWindows()
? new[] { "GC.UI.Server.exe", "GC.UI.Server" }
: new[] { "GC.UI.Server", "GC.UI.Server.exe" })
{
var path = Path.Combine(dir, name);
if (File.Exists(path)) return path;
}
return null;
}
/// <summary>
/// Flutter 桌面产物。
/// macOS 是 <c>GC-UI.app/Contents/MacOS/GC-UI</c>;Windows 是 <c>GC-UI.exe</c>;
/// Linux 是 <c>GC-UI</c>。
/// </summary>
private static string? FindUi(string dir)
{
if (OperatingSystem.IsMacOS())
{
var exe = Path.Combine(dir, "GC-UI.app", "Contents", "MacOS", "GC-UI");
if (File.Exists(exe)) return exe;
}
foreach (var name in OperatingSystem.IsWindows() ? new[] { "GC-UI.exe" } : new[] { "GC-UI" })
{
var path = Path.Combine(dir, name);
if (File.Exists(path)) return path;
}
return null;
}
// ---------------------------------------------------------------- 进程管理
private static Process? Start(string fileName, string? arguments, string workingDirectory, int port = 0)
{
try
{
var info = new ProcessStartInfo(fileName)
{
WorkingDirectory = workingDirectory,
UseShellExecute = false,
CreateNoWindow = true,
};
if (!string.IsNullOrEmpty(arguments)) info.Arguments = arguments;
// 把实际端口传给子进程:后端读它监听,前端读它拼 baseUrl。
// 这样换端口不需要重新编译前端。
if (port > 0)
info.Environment[Services.GcUiContract.PortEnvVar] = port.ToString();
// macOS .app 内的二进制也需要可执行位;发布包由 zip 解开时可能丢失。
if (!OperatingSystem.IsWindows())
{
try { File.SetUnixFileMode(fileName, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); }
catch { /* 权限不足时交给系统判断 */ }
}
return Process.Start(info);
}
catch (Exception ex)
{
Console.Error.WriteLine($"[shell] 启动失败 {fileName}: {ex.Message}");
return null;
}
}
private static void Stop(Process? process)
{
if (process == null) return;
try
{
if (!process.HasExited) process.Kill(entireProcessTree: true);
}
catch (Exception ex)
{
Console.Error.WriteLine($"[shell] 关闭后端失败: {ex.Message}");
}
finally
{
process.Dispose();
}
}
// ---------------------------------------------------------------- 健康检查
private static bool IsHealthy(int port)
{
try
{
using var response = Http.GetAsync($"http://127.0.0.1:{port}/api/health")
.GetAwaiter().GetResult();
return response.IsSuccessStatusCode;
}
catch
{
return false;
}
}
private static bool WaitHealthy(int port, Process backend, TimeSpan timeout)
{
var deadline = DateTime.UtcNow + timeout;
while (DateTime.UtcNow < deadline)
{
// 后端进程已经退出就没必要再等:端口被占、依赖缺失都会走这里。
if (backend.HasExited) return false;
if (IsHealthy(port)) return true;
Thread.Sleep(250);
}
return false;
}
}
@@ -13,8 +13,8 @@
</PropertyGroup>
<ItemGroup>
<!-- 后端以库的方式编进启动器:发布包只需要一个 exe,不用再带一份运行时 -->
<FrameworkReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="Avalonia.Desktop" Version="$(AvaloniaVersion)" />
</ItemGroup>
<ItemGroup>
+3 -3
View File
@@ -1,6 +1,5 @@
using System;
using Avalonia;
using Avalonia.WebView.Desktop;
using GC.Services;
using GC.Download;
@@ -22,13 +21,14 @@ internal static class Program
// 上次下载的启动器新版,到这次启动才应用
if (DownloadModuleHost.Factory.TryApplyPending(paths)) return;
// 所有界面统一由 Avalonia 承载(主窗口 / 模型窗口 / 课件),不再依赖 Flutter。
// 发布包带 Flutter 前端时,界面交给它;没带则回退到内置 Avalonia 界面。
if (FlutterShell.TryRun(args)) return;
BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
}
public static AppBuilder BuildAvaloniaApp()
=> AppBuilder.Configure<App>()
.UsePlatformDetect()
.UseDesktopWebView()
.LogToTrace();
}
File renamed without changes.
+152
View File
@@ -0,0 +1,152 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace GC.Services;
/// <summary>
/// 本地目录源:用于离线教学(U 盘 / 共享盘里的仓库副本)与自动化测试。
/// 目录结构与远端仓库一致:version.json + model/&lt;id&gt;/...
/// </summary>
public sealed class DirectoryRemote : IModelRemote
{
private readonly string _root;
private static readonly HttpClient Http = new() { Timeout = TimeSpan.FromMinutes(5) };
private string? _rawManifest;
private string _launcherVersion = "";
public DirectoryRemote(string root) => _root = Path.GetFullPath(root);
public string DisplayName => _root;
public Task<RepoVersion?> GetVersionAsync(CancellationToken ct)
{
var primary = SafePath("version.json");
var fallback = SafePath(Path.Combine("model", "version.json"));
var file = File.Exists(primary) ? primary : fallback;
if (!File.Exists(file)) return Task.FromResult<RepoVersion?>(null);
// 离线目录同样验签:U 盘 / 共享盘里的清单也可能是被替换过的
var text = File.ReadAllText(file);
_rawManifest = text;
var version = ManifestLoader.Parse(text, out _);
if (version != null && !string.IsNullOrWhiteSpace(version.Launcher.Version))
_launcherVersion = version.Launcher.Version.Trim();
return Task.FromResult(version);
}
/// <summary>最近一次读到的清单原文(SAVEDOG 二次验签用)。</summary>
public Task<string?> GetRawVersionTextAsync(CancellationToken ct)
=> Task.FromResult(_rawManifest);
public Task<IReadOnlyList<RepoEntry>> ListTreeAsync(string rootPath, CancellationToken ct)
{
var baseDir = SafePath(rootPath ?? "model");
var result = new List<RepoEntry>();
if (!Directory.Exists(baseDir)) return Task.FromResult<IReadOnlyList<RepoEntry>>(result);
Walk(baseDir, baseDir, 0, result);
return Task.FromResult<IReadOnlyList<RepoEntry>>(result);
}
private void Walk(string dir, string baseDir, int depth, List<RepoEntry> result)
{
if (depth > 8) return;
foreach (var sub in Directory.GetDirectories(dir))
{
var name = Path.GetFileName(sub);
if (name.StartsWith('.')) continue;
var rel = Relative(baseDir, sub);
result.Add(new RepoEntry
{
Name = name,
Path = Relative(_root, sub),
RelativePath = rel,
IsDirectory = true
});
Walk(sub, baseDir, depth + 1, result);
}
foreach (var file in Directory.GetFiles(dir))
{
var name = Path.GetFileName(file);
if (name.StartsWith('.')) continue;
result.Add(new RepoEntry
{
Name = name,
Path = Relative(_root, file),
RelativePath = Relative(baseDir, file),
IsDirectory = false,
Size = new FileInfo(file).Length
});
}
}
public async Task<byte[]> DownloadAsync(RepoEntry entry, CancellationToken ct)
=> await File.ReadAllBytesAsync(SafePath(entry.Path), ct);
public async Task<byte[]?> DownloadPackageAsync(RepoPackage package, CancellationToken ct)
{
// 清单路径 / dist 根目录命名:按仓库内相对路径直接找
foreach (var rel in LauncherArtifacts.CandidateFiles(
package.Rid, package.Dir, package.Path, package.Name, _launcherVersion))
{
string full;
try { full = SafePath(rel); }
catch (InvalidOperationException) { continue; }
if (File.Exists(full)) return await File.ReadAllBytesAsync(full, ct);
}
// dist/<系统>-<架构>/ 里放着的编译产物(与远端同一套查找规则):
// 本地源同样要能跑通「只发产物、不发 Release」的更新方式。
var fromDist = FindInDist(package);
if (fromDist != null) return await File.ReadAllBytesAsync(fromDist, ct);
var url = package.Url;
if (string.IsNullOrWhiteSpace(url)) return null;
// 离线 U 盘源与 ./build.sh update-test 都会用本地 zip 路径,必须保持兼容。
if (url!.StartsWith("file://", StringComparison.OrdinalIgnoreCase))
return await File.ReadAllBytesAsync(new Uri(url).LocalPath, ct);
if (Path.IsPathRooted(url) && File.Exists(url))
return await File.ReadAllBytesAsync(url, ct);
if (Uri.TryCreate(url, UriKind.Absolute, out _))
return await Http.GetByteArrayAsync(url, ct);
return null;
}
/// <summary>在 dist/&lt;系统&gt;-&lt;架构&gt;/ 里找这个平台的启动器包;找不到返回 null。</summary>
private string? FindInDist(RepoPackage package)
{
foreach (var dir in LauncherArtifacts.CandidateDirs(package.Rid, package.Dir))
{
string full;
try { full = SafePath(dir); }
catch (InvalidOperationException) { continue; }
if (!Directory.Exists(full)) continue;
var zips = Directory.GetFiles(full, "*.zip");
if (zips.Length == 0) continue;
foreach (var zip in zips)
if (LauncherArtifacts.LooksLikePackage(Path.GetFileName(zip), _launcherVersion, package.Rid))
return zip;
if (zips.Length == 1) return zips[0];
}
return null;
}
private string SafePath(string relative)
{
var full = Path.GetFullPath(Path.Combine(_root, relative));
var prefix = _root.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
if (!full.Equals(_root, StringComparison.OrdinalIgnoreCase) &&
!full.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException($"路径越界: {relative}");
return full;
}
private static string Relative(string baseDir, string file) =>
Path.GetRelativePath(baseDir, file).Replace('\\', '/');
}
@@ -56,14 +56,12 @@ public sealed partial class DownloadJob : ObservableObject, IDownloadJob
partial void OnErrorChanged(string? value) => RefreshText();
}
/// <summary>下载中心:最多 4 个并发,任务在「后台列表」里折叠展示。</summary>
/// <summary>下载中心:最多 2 个并发,任务在「后台列表」里折叠展示。</summary>
public sealed class DownloadCenter : IDownloadCenter
{
private readonly ModelRepository _repository;
private readonly AppPaths _paths;
// 断点续传后单任务失败重来的代价小了很多,可以适当提高并发;
// 更新服务那边已是 6,模型下载保持 4,兼顾弱网吞吐与源站压力。
private readonly SemaphoreSlim _slots = new(4);
private readonly SemaphoreSlim _slots = new(2);
public ObservableCollection<IDownloadJob> Jobs { get; } = new();
public event Action? Installed;
File renamed without changes.
File renamed without changes.
@@ -25,8 +25,17 @@ public sealed class GitCodeReleaseRemote : IModelRemote
private readonly string _releasesUrl;
private readonly Dictionary<string, (string Url, string? Sha256, long Size, string Name)> _assets = new();
// 使用共享 HttpClient 工厂,统一连接池管理
private static readonly HttpClient Http = SharedHttpClientFactory.GetDefault();
// 共享静态 HttpClient:避免每次检查更新都创建新实例导致端口耗尽;
// headers 只在一处设置,多个线程并发读取是线程安全的。
private static readonly HttpClient Http = CreateHttp();
private static HttpClient CreateHttp()
{
var client = new HttpClient { Timeout = TimeSpan.FromSeconds(15) };
client.DefaultRequestHeaders.UserAgent.ParseAdd("GC-Updater/1.0");
client.DefaultRequestHeaders.Accept.ParseAdd("application/json");
return client;
}
public GitCodeReleaseRemote(string? manifestUrl, string? repository)
{
@@ -71,8 +80,7 @@ public sealed class GitCodeReleaseRemote : IModelRemote
}
catch (Exception ex)
{
GcLog.Warn($"读取 Release 失败: {ex.Message}",
$"Failed to read Release: {ex.Message}");
Console.Error.WriteLine($"[gitcode] 读取 Release 失败: {ex.Message}");
gotRelease = false;
}
@@ -85,13 +93,12 @@ public sealed class GitCodeReleaseRemote : IModelRemote
var n = version?.Launcher.Packages.Count ?? 0;
if (v.Length == 0 || n == 0)
{
GcLog.Warn($"{DisplayName}: 没有 Release,清单里也没有启动器包",
$"{DisplayName}: No Release, no launcher packages in manifest");
Console.WriteLine($"[gitcode] {DisplayName}: 没有 Release,清单里也没有启动器包");
}
else
{
GcLog.Info($"没有 Release,改用清单声明的 v{v}({n} 个平台包,去 dist/ 找产物)",
$"No Release; using manifest version v{v} ({n} platform packages, looking in dist/)");
Console.WriteLine(
$"[gitcode] {DisplayName}: 没有 Release,改用清单声明的 v{v}({n} 个平台包,去 dist/ 找产物)");
}
}
return version;
@@ -42,8 +42,9 @@ public sealed class GitCodeRemote : IModelRemote
_displayName = string.IsNullOrWhiteSpace(repository)
? DefaultRepository : repository!.TrimEnd('/');
// 使用共享 HttpClient,统一连接池管理
_http = SharedHttpClientFactory.GetDefault();
_http = new HttpClient { Timeout = TimeSpan.FromMinutes(2) };
_http.DefaultRequestHeaders.UserAgent.ParseAdd("GC-Updater/1.0");
_http.DefaultRequestHeaders.Accept.ParseAdd("application/json");
if (string.IsNullOrWhiteSpace(manifestUrl))
{
@@ -134,11 +135,7 @@ public sealed class GitCodeRemote : IModelRemote
if (string.IsNullOrWhiteSpace(version.Generated)) return null;
if (verification.Trust == ManifestTrust.Invalid)
{
GcLog.Warn($"清单验签失败,已拒绝: {verification.Error}",
$"Manifest signature check failed: {verification.Error}");
return null;
}
Console.Error.WriteLine($"[gitcode] 清单验签失败: {verification.Error}");
if (version != null && !string.IsNullOrWhiteSpace(version.Generated))
_rawManifest = payload;
@@ -146,8 +143,7 @@ public sealed class GitCodeRemote : IModelRemote
}
catch (Exception ex)
{
GcLog.Warn($"版本清单解析失败 {url}: {ex.Message}",
$"Failed to parse version manifest {url}: {ex.Message}");
Console.Error.WriteLine($"版本清单解析失败 {url}: {ex.Message}");
return null;
}
}
@@ -180,8 +176,7 @@ public sealed class GitCodeRemote : IModelRemote
try { text = await GetWithRetryAsync(url, ct); }
catch (Exception ex)
{
GcLog.Warn($"列目录失败 {repoPath}: {ex.Message}",
$"Failed to list directory {repoPath}: {ex.Message}");
Console.Error.WriteLine($"列目录失败 {repoPath}: {ex.Message}");
return;
}
if (!text.TrimStart().StartsWith("[", StringComparison.Ordinal)) return;
@@ -340,8 +335,7 @@ public sealed class GitCodeRemote : IModelRemote
if (bytes != null) return bytes;
}
GcLog.Warn("找不到可用的启动器包(Release 附件与 dist 目录都没对上)",
"Could not find a usable launcher package");
Console.Error.WriteLine("[gitcode] 找不到可用的启动器包(Release 附件与 dist 目录都没对上)");
return null;
}
@@ -354,8 +348,7 @@ public sealed class GitCodeRemote : IModelRemote
try { bytes = await _http.GetByteArrayAsync(url!, ct); }
catch (Exception ex)
{
GcLog.Warn($"下载失败 {Short(url!)}: {ex.Message}",
$"Download failed {Short(url!)}: {ex.Message}");
Console.Error.WriteLine($"[gitcode] 下载失败 {Short(url!)}: {ex.Message}");
return null;
}
if (bytes.Length == 0) return null;
@@ -365,14 +358,12 @@ public sealed class GitCodeRemote : IModelRemote
var actual = Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant();
if (!string.Equals(actual, sha256.Trim(), StringComparison.OrdinalIgnoreCase))
{
GcLog.Warn($"包校验不符,换下一个来源: {Short(url!)}",
$"Package hash mismatch, trying next source: {Short(url!)}");
Console.Error.WriteLine($"[gitcode] 包校验不符,换下一个来源: {Short(url!)}");
return null;
}
}
GcLog.Info($"启动器包来源: {Short(url!)}",
$"Launcher package source: {Short(url!)}");
Console.WriteLine($"[gitcode] 启动器包来源: {Short(url!)}");
return bytes;
}
@@ -437,8 +428,7 @@ public sealed class GitCodeRemote : IModelRemote
match = 0;
}
GcLog.Info($"在 {dir} 找到编译产物: {zips[match].Name}",
$"Found build artifact in {dir}: {zips[match].Name}");
Console.WriteLine($"[gitcode] 在 {dir} 找到编译产物: {zips[match].Name}");
return await ResolveFileUrlAsync(zips[match].Path, ct);
}
catch (Exception)
@@ -22,10 +22,17 @@ namespace GC.Services;
public sealed class GiteaRemote : IModelRemote
{
private readonly SourcePreset _preset;
// 使用共享 HttpClient,统一连接池管理
private static readonly HttpClient Http = SharedHttpClientFactory.GetDefault();
private static readonly HttpClient Http = CreateHttp();
private string? _rawManifest;
private static HttpClient CreateHttp()
{
var c = new HttpClient { Timeout = TimeSpan.FromSeconds(20) };
c.DefaultRequestHeaders.UserAgent.ParseAdd("GC-Updater/1.0");
c.DefaultRequestHeaders.Accept.ParseAdd("application/json");
return c;
}
public GiteaRemote(SourcePreset preset)
{
_preset = preset;
@@ -37,18 +44,6 @@ public sealed class GiteaRemote : IModelRemote
private string RepoApi => $"{_preset.ApiBase}/repos/{_preset.Owner}/{_preset.Repo}";
/// <summary>GitHub 的 contents API 必须显式带 ref;Gitea 默认就读默认分支。</summary>
private string ContentsUrl(string path)
{
var p = path.Trim('/');
var head = string.IsNullOrEmpty(p) ? $"{RepoApi}/contents" : $"{RepoApi}/contents/{p}";
return _preset.Kind == "github" ? $"{head}?ref={_preset.Branch}" : head;
}
/// <summary>Releases 列表地址:GitHub 默认只返回 30 条,需要显式拉满一页。</summary>
private string ReleasesUrl() =>
_preset.Kind == "github" ? $"{RepoApi}/releases?per_page=100" : $"{RepoApi}/releases";
// ---------------------------------------------------------------- 清单
/// <summary>
@@ -91,8 +86,7 @@ public sealed class GiteaRemote : IModelRemote
}
// 没有 Release:清空启动器版本,让上层知道"这个源没有可升级的启动器"
GcLog.Warn($"{_preset.Name}: Release 为空(模型清单仍可用)",
$"{_preset.Name}: No Release found (model manifest still available)");
Console.WriteLine($"[gitea] {_preset.Name}: Release 为空(模型清单仍可用)");
result.Launcher.Version = "";
result.Launcher.Packages.Clear();
@@ -113,13 +107,8 @@ public sealed class GiteaRemote : IModelRemote
var text = await Http.GetStringAsync(url, ct);
if (!text.TrimStart().StartsWith('{')) continue; // 可能返回 HTML
var doc = ManifestLoader.Parse(text, out var verification);
// 清单验签失败或格式不对时直接返回 null,不再把不可信清单交给上层
if (verification.Trust == ManifestTrust.Invalid)
{
GcLog.Warn($"清单验签失败,已拒绝: {verification.Error}",
$"Manifest signature verification failed: {verification.Error}");
return null;
}
Console.Error.WriteLine($"[gitea] 清单验签失败: {verification.Error}");
if (doc != null)
{
_rawManifest = text;
@@ -128,8 +117,7 @@ public sealed class GiteaRemote : IModelRemote
}
catch (Exception ex)
{
GcLog.Warn($"version.json 读取失败 {url}: {ex.Message}",
$"Failed to read version.json {url}: {ex.Message}");
Console.Error.WriteLine($"[gitea] version.json 读取失败 {url}: {ex.Message}");
}
}
return null;
@@ -143,7 +131,7 @@ public sealed class GiteaRemote : IModelRemote
{
try
{
var json = await Http.GetStringAsync(ReleasesUrl(), ct);
var json = await Http.GetStringAsync($"{RepoApi}/releases", ct);
using var doc = JsonDocument.Parse(json);
if (doc.RootElement.ValueKind != JsonValueKind.Array) return null;
@@ -160,8 +148,7 @@ public sealed class GiteaRemote : IModelRemote
if (candidates.Count == 0)
{
// 还没发布 Release 是正常状态:交给上层去问另一个源
GcLog.Info($"{_preset.Name}: Release 列表为空",
$"{_preset.Name}: Empty Release list");
Console.WriteLine($"[gitea] {_preset.Name}: Release 列表为空");
return null;
}
@@ -203,8 +190,7 @@ public sealed class GiteaRemote : IModelRemote
}
catch (Exception ex)
{
GcLog.Warn($"Release 读取失败({_preset.Name}): {ex.Message}",
$"Failed to read Release ({_preset.Name}): {ex.Message}");
Console.Error.WriteLine($"[gitea] Release 读取失败({_preset.Name}): {ex.Message}");
return null;
}
}
@@ -236,13 +222,12 @@ public sealed class GiteaRemote : IModelRemote
{
if (depth > 8) return;
var url = ContentsUrl(apiPath);
var url = $"{RepoRepoContentsUrl()}/{apiPath}";
string json;
try { json = await Http.GetStringAsync(url, ct); }
catch (Exception ex)
{
GcLog.Warn($"列目录失败 {apiPath}: {ex.Message}",
$"Failed to list directory {apiPath}: {ex.Message}");
Console.Error.WriteLine($"[gitea] 列目录失败 {apiPath}: {ex.Message}");
return;
}
@@ -279,6 +264,8 @@ public sealed class GiteaRemote : IModelRemote
await WalkAsync(p, rel, sink, ct, depth + 1);
}
private string RepoRepoContentsUrl() => $"{RepoApi}/contents";
private static void AddFile(JsonElement item, string relPrefix, List<RepoEntry> sink)
{
var name = item.TryGetProperty("name", out var n) ? n.GetString() ?? "" : "";
@@ -338,14 +325,12 @@ public sealed class GiteaRemote : IModelRemote
System.Security.Cryptography.SHA256.HashData(bytes)).ToLowerInvariant();
if (!string.Equals(actual, package.Sha256.Trim(), StringComparison.OrdinalIgnoreCase))
{
GcLog.Warn($"包校验不符,换下一个来源: {candidate}",
$"Package hash mismatch, trying next source: {candidate}");
Console.Error.WriteLine($"[gitea] 包校验不符,换下一个来源: {candidate}");
continue;
}
}
GcLog.Info($"启动器包来源: {candidate}",
$"Launcher package source: {candidate}");
Console.WriteLine($"[gitea] 启动器包来源: {candidate}");
return bytes;
}
return null;
File renamed without changes.
@@ -90,13 +90,7 @@ public static class LauncherUpdater
}
}
if (candidates.Count == 0)
{
// 两个源都连不上或都没发 Release:返回一个带明确语义的信号,
// 让上层能区分「检查失败」和「已是最新」。用 null 版本 + 特殊标记表达。
Console.WriteLine("[update] 所有源都不可达,无法检查启动器更新");
return null;
}
if (candidates.Count == 0) return null;
// 取版本号最高的(第 7 项)
var best = candidates.OrderByDescending(c => VersionUtil.Parse(c.Version)).First();
@@ -200,26 +194,8 @@ public static class LauncherUpdater
{
using var ms = new MemoryStream(zip);
using var archive = new System.IO.Compression.ZipArchive(ms, System.IO.Compression.ZipArchiveMode.Read);
// 发布包从 1.0.10 起改为 GCL 命名 + 单文件 + 单顶层目录,主程序是
// <顶层>/GCL-<版本>-<平台>.exe (Windows)
// <顶层>/GCL-<版本>-<平台> (Linux,无扩展名)
// <顶层>/GCL-<版本>-mac-arm64.app/... (macOS)
// 旧布局则是 GC.dll / GC / GC*.dll。先找新名,再退回旧名,兼容老发布包。
// 注意排除 GC-UI / GC-SAVEDOG / .GC/bin 里的附属程序,它们不是启动器本体。
bool IsLauncher(System.IO.Compression.ZipArchiveEntry e)
{
var n = e.Name;
if (n.Length == 0) return false; // 目录条目
if (n.StartsWith("GC-UI", StringComparison.OrdinalIgnoreCase) ||
n.StartsWith("GC-SAVEDOG", StringComparison.OrdinalIgnoreCase)) return false;
if (e.FullName.Replace('\\', '/').Contains("/.GC/")) return false;
if (n.StartsWith("GCL-", StringComparison.OrdinalIgnoreCase)) return true;
return false;
}
var entry = archive.Entries.FirstOrDefault(IsLauncher)
?? archive.Entries.FirstOrDefault(e =>
// 找主程序:app 内的可执行文件 / GC.dll / 单文件 exe
var entry = archive.Entries.FirstOrDefault(e =>
e.Name.Equals("GC.dll", StringComparison.OrdinalIgnoreCase))
?? archive.Entries.FirstOrDefault(e =>
e.Name.Equals("GC", StringComparison.OrdinalIgnoreCase))
+88
View File
@@ -0,0 +1,88 @@
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using GC.Models;
namespace GC.Services;
public static class ModelInstaller
{
/// <summary>把源里的模型目录复制进本地模型库(先写临时目录再原子替换)。</summary>
public static async Task<string> InstallAsync(RemoteModel model, string modelRoot,
IProgress<(long Done, long Total)>? progress, CancellationToken ct)
{
var target = Path.Combine(modelRoot, model.Id);
var staging = target + ".installing";
if (Directory.Exists(staging)) Directory.Delete(staging, true);
Directory.CreateDirectory(staging);
long total = 0;
var files = Directory.GetFiles(model.Directory, "*", SearchOption.AllDirectories);
foreach (var file in files)
{
try { total += new FileInfo(file).Length; } catch { }
}
long done = 0;
try
{
foreach (var file in files)
{
ct.ThrowIfCancellationRequested();
var relative = Path.GetRelativePath(model.Directory, file);
// 路径穿越防护:相对路径必须完整落在 staging 目录内
var dest = Path.GetFullPath(Path.Combine(staging, relative));
var stagingFull = Path.GetFullPath(staging)
.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
if (!dest.StartsWith(stagingFull, StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException($"非法的模型文件路径: {relative}");
var destDir = Path.GetDirectoryName(dest);
if (!string.IsNullOrEmpty(destDir)) Directory.CreateDirectory(destDir);
await using (var src = File.OpenRead(file))
await using (var dst = File.Create(dest))
{
await src.CopyToAsync(dst, 81920, ct);
}
long length = 0;
try { length = new FileInfo(dest).Length; } catch { }
done += length;
progress?.Report((done, total <= 0 ? done : total));
}
// 原子替换:先备份旧目录,第二次 Move 失败时完整回滚,绝不把模型库清空
var backup = target + ".old";
if (Directory.Exists(backup)) Directory.Delete(backup, true);
var hasBackup = false;
try
{
if (Directory.Exists(target))
{
Directory.Move(target, backup);
hasBackup = true;
}
Directory.Move(staging, target);
}
catch
{
// 新目录尚未就位时把旧目录还原;staging 由外层 catch 清理
if (hasBackup && !Directory.Exists(target) && Directory.Exists(backup))
Directory.Move(backup, target);
throw;
}
if (hasBackup)
{
try { Directory.Delete(backup, true); } catch { /* 占用时留到下次 */ }
}
progress?.Report((total, total));
return target;
}
catch
{
try { if (Directory.Exists(staging)) Directory.Delete(staging, true); } catch { }
throw;
}
}
}
@@ -5,8 +5,6 @@ using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using GC.Models;
@@ -21,11 +19,16 @@ namespace GC.Services;
public sealed class ModelSourceClient : IModelSourceClient
{
private readonly AppPaths _paths;
private static readonly HttpClient Http = CreateHttp();
public ModelSourceClient(AppPaths paths) => _paths = paths;
// 使用共享 HttpClient(长超时版本用于大文件下载)
private static readonly HttpClient Http = SharedHttpClientFactory.GetLongTimeout();
private static HttpClient CreateHttp()
{
var client = new HttpClient { Timeout = TimeSpan.FromMinutes(5) };
client.DefaultRequestHeaders.UserAgent.ParseAdd("GC/1.0 (+model-source)");
return client;
}
public async Task<SourceIndex> FetchAsync(ModelSource source, bool force, IProgress<string>? log, CancellationToken ct)
{
@@ -149,33 +152,24 @@ public sealed class ModelSourceClient : IModelSourceClient
else if (host.Contains("gitee.com"))
yield return $"https://gitee.com/{owner}/{repo}/repository/archive/{b}.zip";
else
{
// 自托管 Gitea(如 git.xhmcl.com):用 archive/<branch>.zip 拉源码归档。
// 关键:不能在这里 yield break —— 那样就只剩 git clone 一条路,
// 用户机器没装 git 时「检测模型 / 下载 / 自动更新」会全部失效。
// 归档下载走 ResumableDownloader,无需系统 git。
yield return $"{uri.GetLeftPart(UriPartial.Authority)}/{owner}/{repo}/archive/{b}.zip";
}
yield break;
}
}
private async Task DownloadZipAsync(string url, string cacheDir, CancellationToken ct)
{
// .part 用 URL 哈希做稳定文件名:同一个源重试时命中同一份半成品,
// 断点续传才有意义(用 GUID 的话每次重试都是新文件,等于从零开始)。
// 解压目录仍用 GUID —— 它只是中间产物,成功后整块移走或失败即删。
var key = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(url)))[..16].ToLowerInvariant();
var partPath = Path.Combine(_paths.CacheRoot, "tmp", "downloads", key + ".part");
var tmpRoot = Path.Combine(_paths.CacheRoot, "tmp", Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(tmpRoot);
var zipPath = Path.Combine(tmpRoot, "source.zip");
try
{
// 带断点续传的流式下载;网络中断时 .part 保留,下次从这里接上。
await ResumableDownloader.DownloadAsync(Http, url, partPath, null, ct)
.ConfigureAwait(false);
// 下载完整,.part 转正。转正成功即代表这份 zip 已完整,删掉 .part 避免重复下载。
File.Move(partPath, zipPath, overwrite: true);
using (var response = await Http.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, ct))
{
response.EnsureSuccessStatusCode();
await using var input = await response.Content.ReadAsStreamAsync(ct);
await using var output = File.Create(zipPath);
await input.CopyToAsync(output, 81920, ct);
}
var extractDir = Path.Combine(tmpRoot, "extract");
Directory.CreateDirectory(extractDir);
@@ -24,14 +24,10 @@ public static class SavedogLauncher
var home = Path.Combine(paths.SafedogRoot, name);
if (File.Exists(home)) return home;
// 包内 payload:非本体文件统一收在 .GC/bin
var payload = Path.Combine(install, ".GC", "bin", name);
if (File.Exists(payload)) return payload;
var direct = Path.Combine(install, name);
if (File.Exists(direct)) return direct;
// 1.0.10 及更早的包把守护进程放在 safedog/ 子目录
// 新包把守护进程放在 safedog/ 子目录
var packaged = Path.Combine(install, "safedog", name);
if (File.Exists(packaged)) return packaged;
@@ -112,13 +108,8 @@ public static class SavedogLauncher
catch { }
}
var process = Process.Start(psi);
if (process == null)
{
error = "无法启动 GC-SAVEDOG:Process.Start 返回 null(参数或路径问题)";
return false;
}
Console.WriteLine($"[update] GC-SAVEDOG 已启动: {exe}(PID {process.Id})");
Process.Start(psi);
Console.WriteLine($"[update] GC-SAVEDOG 已启动: {exe}");
return true;
}
catch (Exception ex)
@@ -9,18 +9,22 @@ using System.Threading.Tasks;
namespace GC.Services;
/// <summary>
/// 多源选择:Xhmcl 与 GitHub 是同一份仓库的两个镜像。
/// 双源选择:Xhmcl 与 GitCode 是同一份仓库的两个镜像。
///
/// 启动更新 / 下载页面 / 检查更新时,先并发探测各源的 version.json 响应时间,
/// 启动更新 / 下载页面 / 检查更新时,先并发探测两边的 version.json 响应时间,
/// 取**最快且内容可用**的那个作为本次下载源;探测结果缓存一段时间,
/// 避免每次点下载都重新测速。单个源探测超时 2 秒,慢源不会拖住整体。
/// 避免每次点下载都重新测速。
/// </summary>
public sealed class SourceSelector : ISourceSelector
{
/// <summary>单源探测超时:超过 2 秒视为不可用(用户可见的「ping 2s」)。</summary>
private static readonly TimeSpan ProbeTimeout = TimeSpan.FromSeconds(2);
// 使用共享 HttpClient 工厂,统一连接管理,避免端口耗尽
private static readonly HttpClient Http = SharedHttpClientFactory.GetDefault();
private static readonly HttpClient Http = CreateHttp();
private static HttpClient CreateHttp()
{
var c = new HttpClient { Timeout = TimeSpan.FromSeconds(6) };
c.DefaultRequestHeaders.UserAgent.ParseAdd("GC-Probe/1.0");
return c;
}
private readonly object _lock = new();
private SourcePreset? _cached;
@@ -67,8 +71,7 @@ public sealed class SourceSelector : ISourceSelector
var chosen = usable.Count > 0 ? usable[0].Preset : fallback;
if (usable.Count == 0)
GcLog.Warn($"所有源探测失败,退回主源 {chosen.Name}",
$"All probes failed, fallback to {chosen.Name}");
Console.WriteLine($"[selector] 所有源探测失败,退回主源 {chosen.Name}(稍后由实际请求再判定)");
lock (_lock)
{
@@ -78,19 +81,17 @@ public sealed class SourceSelector : ISourceSelector
_cachedAt = usable.Count > 0 ? DateTime.UtcNow : DateTime.MinValue;
}
GcLog.Info($"测速结果:{string.Join(" ",
results.Select(r => $"{r.Preset.Name}={r.Ms}ms{(r.Ok ? "" : "(不可用)")}"))} → 选择 {chosen.Name}",
$"Probe results: {string.Join(", ",
results.Select(r => $"{r.Preset.Name}={r.Ms}ms{(r.Ok ? "" : "(unavailable)")}"))} -> chosen: {chosen.Name}");
Console.WriteLine("[selector] 测速:" + string.Join(" ",
results.Select(r => $"{r.Preset.Name}={r.Ms}ms{(r.Ok ? "" : "(不可用)")}"))
+ $" → 选择 {chosen.Name}");
return chosen;
}
/// <summary>
/// 探测:能拿到合法 JSON 才算可用。
/// 注意各平台取文件的方式不同:
/// 注意两个平台取文件的方式不同:
/// · Gitea(Xhmcl):raw/branch/{b}/{path} 直接返回文件内容
/// · GitHub:raw.githubusercontent.com/{b}/{path} 直接返回文件内容
/// · GitCode:raw 地址返回的是 HTML 页面,必须走 API(内容为 base64)
/// 因此 GitCode 用 api/v5 contents + Accept: application/json 探测。
/// </summary>
@@ -101,7 +102,7 @@ public sealed class SourceSelector : ISourceSelector
try
{
using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
cts.CancelAfter(ProbeTimeout);
cts.CancelAfter(TimeSpan.FromSeconds(5));
var api = $"{preset.ApiBase}/repos/{preset.Owner}/{preset.Repo}/contents/version.json?ref={preset.Branch}";
using var req = new HttpRequestMessage(HttpMethod.Get, api);
req.Headers.Accept.ParseAdd("application/json");
@@ -120,7 +121,7 @@ public sealed class SourceSelector : ISourceSelector
try
{
using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
cts.CancelAfter(ProbeTimeout);
cts.CancelAfter(TimeSpan.FromSeconds(5));
var text = await Http.GetStringAsync(url, cts.Token);
if (text.TrimStart().StartsWith('{')) return true;
}
@@ -133,9 +134,6 @@ public sealed class SourceSelector : ISourceSelector
public static IModelRemote CreateRemote(SourcePreset preset) => preset.Kind switch
{
"gitea" => new GiteaRemote(preset),
// GitHub 的 contents / releases API 与 Gitea 同构,复用同一实现
"github" => new GiteaRemote(preset),
"gitcode" => new GitCodeReleaseRemote(null, preset.HomeUrl),
_ => throw new InvalidOperationException($"未知的源类型: {preset.Kind}")
_ => new GitCodeReleaseRemote(null, preset.HomeUrl)
};
}
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -84,21 +84,12 @@ internal sealed class Applier
var manifestText = File.Exists(manifestPath) ? File.ReadAllText(manifestPath) : null;
var verification = ManifestSignature.Verify(manifestText, require);
// 签名不对(被改过 / 密钥不认识)永远拒绝;仅「没有签名」在明确不强制时放行。
// 之前这里不看 require:即使调用方声明 requireSignature=false(开发态、测试),
// 未签名清单也会被当成验签失败直接拒掉。
var hostile = verification.Trust == ManifestTrust.Invalid;
if (hostile || (verification.IsRejected && require))
if (verification.IsRejected)
{
_log.Error($"清单验签失败({verification.Trust}):{verification.Error}",
$"Manifest signature check failed ({verification.Trust}): {verification.Error}");
return Refuse(updateDir, request, verification);
}
if (verification.IsRejected)
{
_log.Warn($"清单未签名,按调用方要求放行:{verification.Error}",
$"Manifest is unsigned; continuing as requested: {verification.Error}");
}
_log.Info($"清单可信度:{verification.Trust}" +
(verification.KeyId != null ? $"({verification.KeyId})" : ""),
$"Manifest trust: {verification.Trust}" +
@@ -502,12 +493,12 @@ internal sealed class Applier
/// <summary>
/// 把 <paramref name="stage"/> 的内容替换进 <paramref name="installDir"/>。
///
/// 发布包是「整目录」(启动器 + 后端运行时 + 课件资源),只搬一个 exe 会留下
/// 发布包是「整目录」(启动器 + 后端运行时 + Flutter 前端资源),只搬一个 exe 会留下
/// 旧后端 / 旧界面,所以这里按目录整体替换:
/// 1. 安装目录里「新版没有」的条目 → 移到 backup(旧版本残留,如上一版的旧文件名);
/// 2. 与新版同名的条目 → 先移到 backup,再把新版放进来(覆盖正在被占用的文件会失败,
/// 这种情况直接报错并还原,绝不留下半新半旧的目录);
/// 3. `.GC` 只合并 `bin/`(非本体文件),其余子目录与更新目录自身一律跳过。
/// 3. `.GC`、更新目录自身、正在运行的 GC-SAVEDOG.exe 一律跳过。
///
/// 返回 false 时调用方应调用 <see cref="RestoreFromBackup"/> 还原。
/// </summary>
@@ -527,14 +518,6 @@ internal sealed class Applier
foreach (var entry in Directory.GetFileSystemEntries(stage))
{
var name = Path.GetFileName(entry);
if (string.Equals(name, ".GC", StringComparison.OrdinalIgnoreCase))
{
// .GC 里只有 bin/ 属于程序本体(守护进程这类「非本体」文件),
// 其余(config / model / cache / update / logs / safedog)是用户数据,
// 整目录替换时必须原地不动。
MergeGcBin(entry, installDir, backupDir, replaced);
continue;
}
if (IsProtected(name))
{
// 例如 GC-SAVEDOG.exe:本进程正在运行,Windows 上无法替换。
@@ -592,52 +575,6 @@ internal sealed class Applier
}
}
/// <summary>
/// 合并新包里的 <c>.GC/bin</c>:只搬这一层文件,不动 .GC 下的用户数据。
///
/// 守护进程放在这里(而不是安装目录根)是为了「非本体文件全部收进 .GC/bin」;
/// 但正在运行的是 <c>.GC/safedog</c> 里的副本,所以这里的文件可以安全替换。
/// </summary>
private void MergeGcBin(string stageGc, string installDir, string backupDir,
List<(string Name, string? BackupPath)> replaced)
{
try
{
var bin = Path.Combine(stageGc, "bin");
if (!Directory.Exists(bin)) return;
var relBin = Path.Combine(".GC", "bin");
var targetBin = Path.Combine(installDir, relBin);
Directory.CreateDirectory(targetBin);
foreach (var file in Directory.GetFiles(bin))
{
var name = Path.GetFileName(file);
var rel = Path.Combine(relBin, name);
var target = Path.Combine(targetBin, name);
var backup = Path.Combine(backupDir, ".GC-bin", name);
if (File.Exists(target))
{
MoveEntry(target, backup);
replaced.Add((rel, backup));
}
else
{
replaced.Add((rel, null));
}
MoveEntry(file, target);
_log.Info("已更新非本体文件: " + rel, "Updated non-core file: " + rel);
}
}
catch (Exception ex)
{
_log.Warn($"合并 .GC/bin 失败(继续使用已有版本):{ex.Message}",
$"Failed to merge .GC/bin (keeping the existing one): {ex.Message}");
}
}
/// <summary>
/// 把备份里的条目原样搬回安装目录,撤掉新装的内容。
/// <paramref name="BackupPath"/> 为 null 表示这一项是新包里独有的(没有旧版本),
@@ -686,7 +623,7 @@ internal sealed class Applier
/// <summary>
/// 安装目录里不该被更新碰的东西:
/// · .GC —— 模型库、设置、日志、更新目录本身都在这里(只有 bin/ 由 MergeGcBin 单独处理);
/// · .GC —— 模型库、设置、日志、更新目录本身都在这里;
/// · GC-SAVEDOG.exe —— 本进程正在运行,Windows 上无法替换。
/// </summary>
private static bool IsProtected(string name)
@@ -37,11 +37,6 @@
<DebugType>none</DebugType>
</PropertyGroup>
<ItemGroup>
<!-- 应用器测试要直接构造 Applier(internal):只对测试程序集放开可见性 -->
<InternalsVisibleTo Include="GC.Savedog.Tests" />
</ItemGroup>
<ItemGroup>
<!-- 与启动器共用同一份安全实现,避免两套逻辑各说各话。
ManifestLoader 依赖启动器的 RepoVersion 模型,守护进程不需要,排除。 -->
File renamed without changes.
File renamed without changes.
File renamed without changes.
-19
View File
@@ -137,25 +137,6 @@ GC-UI.exe flutter_windows.dll data/{icudtl.dat, app.so, flutter_assets/}
- `Runner.rc` 在 windres 下有两处不兼容:图标用反斜杠相对路径、`VERSION_AS_STRING`
依赖命令行传 `-D` 的转义字符串。脚本生成一份路径与宏都已规整的 rc 副本再编译。
### 交叉编译必须自己嵌 DPI 清单
`windows/runner/CMakeLists.txt` 把 `runner.exe.manifest` 当**源文件**列进 target,
Visual Studio 生成器会把它交给链接器(`/MANIFESTINPUT`)自动嵌入 exe;
但 `buildsh/cross/CMakeLists.txt` 只用 windres 编 `Runner.rc`,CMake 不会做这一步。
结果就是交叉编出来的 `GC-UI.exe` **完全没有清单**:Windows 认为它「DPI 不感知」,
在 125% / 150% 缩放的屏幕上把整块窗口当位图拉伸 —— 界面整体发虚,中文小字最明显。
现在两处都已加固,改这块代码时不要拆掉任何一处:
| 位置 | 做法 |
|---|---|
| `buildsh/cross/CMakeLists.txt` | 往 `Runner.cross.rc` 追加 `1 24 "<abs>/runner.exe.manifest"`(id 1 = CREATEPROCESS_MANIFEST_RESOURCE_ID,type 24 = RT_MANIFEST) |
| `windows/runner/main.cpp` | 建窗之前调 `SetProcessDpiAwarenessContext(PER_MONITOR_AWARE_V2)`,失败依次退到 `SetProcessDpiAwareness` / `SetProcessDPIAware` |
`main.cpp` 那层是兜底:即使清单因为工具链原因没嵌进去,程序自己也会声明 DPI 感知。
验证办法(Windows):`GC-UI.exe` 属性 →「兼容性」里不该出现「替代高 DPI 缩放行为」,
或在 125% 缩放下截图,文字边缘应是锐利的 1.25 倍像素,而不是模糊的插值。
`.gitea/workflows` 里的 `windows` 任务仍然跑在 `windows-latest` 上;若手头只有 macOS/Linux
构建机,可以把该任务的 `runs-on` 换成对应标签,直接复用这套交叉编译脚本,
不再需要 VS Build Tools。
+5 -30
View File
@@ -55,10 +55,6 @@ Windows 与 macOS 用**同一套 Flutter 代码 + 各自的原生 runner**:
### 1. 启动后端
发布版里后端不走独立进程:`GC-BOOT` 直接引用本工程,调用
`BackendServer.Start(args, port)` 在自己进程内托管,发布包因此只有一个 exe
(两个自包含进程会把 60MB 运行时复制两份)。下面的独立运行方式只用于开发调试。
```bash
# 仓库根目录
dotnet run --project GC-UI/backend/GC.UI.Server
@@ -149,35 +145,14 @@ flutter test
# 前后端联调(需要后端正在运行;后端没起时自动跳过)
flutter test test/backend_contract_test.dart
# 生成界面截图到 test/shots/(视觉检查用,不需要后端)
# 生成界面截图到 test/shots/(视觉检查用)
flutter test tool/render_shots_test.dart
```
截图脚本覆盖四个页面(首页 / 下载 / 设置 / 关于),再加一整套外壳与 1024×680 小窗回归:
`test/shots/home.png`、`download.png`、`settings.png`、`about.png`、`shell.png`、
`home-small.png`、`download-small.png`、`settings-small.png`,以及浅色主题的
`home-light.png`、`settings-light.png`。小窗用例会顺带抓布局溢出(RenderFlex overflow)。
四个页面都用预置数据(`initialModels` / `initialSources` / `initialAbout` 等)渲染,
所以**不需要先起后端**。测试环境的字体是 Ahem(所有字都是方块),脚本会显式加载
系统里的 Noto Sans SC / 微软雅黑 / 苹方,并顺带加载 Material 图标字体,中文和图标才正常。
截图必须放在 `runAsync` 里取像素(`toImage` / `toByteData` 走真实引擎管线),
否则 fake async 时钟不推进,每个用例会卡满 10 分钟才超时。
## 界面清晰度(DPI)
`GC-UI.exe` 必须在启动时就声明 DPI 感知,否则 Windows 在 125% / 150% 缩放下会把
整块窗口当位图拉伸,界面看起来「糊」—— 中文小字最先糊。两处保证:
- `windows/runner/runner.exe.manifest`:PerMonitorV2(原生 MSVC 构建由 CMake 自动嵌入)
- `windows/runner/main.cpp`:建窗前再声明一次,依次尝试
`SetProcessDpiAwarenessContext` → `SetProcessDpiAwareness` → `SetProcessDPIAware`
- `buildsh/cross/CMakeLists.txt`:交叉编译时把清单写进 `.rc`(windres 不会自动嵌入)
另外主题里做了两件跟「清晰」有关的事:字体族走
`Segoe UI + Microsoft YaHei UI`(macOS 走苹方)而不是让引擎随意回退;
正文最小 12px、行高固定,中文不再挤成一片。详见
[CI.md 的「交叉编译必须自己嵌 DPI 清单」](CI.md#交叉编译必须自己嵌-dpi-清单)。
截图脚本覆盖四个页面(首页 / 下载 / 设置 / 关于)再加一整套外壳:
`test/shots/home.png`、`download.png`、`settings.png`、`about.png`、`shell.png`。
需要先在本机 17890 端口跑起后端;脚本用 `runAsync` 给真实 HTTP 留出时间,
否则 `flutter_test` 的假时钟会让页面停在加载态。
## 「关于」页展示的技术栈
@@ -4,7 +4,7 @@ namespace GC.UI.Server;
// ---------------------------------------------------------------------------
// 前后端之间的数据契约(HTTP + JSON,camelCase)。
// HTTP 客户端只认这些字段,不认 .NET 类型;后端换实现不影响契约。
// 前端(Flutter)只认这些字段,不认 .NET 类型;后端换实现不影响前端。
// ---------------------------------------------------------------------------
public sealed record HealthDto(
@@ -12,8 +12,7 @@ public sealed record HealthDto(
string Version,
string Platform,
bool UiAvailable,
string? UiError,
string? SessionProof = null);
string? UiError);
public sealed record ModelDto(
string Id,
@@ -123,31 +122,6 @@ public sealed record UpdateCheckDto(
public sealed record ContributorDto(string Name, int Contributions, string? AvatarUrl);
// ---- 用户 API DTO ----
public sealed record RegisterRequest(
string Username,
string Password,
string? CaptchaId = null,
string? Captcha = null);
public sealed record LoginRequest(string Username, string Password);
/// <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>
public sealed record LauncherRedownloadDto(
string State,
string Version,
string Message,
IReadOnlyList<string> Steps);
public sealed record AboutDto(
string AppName,
string Version,
@@ -16,9 +16,9 @@ namespace GC.UI.Server;
/// 模型窗口宿主。
///
/// 为什么渲染这一层留在 .NET:模型 dll 通过 <c>IModelRuntime.CreateView</c> 返回的是
/// Avalonia <see cref="Control"/>,这是模型契约的一部分。换掉渲染栈等于换掉契约,
/// Avalonia <see cref="Control"/>,这是模型契约的一部分。把渲染栈换成 Flutter 等于换掉契约,
/// 所有已发布模型都会失效。所以前后端分离的切法是:
/// · 界面(首页 / 下载 / 设置 / 关于)→ Avalonia 主窗口
/// · 界面(首页 / 下载 / 设置 / 关于)→ Flutter 前端
/// · 模型窗口(模型自带界面)→ 仍由 .NET 承载,前端只发一条「启动模型」的指令
///
/// 这里惰性启动一个没有主窗口的 Avalonia 桌面生命周期,之后所有模型窗口都在它的 UI 线程上创建。
@@ -29,9 +29,7 @@ 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;
private Task<bool>? _startTask;
public AvaloniaHost(AppServices services) => _services = services;
@@ -39,60 +37,56 @@ public sealed class AvaloniaHost
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()
public Task<bool> EnsureStartedAsync()
{
if (Interlocked.Exchange(ref _started, 1) == 1) return;
try
lock (_gate)
{
AppBuilder.Configure<HostApp>()
.UsePlatformDetect()
.AfterSetup(_ =>
{
IsAvailable = true;
_ready.TrySetResult(true);
})
.StartWithClassicDesktopLifetime(Array.Empty<string>());
}
catch (Exception ex)
{
// 无桌面会话(CI / 无头环境):模型窗口不可用,但后端其余接口照常。
LastError = ex.Message;
_ready.TrySetResult(false);
_startTask ??= Task.Run(StartCore);
return _startTask;
}
}
/// <summary>从任意线程请求结束事件循环,使 <see cref="RunOnCurrentThread"/> 返回。</summary>
public void Shutdown()
private bool StartCore()
{
if (_started == 0) return;
try
var ready = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
var thread = new Thread(() =>
{
Dispatcher.UIThread.Post(() =>
try
{
if (Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
desktop.Shutdown();
});
}
catch
AppBuilder.Configure<HostApp>()
.UsePlatformDetect()
.AfterSetup(_ => ready.TrySetResult(true))
.StartWithClassicDesktopLifetime(Array.Empty<string>());
}
catch (Exception ex)
{
LastError = ex.Message;
ready.TrySetResult(false);
}
})
{
// 事件循环尚未建立或已退出:无需处理
IsBackground = true,
Name = "gc-ui-avalonia"
};
// Windows 上 Avalonia 需要 STA 线程;macOS / Linux 不支持也不必要。
if (OperatingSystem.IsWindows())
{
try { thread.SetApartmentState(ApartmentState.STA); }
catch { /* 忽略:部分运行时不允许设置 */ }
}
thread.Start();
if (!ready.Task.Wait(TimeSpan.FromSeconds(30)))
{
LastError = "图形环境初始化超时";
return false;
}
IsAvailable = ready.Task.Result;
return IsAvailable;
}
/// <summary>在 Avalonia UI 线程上加载模型并打开它自己的窗口。</summary>
@@ -3,10 +3,10 @@
<!--
GC-UI 后端:把原来「启动器 = UI + 服务」的一体式结构拆成
· 后端(本工程):模型扫描 / 下载 / 更新 / 设置 / 模型窗口宿主,只暴露本地 HTTP API
· HTTP 客户端:通过 HTTP 调用本后端(可选部署)
· 前端(GC-UI/frontend,Flutter):只做界面,通过 HTTP 调后端
模型渲染由客户端负责:模型不再返回 Avalonia Control,
后端只剩纯 HTTP API,不再依赖任何 UI 框架。
模型窗口仍然由 .NET 侧承载:模型 dll 返回的是 Avalonia Control,
换掉渲染栈等于换掉模型契约,所以「渲染留在 .NET,界面交给 Flutter」是唯一不破坏模型生态的切法。
-->
<PropertyGroup>
<OutputType>Exe</OutputType>
@@ -15,10 +15,16 @@
<RootNamespace>GC.UI.Server</RootNamespace>
<AssemblyName>GC.UI.Server</AssemblyName>
<InvariantGlobalization>false</InvariantGlobalization>
<AvaloniaUseCompiledBindingsByDefault>false</AvaloniaUseCompiledBindingsByDefault>
<!-- 后端是本地伴随进程,不需要浏览器启动配置 / 静态文件 -->
<GenerateDocumentationFile>false</GenerateDocumentationFile>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="Avalonia.Desktop" Version="$(AvaloniaVersion)" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\GC\src\GC.Core.csproj" />
<ProjectReference Include="..\..\..\GC-DOWNLOAD\GC-DOWNLOAD.csproj" />
+665
View File
@@ -0,0 +1,665 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using GC.Download;
using GC.Models;
using GC.Services;
using GC.UI.Server;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
// ---------------------------------------------------------------------------
// GC-UI 后端:本地 HTTP 服务(只监听 127.0.0.1)。
//
// 它把原来 GC 启动器里的服务层原样复用(GC.Core / GC-DOWNLOAD),
// 只是把「界面」从 Avalonia 换成 Flutter —— 前端通过下面这些接口驱动后端。
//
// GET /api/health 健康检查 + 图形环境是否可用
// GET /api/models 已安装模型
// GET /api/models/{id}/preview 模型封面图
// POST /api/models/{id}/launch 启动模型(打开模型自己的窗口)
// DELETE /api/models/{id} 删除模型
// GET /api/settings 读取设置
// POST /api/settings 修改设置(补丁式)
// GET /api/sources 模型源列表
// POST /api/sources/select 双源测速并切到最快
// GET /api/remote/models 远端可下载模型
// POST /api/download 入队下载
// GET /api/download/jobs 下载任务
// POST /api/download/{id}/cancel|retry|remove
// POST /api/download/clear-finished 清除已完成
// POST /api/update/check 检查模型 / 启动器更新
// GET /api/about 版本 + 贡献者
// POST /api/shell/open-folder|open-url 打开目录 / 链接
// ---------------------------------------------------------------------------
var port = ResolvePort(args);
// 下载模块(GC-DOWNLOAD)通过宿主钩子注入,和 GC-BOOT 的做法一致。
DownloadModuleHost.Factory = new DownloadModuleFactory();
var services = AppServices.Create();
var uiHost = new AvaloniaHost(services);
var builder = WebApplication.CreateBuilder(new WebApplicationOptions { Args = args });
builder.Logging.ClearProviders();
builder.WebHost.UseUrls($"http://127.0.0.1:{port}");
// 本地伴随进程:限制请求体大小、关闭 Server 头、收紧超时,减少被本地恶意页面
// 或异常客户端拖垮的攻击面。
builder.WebHost.ConfigureKestrel(options =>
{
options.AddServerHeader = false;
options.Limits.MaxRequestBodySize = 2 * 1024 * 1024;
options.Limits.RequestHeadersTimeout = TimeSpan.FromSeconds(15);
options.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(2);
options.Limits.MaxConcurrentConnections = 64;
});
// 桌面端(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) &&
(uri.Host == "127.0.0.1" || uri.Host == "localhost" || uri.Host == "::1"))
.AllowAnyHeader()
.AllowAnyMethod()));
var app = builder.Build();
app.UseCors();
// 日志与启动器共用 .GC/logs,整条启动链路(启动器 → 后端 → 守护进程)都在同一组文件里。
var logPaths = AppPaths.Discover();
GcLog.Init(logPaths.LogsRoot);
GcLog.Info($"GC-UI 后端启动,监听 127.0.0.1:{port}",
$"GC-UI backend started on 127.0.0.1:{port}");
// 设置白名单 / 标识校验用到的规则(只在本进程内使用)。
var allowedLanguages = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{ "auto", "zh-CN", "en" };
var allowedThemes = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{ "light", "dark", "system" };
var accentHexRegex = new System.Text.RegularExpressions.Regex(
"^#(?:[0-9A-Fa-f]{6})$", System.Text.RegularExpressions.RegexOptions.Compiled);
var safeIdRegex = new System.Text.RegularExpressions.Regex(
"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$", System.Text.RegularExpressions.RegexOptions.Compiled);
// 安全响应头 + Host/Origin 校验(抵御 DNS rebinding 与跨站调用)。
app.Use(async (context, next) =>
{
var headers = context.Response.Headers;
headers["X-Content-Type-Options"] = "nosniff";
headers["X-Frame-Options"] = "DENY";
headers["Referrer-Policy"] = "no-referrer";
headers["Content-Security-Policy"] = "default-src 'none'; frame-ancestors 'none'";
headers["Cache-Control"] = "no-store";
var host = context.Request.Host.Host;
if (!string.Equals(host, "127.0.0.1", StringComparison.OrdinalIgnoreCase) &&
!string.Equals(host, "localhost", StringComparison.OrdinalIgnoreCase) &&
!string.Equals(host, "::1", StringComparison.OrdinalIgnoreCase))
{
context.Response.StatusCode = StatusCodes.Status403Forbidden;
return;
}
var origin = context.Request.Headers.Origin.ToString();
if (!string.IsNullOrEmpty(origin) &&
!(Uri.TryCreate(origin, UriKind.Absolute, out var parsed) &&
(parsed.Host == "127.0.0.1" || parsed.Host == "localhost" || parsed.Host == "::1")))
{
context.Response.StatusCode = StatusCodes.Status403Forbidden;
return;
}
await next();
});
// 写入类接口做简单限流:单 IP 每秒最多 40 次,防止本地脚本刷爆下载/更新。
var writeBuckets =
new System.Collections.Concurrent.ConcurrentDictionary<string, (long Window, int Count)>();
app.Use(async (context, next) =>
{
if (HttpMethods.IsPost(context.Request.Method) ||
HttpMethods.IsDelete(context.Request.Method))
{
var key = context.Connection.RemoteIpAddress?.ToString() ?? "local";
var now = Environment.TickCount64;
// 定期丢弃过期窗口:本机连接数不多,但长时间运行后桶只增不减会缓慢泄漏。
if (writeBuckets.Count > 256)
{
foreach (var entry in writeBuckets)
{
if (now - entry.Value.Window > 60_000)
writeBuckets.TryRemove(entry.Key, out _);
}
}
var bucket = writeBuckets.AddOrUpdate(
key,
_ => (now, 1),
(_, old) => now - old.Window > 1000 ? (now, 1) : (old.Window, old.Count + 1));
if (bucket.Count > 40)
{
context.Response.StatusCode = StatusCodes.Status429TooManyRequests;
await context.Response.WriteAsJsonAsync(ErrorDto.Of("请求过于频繁,请稍后再试"));
return;
}
}
await next();
});
// ---- 健康检查 -------------------------------------------------------------
app.MapGet("/api/health", () => Results.Ok(new HealthDto(
true,
LauncherRuntimeInfo.CurrentLauncherVersion,
LauncherRuntimeInfo.CurrentRid,
uiHost.IsAvailable,
uiHost.LastError)));
// ---- 已安装模型 -----------------------------------------------------------
app.MapGet("/api/models", () =>
Results.Ok(services.Models.Scan().Select(ToModelDto).ToList()));
app.MapGet("/api/models/{id}/preview", (string id, HttpResponse response) =>
{
if (!IsSafeId(id)) return Results.BadRequest(ErrorDto.Of("模型标识无效"));
var package = services.Models.Find(id);
if (package == null || !File.Exists(package.PreviewPath)) return Results.NotFound();
// 封面是静态图,允许前端缓存:默认全局中间件写的 no-store 会让每次滚动都重新请求。
// 按扩展名给准确的 MIME —— 统一写 image/png 时,WebP / JPEG 封面在部分平台显示不出来。
response.Headers.CacheControl = "private, max-age=300";
return Results.File(package.PreviewPath, GuessImageContentType(package.PreviewPath));
});
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}"));
try
{
services.Memory.Refresh();
var message = await uiHost.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) =>
{
if (!IsSafeId(id)) return Results.BadRequest(ErrorDto.Of("模型标识无效"));
var ok = services.Models.Delete(id);
if (ok) services.Models.NotifyChanged();
return ok
? Results.Ok(new LaunchResultDto(true, $"已删除模型 {id}"))
: Results.NotFound(ErrorDto.Of($"没有找到模型 {id}"));
});
// ---- 设置 -----------------------------------------------------------------
app.MapGet("/api/settings", () => Results.Ok(ToSettingsDto()));
app.MapPost("/api/settings", (SettingsPatch? patch) =>
{
if (patch == null) return Results.BadRequest(ErrorDto.Of("缺少设置内容"));
// 白名单校验:设置项会写进磁盘并被前端直接使用,不接受任意字符串。
if (patch.Language != null && !allowedLanguages.Contains(patch.Language))
return Results.BadRequest(ErrorDto.Of("不支持的界面语言"));
if (patch.Theme != null && !allowedThemes.Contains(patch.Theme))
return Results.BadRequest(ErrorDto.Of("不支持的主题"));
if (patch.AccentColor != null && !accentHexRegex.IsMatch(patch.AccentColor))
return Results.BadRequest(ErrorDto.Of("主题色需为 #RRGGBB"));
if (patch.UpdateRepository != null && !IsAllowedRepository(patch.UpdateRepository))
return Results.BadRequest(ErrorDto.Of("更新仓库地址不受信任"));
services.Settings.Apply(s =>
{
if (patch.Language != null) s.Language = patch.Language;
if (patch.Theme != null) s.Theme = patch.Theme;
if (patch.AccentColor != null) s.AccentColor = patch.AccentColor.ToUpperInvariant();
if (patch.RenderFps.HasValue) s.RenderFps = Math.Clamp(patch.RenderFps.Value, 12, 120);
if (patch.MemoryMb.HasValue) s.MemoryMb = Math.Clamp(patch.MemoryMb.Value, 256, 16384);
if (patch.MemoryAuto.HasValue) s.MemoryAuto = patch.MemoryAuto.Value;
if (patch.AutoUpdateOnStartup.HasValue) s.AutoUpdateOnStartup = patch.AutoUpdateOnStartup.Value;
if (patch.RequireSignedManifest.HasValue) s.RequireSignedManifest = patch.RequireSignedManifest.Value;
if (patch.UpdateRepository != null) s.UpdateRepository = patch.UpdateRepository;
if (patch.UpdateLocalRoot != null) s.UpdateLocalRoot = patch.UpdateLocalRoot;
if (patch.ModelRootOverride != null) s.ModelRootOverride = patch.ModelRootOverride;
});
if (patch.Language != null) L.I.SetLanguage(patch.Language);
if (patch.MemoryMb.HasValue || patch.MemoryAuto.HasValue)
services.Memory.ApplyAuto(services.Settings.Current.MemoryAuto, services.Settings.Current.MemoryMb);
return Results.Ok(ToSettingsDto());
});
// ---- 模型源 ---------------------------------------------------------------
app.MapGet("/api/sources", () =>
Results.Ok(services.Settings.Current.Sources.Select(ToSourceDto).ToList()));
app.MapPost("/api/sources/select", async (ForceRequest? request) =>
{
var force = request?.Force ?? false;
try
{
var fastest = await services.Selector.PickFastestAsync(force, CancellationToken.None);
services.Updates.UseRemote(services.DownloadModule.CreateRemote(fastest));
return Results.Ok(new LatencyDto(
fastest.Id, fastest.Name,
services.Selector.LastLatency.TryGetValue(fastest.Id, out var ms) ? ms : 0));
}
catch (Exception ex)
{
Console.Error.WriteLine($"[sources] 切换模型源失败: {ex}");
return Results.Json(ErrorDto.Of("模型源切换失败"), statusCode: 503);
}
});
app.MapGet("/api/remote/models", async (string? sourceId, bool force) =>
{
var source = ResolveSource(sourceId);
if (source == null) return Results.NotFound(ErrorDto.Of("没有可用的模型源"));
var index = await services.Sources.FetchAsync(source, force, null, CancellationToken.None);
var installed = services.Models.Scan()
.ToDictionary(p => p.Id, p => p.Manifest.Version, StringComparer.OrdinalIgnoreCase);
return Results.Ok(new SourceIndexDto(
index.SourceId,
index.Root,
index.FromCache,
index.Error,
index.ResolvedFrom,
index.Models.Select(m => new RemoteModelDto(
m.Id,
m.LocalizedName,
m.LocalizedDescription,
m.Manifest.Version,
m.SizeBytes,
ModelScanner.HumanSize(m.SizeBytes),
m.SourceId,
installed.ContainsKey(m.Id),
installed.TryGetValue(m.Id, out var v) ? v : null)).ToList()));
});
// ---- 下载 -----------------------------------------------------------------
app.MapPost("/api/download", async (DownloadRequest? request) =>
{
if (request == null || string.IsNullOrWhiteSpace(request.ModelId))
return Results.BadRequest(ErrorDto.Of("缺少 modelId"));
var source = ResolveSource(request.SourceId);
if (source == null) return Results.NotFound(ErrorDto.Of("没有可用的模型源"));
var index = await services.Sources.FetchAsync(source, false, null, CancellationToken.None);
var model = index.Models.FirstOrDefault(m =>
m.Id.Equals(request.ModelId, StringComparison.OrdinalIgnoreCase));
if (model == null)
return Results.NotFound(ErrorDto.Of($"源里没有模型 {request.ModelId}"));
var job = services.Downloads.Enqueue(model);
return Results.Ok(ToJobDto(job));
});
app.MapGet("/api/download/jobs", () =>
Results.Ok(services.Downloads.Jobs.Select(ToJobDto).ToList()));
app.MapPost("/api/download/{id}/cancel", (string id) =>
ActOnJob(id, job => services.Downloads.Cancel(job)));
app.MapPost("/api/download/{id}/retry", (string id) =>
ActOnJob(id, job => services.Downloads.Retry(job)));
app.MapPost("/api/download/{id}/remove", (string id) =>
ActOnJob(id, job => services.Downloads.Remove(job)));
app.MapPost("/api/download/clear-finished", () =>
{
services.Downloads.ClearFinished();
return Results.Ok(new LaunchResultDto(true, "已清除完成的任务"));
});
// ---- 更新 -----------------------------------------------------------------
app.MapPost("/api/update/check", async (ForceRequest? request) =>
{
var force = request?.Force ?? true;
var messages = new List<string>();
try
{
var fastest = await services.Selector.PickFastestAsync(force, CancellationToken.None);
services.Updates.UseRemote(services.DownloadModule.CreateRemote(fastest));
}
catch (Exception ex)
{
Console.Error.WriteLine($"[update] 测速失败,沿用当前源: {ex.Message}");
}
string? launcherLatest = null;
try
{
launcherLatest = await services.LauncherUpdates.CheckAsync(
services.Updates.Remote, CancellationToken.None);
}
catch (Exception ex)
{
Console.Error.WriteLine($"[update] 启动器版本检查失败: {ex.Message}");
}
var progress = new Progress<UpdateProgress>(p =>
{
if (!string.IsNullOrWhiteSpace(p.Message)) messages.Add(p.Message);
});
var result = await services.Updates.RunAsync(force, progress, CancellationToken.None);
return Results.Ok(new UpdateCheckDto(
result.Outcome.ToString(),
result.Message,
result.UpdatedModels,
result.ModelNames,
result.LauncherMessage,
result.Error,
launcherLatest,
services.Updates.Remote.DisplayName,
services.Selector.LastLatency
.Select(kv => new LatencyDto(
kv.Key,
SourcePreset.Find(kv.Key)?.Name ?? kv.Key,
kv.Value))
.ToList()));
});
// ---- 关于 -----------------------------------------------------------------
app.MapGet("/api/about", async () =>
{
var repository = services.Settings.Current.UpdateRepository;
var contributors = new List<ContributorDto>();
try
{
foreach (var c in await ContributorsService.FetchAsync(repository, CancellationToken.None))
contributors.Add(new ContributorDto(c.DisplayName, c.Contributions, c.AvatarUrl));
}
catch (Exception ex)
{
Console.Error.WriteLine($"[about] 读取贡献者失败: {ex.Message}");
}
return Results.Ok(new AboutDto(
"Morris GC",
LauncherRuntimeInfo.CurrentLauncherVersion,
LauncherRuntimeInfo.CurrentRid,
repository,
contributors,
// 「关于」页展示的技术栈信息:源码语言与前端框架。
SourceLanguage: "C#",
Frontend: "Flutter"));
});
// ---- 系统集成 -------------------------------------------------------------
app.MapPost("/api/shell/open-folder", (PathRequest? request) =>
{
var path = request?.Path;
if (string.IsNullOrWhiteSpace(path))
return Results.BadRequest(ErrorDto.Of("缺少 path"));
// 只允许打开启动器自己的目录,避免前端被当成任意路径执行器
if (!IsInsideKnownRoot(path!))
return Results.BadRequest(ErrorDto.Of("只允许打开启动器自己的目录"));
Shell.OpenFolder(path!);
return Results.Ok(new LaunchResultDto(true, "已打开目录"));
});
app.MapPost("/api/shell/open-url", (UrlRequest? request) =>
{
var url = request?.Url;
if (string.IsNullOrWhiteSpace(url) || url.Length > 2048 ||
!Uri.TryCreate(url, UriKind.Absolute, out var uri))
return Results.BadRequest(ErrorDto.Of("URL 无效"));
if (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps)
return Results.BadRequest(ErrorDto.Of("只允许 http/https 链接"));
if (!string.IsNullOrEmpty(uri.UserInfo))
return Results.BadRequest(ErrorDto.Of("URL 不允许携带账号密码"));
Shell.OpenUrl(url!);
return Results.Ok(new LaunchResultDto(true, "已打开链接"));
});
// ---- 启动 -----------------------------------------------------------------
WriteEndpointFile(services, port);
Console.WriteLine($"[GC-UI] 后端已启动: http://127.0.0.1:{port}");
Console.WriteLine($"[GC-UI] 模型库: {services.Paths.ModelRoot}");
app.Run();
// ---------------------------------------------------------------------------
// 局部辅助
// ---------------------------------------------------------------------------
static int ResolvePort(string[] args)
{
// 优先用启动器传来的端口(GC_UI_PORT),保证前端拼出来的 baseUrl 和这里一致。
var env = Environment.GetEnvironmentVariable(GcUiContract.PortEnvVar);
if (int.TryParse(env, out var fromEnv) && fromEnv > 0 && fromEnv < 65536) return fromEnv;
for (var i = 0; i < args.Length; i++)
{
if (args[i] == "--port" && i + 1 < args.Length &&
int.TryParse(args[i + 1], out var next) && next > 0 && next < 65536)
return next;
const string prefix = "--port=";
if (args[i].StartsWith(prefix, StringComparison.Ordinal) &&
int.TryParse(args[i][prefix.Length..], out var inline) && inline > 0 && inline < 65536)
return inline;
}
return GcUiContract.DefaultPort;
}
static void WriteEndpointFile(AppServices services, int port)
{
try
{
var file = Path.Combine(services.Paths.HomeRoot, "ui-backend.json");
var payload = JsonSerializer.Serialize(new
{
port,
pid = Environment.ProcessId,
url = $"http://127.0.0.1:{port}",
version = LauncherRuntimeInfo.CurrentLauncherVersion,
platform = LauncherRuntimeInfo.CurrentRid,
startedAt = DateTimeOffset.UtcNow.ToString("o")
}, new JsonSerializerOptions { WriteIndented = true });
File.WriteAllText(file, payload);
}
catch (Exception ex)
{
Console.Error.WriteLine($"[GC-UI] 写入端点文件失败: {ex.Message}");
}
}
/// <summary>按扩展名推断图片 MIME;模型封面允许 png / jpg / webp / gif。</summary>
static string GuessImageContentType(string path) => Path.GetExtension(path).ToLowerInvariant() switch
{
".jpg" or ".jpeg" => "image/jpeg",
".webp" => "image/webp",
".gif" => "image/gif",
".bmp" => "image/bmp",
".svg" => "image/svg+xml",
_ => "image/png"
};
ModelDto ToModelDto(ModelPackage package) => new( package.Id,
package.LocalizedName,
package.LocalizedDescription,
package.Manifest.Version,
package.Manifest.Author,
package.SizeBytes,
ModelScanner.HumanSize(package.SizeBytes),
package.Manifest.Tags ?? new List<string>(),
File.Exists(package.PreviewPath),
$"/api/models/{package.Id}/preview",
package.Directory,
package.DataDirectory);
SourceDto ToSourceDto(ModelSource source) => new(
source.Id,
string.IsNullOrWhiteSpace(source.Name) ? source.Id : source.Name,
source.Url,
source.Enabled,
source.BuiltIn,
source.DisplayHost);
SettingsDto ToSettingsDto() => new(
services.Settings.Current.Language,
services.Settings.Current.Theme,
services.Settings.Current.AccentColor,
services.Settings.Current.RenderFps,
services.Settings.Current.MemoryMb,
services.Settings.Current.MemoryAuto,
services.Settings.Current.AutoUpdateOnStartup,
services.Settings.Current.RequireSignedManifest,
services.Settings.Current.UpdateRepository,
services.Settings.Current.UpdateLocalRoot,
services.Settings.Current.ModelRootOverride,
services.Memory.BudgetMb,
services.Memory.UsageText,
services.Paths.ModelRoot,
services.Paths.DataRoot,
services.Paths.SettingsFile,
LauncherRuntimeInfo.CurrentLauncherVersion,
LauncherRuntimeInfo.CurrentRid,
services.Settings.Current.Sources.Select(ToSourceDto).ToList(),
L.Supported.Select(s => new LanguageDto(s.Code, s.Label)).ToList());
JobDto ToJobDto(IDownloadJob job) => new(
job.Id,
job.Model.Id,
job.Name,
job.Version,
job.State.ToString(),
job.Progress,
job.StatusText,
job.DetailText,
job.Error,
job.IsActive,
job.CanRetry,
job.IsDone);
ModelSource? ResolveSource(string? sourceId)
{
var sources = services.Settings.Current.Sources;
if (!string.IsNullOrWhiteSpace(sourceId))
{
var exact = sources.FirstOrDefault(s =>
s.Id.Equals(sourceId, StringComparison.OrdinalIgnoreCase));
if (exact != null) return exact;
}
return sources.FirstOrDefault(s => s.Enabled && !string.IsNullOrWhiteSpace(s.Url))
?? sources.FirstOrDefault();
}
IResult ActOnJob(string id, Action<IDownloadJob> action)
{
if (!IsSafeId(id)) return Results.BadRequest(ErrorDto.Of("任务标识无效"));
var job = services.Downloads.Jobs.FirstOrDefault(j =>
j.Id.Equals(id, StringComparison.OrdinalIgnoreCase));
if (job == null) return Results.NotFound(ErrorDto.Of($"没有找到任务 {id}"));
action(job);
return Results.Ok(ToJobDto(job));
}
bool IsInsideKnownRoot(string path)
{
try
{
var full = Path.GetFullPath(path);
var roots = new[]
{
services.Paths.ModelRoot,
services.Paths.DataRoot,
services.Paths.HomeRoot,
services.Paths.AppRoot
};
foreach (var root in roots)
{
if (string.IsNullOrWhiteSpace(root)) continue;
var rootFull = Path.GetFullPath(root);
if (full.Equals(rootFull, StringComparison.OrdinalIgnoreCase)) return true;
if (full.StartsWith(rootFull + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
return true;
}
}
catch
{
return false;
}
return false;
}
// 路由标识:只允许字母数字开头,后接字母数字/点/下划线/短横线,长度上限 64。
// 用于模型 id、任务 id,杜绝 `../` 之类的路径穿越尝试。
bool IsSafeId(string? id) => !string.IsNullOrEmpty(id) && safeIdRegex.IsMatch(id);
// 更新仓库地址:必须是 https、不带账号密码、不是回环/内网 IP。
// 防止把本地后端当成 SSRF 跳板去访问内网服务。
bool IsAllowedRepository(string value)
{
if (string.IsNullOrWhiteSpace(value)) return false;
if (!Uri.TryCreate(value, UriKind.Absolute, out var uri)) return false;
if (uri.Scheme != Uri.UriSchemeHttps) return false;
if (!string.IsNullOrEmpty(uri.UserInfo)) return false;
if (string.Equals(uri.Host, "localhost", StringComparison.OrdinalIgnoreCase)) return false;
if (System.Net.IPAddress.TryParse(uri.Host, out var ip) &&
(System.Net.IPAddress.IsLoopback(ip) || IsPrivateAddress(ip)))
return false;
return true;
}
static bool IsPrivateAddress(System.Net.IPAddress ip)
{
var bytes = ip.GetAddressBytes();
if (bytes.Length != 4) return false;
return bytes[0] == 10
|| (bytes[0] == 172 && bytes[1] >= 16 && bytes[1] <= 31)
|| (bytes[0] == 192 && bytes[1] == 168)
|| (bytes[0] == 169 && bytes[1] == 254);
}
+29
View File
@@ -0,0 +1,29 @@
@echo off
REM 构建 GC-UI 前端(Windows 上运行;macOS 请用 build-ui.sh)。
REM
REM GC-UI\build-ui.cmd
setlocal
set ROOT=%~dp0..
set FRONTEND=%ROOT%\GC-UI\frontend
where flutter >nul 2>nul
if errorlevel 1 (
echo 找不到 flutter,请先安装 Flutter SDK 并加入 PATH。
exit /b 1
)
echo ==^> 构建后端(GC.UI.Server)
dotnet build "%ROOT%\GC-UI\backend\GC.UI.Server\GC.UI.Server.csproj" -c Release
if errorlevel 1 exit /b 1
echo ==^> 构建前端(windows)
cd /d "%FRONTEND%"
call flutter pub get
if errorlevel 1 exit /b 1
call flutter build windows --release
if errorlevel 1 exit /b 1
echo ==^> 完成
echo 产物: %FRONTEND%\build\windows\x64\runner\Release\
endlocal
+37
View File
@@ -0,0 +1,37 @@
#!/usr/bin/env bash
# 构建 GC-UI 前端(macOS / Linux 上运行;Windows 请用 build-ui.cmd)。
#
# ./GC-UI/build-ui.sh # 构建当前平台
# ./GC-UI/build-ui.sh macos # 指定目标
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
FRONTEND="$ROOT/GC-UI/frontend"
TARGET="${1:-}"
if ! command -v flutter >/dev/null 2>&1; then
echo "找不到 flutter,请先安装 Flutter SDK 并加入 PATH。" >&2
exit 1
fi
if [ -z "$TARGET" ]; then
case "$(uname -s)" in
Darwin) TARGET="macos" ;;
*) TARGET="macos" ;;
esac
fi
echo "==> 构建后端(GC.UI.Server)"
dotnet build "$ROOT/GC-UI/backend/GC.UI.Server/GC.UI.Server.csproj" -c Release
echo "==> 构建前端($TARGET)"
cd "$FRONTEND"
flutter pub get
flutter build "$TARGET" --release
echo "==> 完成"
case "$TARGET" in
macos) echo "产物: $FRONTEND/build/macos/Build/Products/Release/" ;;
windows) echo "产物: $FRONTEND/build/windows/x64/runner/Release/" ;;
*) echo "产物: $FRONTEND/build/$TARGET/" ;;
esac
+43
View File
@@ -0,0 +1,43 @@
# Miscellaneous
*.class
*.log
*.pyc
*.swp
.DS_Store
.atom/
.buildlog/
.history
.svn/
migrate_working_dir/
# IntelliJ related
*.iml
*.ipr
*.iws
.idea/
# The .vscode folder contains launch configuration and tasks you configure in
# VS Code which you may wish to be included in version control, so this line
# is commented out by default.
#.vscode/
# Flutter/Dart/Pub related
**/doc/api/
**/ios/Flutter/.last_build_id
.dart_tool/
.flutter-plugins
.flutter-plugins-dependencies
.pub-cache/
.pub/
/build/
# Symbolication related
app.*.symbols
# Obfuscation related
app.*.map.json
# Android Studio will place build artifacts here
/android/app/debug
/android/app/profile
/android/app/release
+36
View File
@@ -0,0 +1,36 @@
# This file tracks properties of this Flutter project.
# Used by Flutter tool to assess capabilities and perform upgrades etc.
#
# This file should be version controlled and should not be manually edited.
version:
revision: "dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668"
channel: "stable"
project_type: app
# Tracks metadata for the flutter migrate command
migration:
platforms:
- platform: root
create_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
base_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
- platform: linux
create_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
base_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
- platform: macos
create_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
base_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
- platform: windows
create_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
base_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
# User provided section
# List of Local paths (relative to this file) that should be
# ignored by the migrate tool.
#
# Files that are not part of the templates will be ignored by default.
unmanaged_files:
- 'lib/main.dart'
- 'ios/Runner.xcodeproj/project.pbxproj'
+16
View File
@@ -0,0 +1,16 @@
# gc_ui
GC launcher UI (Flutter frontend)
## Getting Started
This project is a starting point for a Flutter application.
A few resources to get you started if this is your first Flutter project:
- [Lab: Write your first Flutter app](https://docs.flutter.dev/get-started/codelab)
- [Cookbook: Useful Flutter samples](https://docs.flutter.dev/cookbook)
For help getting started with Flutter development, view the
[online documentation](https://docs.flutter.dev/), which offers tutorials,
samples, guidance on mobile development, and a full API reference.
+28
View File
@@ -0,0 +1,28 @@
# This file configures the analyzer, which statically analyzes Dart code to
# check for errors, warnings, and lints.
#
# The issues identified by the analyzer are surfaced in the UI of Dart-enabled
# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be
# invoked from the command line by running `flutter analyze`.
# The following line activates a set of recommended lints for Flutter apps,
# packages, and plugins designed to encourage good coding practices.
include: package:flutter_lints/flutter.yaml
linter:
# The lint rules applied to this project can be customized in the
# section below to disable rules from the `package:flutter_lints/flutter.yaml`
# included above or to enable additional rules. A list of all available lints
# and their documentation is published at https://dart.dev/lints.
#
# Instead of disabling a lint rule for the entire project in the
# section below, it can also be suppressed for a single line of code
# or a specific dart file by using the `// ignore: name_of_lint` and
# `// ignore_for_file: name_of_lint` syntax on the line or in the file
# producing the lint.
rules:
# avoid_print: false # Uncomment to disable the `avoid_print` rule
# prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule
# Additional information about this file can be found at
# https://dart.dev/guides/language/analysis-options
+521
View File
@@ -0,0 +1,521 @@
import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;
/// 后端返回的错误(HTTP 非 2xx,或后端明确返回 ok=false)。
class ApiException implements Exception {
ApiException(this.message, {this.statusCode});
final String message;
final int? statusCode;
@override
String toString() => message;
}
/// 已安装模型。
class ModelInfo {
ModelInfo.fromJson(Map<String, dynamic> json)
: id = json['id'] as String? ?? '',
name = json['name'] as String? ?? '',
description = json['description'] as String? ?? '',
version = json['version'] as String? ?? '',
author = json['author'] as String? ?? '',
sizeBytes = (json['sizeBytes'] as num?)?.toInt() ?? 0,
sizeText = json['sizeText'] as String? ?? '',
tags = _stringList(json['tags']),
hasPreview = json['hasPreview'] as bool? ?? false,
previewUrl = json['previewUrl'] as String? ?? '',
directory = json['directory'] as String? ?? '',
dataDirectory = json['dataDirectory'] as String? ?? '';
final String id;
final String name;
final String description;
final String version;
final String author;
final int sizeBytes;
final String sizeText;
final List<String> tags;
final bool hasPreview;
final String previewUrl;
final String directory;
final String dataDirectory;
String get metaText => 'v$version · $sizeText';
}
/// 模型源。
class SourceInfo {
SourceInfo.fromJson(Map<String, dynamic> json)
: id = json['id'] as String? ?? '',
name = json['name'] as String? ?? '',
url = json['url'] as String? ?? '',
enabled = json['enabled'] as bool? ?? false,
builtIn = json['builtIn'] as bool? ?? false,
host = json['host'] as String? ?? '';
final String id;
final String name;
final String url;
final bool enabled;
final bool builtIn;
final String host;
}
/// 远端可下载模型。
class RemoteModelInfo {
RemoteModelInfo.fromJson(Map<String, dynamic> json)
: id = json['id'] as String? ?? '',
name = json['name'] as String? ?? '',
description = json['description'] as String? ?? '',
version = json['version'] as String? ?? '',
sizeBytes = (json['sizeBytes'] as num?)?.toInt() ?? 0,
sizeText = json['sizeText'] as String? ?? '',
sourceId = json['sourceId'] as String? ?? '',
installed = json['installed'] as bool? ?? false,
installedVersion = json['installedVersion'] as String?;
final String id;
final String name;
final String description;
final String version;
final int sizeBytes;
final String sizeText;
final String sourceId;
final bool installed;
final String? installedVersion;
}
/// 一次远端源索引结果。
class SourceIndexInfo {
SourceIndexInfo.fromJson(Map<String, dynamic> json)
: sourceId = json['sourceId'] as String? ?? '',
root = json['root'] as String? ?? '',
fromCache = json['fromCache'] as bool? ?? false,
error = json['error'] as String?,
resolvedFrom = json['resolvedFrom'] as String? ?? '',
models = (json['models'] as List<dynamic>? ?? const [])
.map((e) => RemoteModelInfo.fromJson(e as Map<String, dynamic>))
.toList();
final String sourceId;
final String root;
final bool fromCache;
final String? error;
final String resolvedFrom;
final List<RemoteModelInfo> models;
}
/// 下载任务。
class JobInfo {
JobInfo.fromJson(Map<String, dynamic> json)
: id = json['id'] as String? ?? '',
modelId = json['modelId'] as String? ?? '',
name = json['name'] as String? ?? '',
version = json['version'] as String? ?? '',
state = json['state'] as String? ?? 'Queued',
progress = (json['progress'] as num?)?.toDouble() ?? 0,
statusText = json['statusText'] as String? ?? '',
detailText = json['detailText'] as String? ?? '',
error = json['error'] as String?,
isActive = json['isActive'] as bool? ?? false,
canRetry = json['canRetry'] as bool? ?? false,
isDone = json['isDone'] as bool? ?? false;
final String id;
final String modelId;
final String name;
final String version;
final String state;
final double progress;
final String statusText;
final String detailText;
final String? error;
final bool isActive;
final bool canRetry;
final bool isDone;
}
/// 界面语言选项。
class LanguageInfo {
LanguageInfo.fromJson(Map<String, dynamic> json)
: code = json['code'] as String? ?? '',
label = json['label'] as String? ?? '';
final String code;
final String label;
}
/// 设置。
class SettingsInfo {
SettingsInfo.fromJson(Map<String, dynamic> json)
: language = json['language'] as String? ?? 'auto',
theme = json['theme'] as String? ?? 'light',
accentColor = json['accentColor'] as String? ?? '#8FB6FF',
renderFps = (json['renderFps'] as num?)?.toInt() ?? 120,
memoryMb = (json['memoryMb'] as num?)?.toInt() ?? 2048,
memoryAuto = json['memoryAuto'] as bool? ?? true,
autoUpdateOnStartup = json['autoUpdateOnStartup'] as bool? ?? true,
requireSignedManifest = json['requireSignedManifest'] as bool? ?? true,
updateRepository = json['updateRepository'] as String? ?? '',
updateLocalRoot = json['updateLocalRoot'] as String?,
modelRootOverride = json['modelRootOverride'] as String?,
memoryBudgetMb = (json['memoryBudgetMb'] as num?)?.toInt() ?? 0,
memoryUsageText = json['memoryUsageText'] as String? ?? '',
modelRoot = json['modelRoot'] as String? ?? '',
dataRoot = json['dataRoot'] as String? ?? '',
settingsFile = json['settingsFile'] as String? ?? '',
version = json['version'] as String? ?? '',
platform = json['platform'] as String? ?? '',
sources = (json['sources'] as List<dynamic>? ?? const [])
.map((e) => SourceInfo.fromJson(e as Map<String, dynamic>))
.toList(),
languages = (json['languages'] as List<dynamic>? ?? const [])
.map((e) => LanguageInfo.fromJson(e as Map<String, dynamic>))
.toList();
final String language;
final String theme;
final String accentColor;
final int renderFps;
final int memoryMb;
final bool memoryAuto;
final bool autoUpdateOnStartup;
final bool requireSignedManifest;
final String updateRepository;
final String? updateLocalRoot;
final String? modelRootOverride;
final int memoryBudgetMb;
final String memoryUsageText;
final String modelRoot;
final String dataRoot;
final String settingsFile;
final String version;
final String platform;
final List<SourceInfo> sources;
final List<LanguageInfo> languages;
}
/// 设置补丁:只提交要改的字段。
class SettingsPatch {
const SettingsPatch({
this.language,
this.theme,
this.accentColor,
this.renderFps,
this.memoryMb,
this.memoryAuto,
this.autoUpdateOnStartup,
this.requireSignedManifest,
this.updateRepository,
this.updateLocalRoot,
this.modelRootOverride,
});
final String? language;
final String? theme;
final String? accentColor;
final int? renderFps;
final int? memoryMb;
final bool? memoryAuto;
final bool? autoUpdateOnStartup;
final bool? requireSignedManifest;
final String? updateRepository;
final String? updateLocalRoot;
final String? modelRootOverride;
Map<String, dynamic> toJson() {
final map = <String, dynamic>{};
if (language != null) map['language'] = language;
if (theme != null) map['theme'] = theme;
if (accentColor != null) map['accentColor'] = accentColor;
if (renderFps != null) map['renderFps'] = renderFps;
if (memoryMb != null) map['memoryMb'] = memoryMb;
if (memoryAuto != null) map['memoryAuto'] = memoryAuto;
if (autoUpdateOnStartup != null) map['autoUpdateOnStartup'] = autoUpdateOnStartup;
if (requireSignedManifest != null) map['requireSignedManifest'] = requireSignedManifest;
if (updateRepository != null) map['updateRepository'] = updateRepository;
if (updateLocalRoot != null) map['updateLocalRoot'] = updateLocalRoot;
if (modelRootOverride != null) map['modelRootOverride'] = modelRootOverride;
return map;
}
}
/// 健康检查。
class HealthInfo {
HealthInfo.fromJson(Map<String, dynamic> json)
: ok = json['ok'] as bool? ?? false,
version = json['version'] as String? ?? '',
platform = json['platform'] as String? ?? '',
uiAvailable = json['uiAvailable'] as bool? ?? false,
uiError = json['uiError'] as String?;
final bool ok;
final String version;
final String platform;
final bool uiAvailable;
final String? uiError;
}
/// 一次更新检查的结果。
class UpdateCheckInfo {
UpdateCheckInfo.fromJson(Map<String, dynamic> json)
: outcome = json['outcome'] as String? ?? '',
message = json['message'] as String? ?? '',
updatedModels = (json['updatedModels'] as num?)?.toInt() ?? 0,
modelNames = _stringList(json['modelNames']),
launcherMessage = json['launcherMessage'] as String?,
error = json['error'] as String?,
launcherLatest = json['launcherLatest'] as String?,
sourceName = json['sourceName'] as String? ?? '';
final String outcome;
final String message;
final int updatedModels;
final List<String> modelNames;
final String? launcherMessage;
final String? error;
final String? launcherLatest;
final String sourceName;
}
/// 贡献者。
class ContributorInfo {
ContributorInfo.fromJson(Map<String, dynamic> json)
: name = json['name'] as String? ?? '',
contributions = (json['contributions'] as num?)?.toInt() ?? 0,
avatarUrl = json['avatarUrl'] as String?;
final String name;
final int contributions;
final String? avatarUrl;
}
/// 关于页数据。
class AboutInfo {
AboutInfo.fromJson(Map<String, dynamic> json)
: appName = json['appName'] as String? ?? '',
version = json['version'] as String? ?? '',
platform = json['platform'] as String? ?? '',
repository = json['repository'] as String? ?? '',
sourceLanguage = json['sourceLanguage'] as String? ?? 'C#',
frontend = json['frontend'] as String? ?? 'Flutter',
contributors = (json['contributors'] as List<dynamic>? ?? const [])
.map((e) => ContributorInfo.fromJson(e as Map<String, dynamic>))
.toList();
final String appName;
final String version;
final String platform;
final String repository;
/// 源码语言(后端 / 模型层),由后端 `/api/about` 返回。
final String sourceLanguage;
/// 前端框架,由后端 `/api/about` 返回。
final String frontend;
final List<ContributorInfo> contributors;
}
/// 通用操作结果。
class ActionResult {
ActionResult.fromJson(Map<String, dynamic> json)
: ok = json['ok'] as bool? ?? false,
message = json['message'] as String? ?? '';
final bool ok;
final String message;
}
List<String> _stringList(dynamic value) =>
(value as List<dynamic>? ?? const []).map((e) => e.toString()).toList();
/// GC-UI 后端客户端。
///
/// 后端是本地伴随进程,端口由启动器(GC-BOOT)选定后通过 `GC_UI_PORT`
/// 环境变量传进来 —— 这样端口被占用时换端口不用重新编译前端。
/// 也可用 `--dart-define=GC_UI_BASE_URL=http://127.0.0.1:12345` 强制指定。
class GcApi {
GcApi({String? baseUrl})
: baseUrl = baseUrl ?? defaultBaseUrl;
/// 复用同一个 HTTP 连接:轮询(下载任务每秒一次)时每次都新建连接
/// 会不断握手,桌面端也能明显看到延迟抖动。
static final http.Client _client = http.Client();
/// 兜底默认端口,与后端 GC.Services.GcUiContract.DefaultPort 保持一致。
static const int fallbackPort = 17890;
static String get defaultBaseUrl {
const fromDefine = String.fromEnvironment('GC_UI_BASE_URL');
if (fromDefine.isNotEmpty) return fromDefine;
final fromEnvUrl = Platform.environment['GC_UI_BASE_URL'];
if (fromEnvUrl != null && fromEnvUrl.isNotEmpty) return fromEnvUrl;
// 启动器通过 GC_UI_PORT 传端口(主路径)。
final port = int.tryParse(Platform.environment['GC_UI_PORT'] ?? '');
if (port != null) return 'http://127.0.0.1:$port';
// 手动起后端 / 前端调试时没有环境变量:读后端写的 .GC/ui-backend.json。
final discovered = _endpointFileUrl();
if (discovered != null) return discovered;
return 'http://127.0.0.1:$fallbackPort';
}
/// 从运行目录下的 `.GC/ui-backend.json` 发现后端地址。
///
/// 后端每次启动都会写这个文件(port / pid / url)。只认 24 小时内的记录:
/// 更早的多半是上次遗留的,连过去只会得到一个「无法连接」。
static String? _endpointFileUrl() {
try {
final file = File('${Directory.current.path}/.GC/ui-backend.json');
if (!file.existsSync()) return null;
final age = DateTime.now().difference(file.lastModifiedSync());
if (age.inHours >= 24) return null;
final decoded = jsonDecode(file.readAsStringSync());
if (decoded is! Map<String, dynamic>) return null;
final url = decoded['url'];
if (url is String && url.startsWith('http://127.0.0.1:')) return url;
final port = (decoded['port'] as num?)?.toInt();
if (port != null && port > 0 && port < 65536) {
return 'http://127.0.0.1:$port';
}
} catch (_) {
// 文件损坏 / 无权限:退回默认端口即可
}
return null;
}
final String baseUrl;
Uri _uri(String path, [Map<String, String>? query]) =>
Uri.parse('$baseUrl$path').replace(queryParameters: query);
Future<dynamic> _send(String method, String path,
{Map<String, String>? query, Object? body}) async {
final uri = _uri(path, query);
late http.Response response;
try {
switch (method) {
case 'GET':
response = await _client.get(uri).timeout(const Duration(seconds: 30));
break;
case 'POST':
response = await _client
.post(uri,
headers: const {'Content-Type': 'application/json'},
body: body == null ? null : jsonEncode(body))
.timeout(const Duration(seconds: 120));
break;
case 'DELETE':
response = await _client.delete(uri).timeout(const Duration(seconds: 30));
break;
default:
throw ApiException('不支持的方法 $method');
}
} on ApiException {
rethrow;
} catch (error) {
throw ApiException('无法连接后端($baseUrl):$error');
}
final text = utf8.decode(response.bodyBytes);
dynamic decoded;
if (text.isNotEmpty) {
try {
decoded = jsonDecode(text);
} catch (_) {
decoded = null;
}
}
if (response.statusCode >= 400) {
final message = decoded is Map<String, dynamic>
? (decoded['message'] as String? ?? 'HTTP ${response.statusCode}')
: 'HTTP ${response.statusCode}';
throw ApiException(message, statusCode: response.statusCode);
}
return decoded;
}
List<Map<String, dynamic>> _asList(dynamic value) =>
(value as List<dynamic>? ?? const [])
.map((e) => e as Map<String, dynamic>)
.toList();
Future<HealthInfo> health() async =>
HealthInfo.fromJson(await _send('GET', '/api/health') as Map<String, dynamic>);
Future<List<ModelInfo>> models() async =>
_asList(await _send('GET', '/api/models')).map(ModelInfo.fromJson).toList();
Future<ActionResult> launchModel(String id) async => ActionResult.fromJson(
await _send('POST', '/api/models/$id/launch') as Map<String, dynamic>);
Future<ActionResult> deleteModel(String id) async => ActionResult.fromJson(
await _send('DELETE', '/api/models/$id') as Map<String, dynamic>);
Future<SettingsInfo> settings() async =>
SettingsInfo.fromJson(await _send('GET', '/api/settings') as Map<String, dynamic>);
Future<SettingsInfo> saveSettings(SettingsPatch patch) async =>
SettingsInfo.fromJson(await _send('POST', '/api/settings', body: patch.toJson())
as Map<String, dynamic>);
Future<List<SourceInfo>> sources() async =>
_asList(await _send('GET', '/api/sources')).map(SourceInfo.fromJson).toList();
Future<SourceIndexInfo> remoteModels({String? sourceId, bool force = false}) async =>
SourceIndexInfo.fromJson(await _send('GET', '/api/remote/models', query: {
if (sourceId != null) 'sourceId': sourceId,
'force': force.toString(),
}) as Map<String, dynamic>);
Future<List<JobInfo>> jobs() async =>
_asList(await _send('GET', '/api/download/jobs')).map(JobInfo.fromJson).toList();
Future<JobInfo> startDownload(String sourceId, String modelId) async =>
JobInfo.fromJson(await _send('POST', '/api/download',
body: {'sourceId': sourceId, 'modelId': modelId}) as Map<String, dynamic>);
Future<JobInfo> cancelJob(String id) async => JobInfo.fromJson(
await _send('POST', '/api/download/$id/cancel') as Map<String, dynamic>);
Future<JobInfo> retryJob(String id) async => JobInfo.fromJson(
await _send('POST', '/api/download/$id/retry') as Map<String, dynamic>);
Future<JobInfo> removeJob(String id) async => JobInfo.fromJson(
await _send('POST', '/api/download/$id/remove') as Map<String, dynamic>);
Future<ActionResult> clearFinished() async => ActionResult.fromJson(
await _send('POST', '/api/download/clear-finished') as Map<String, dynamic>);
Future<UpdateCheckInfo> checkUpdate({bool force = true}) async =>
UpdateCheckInfo.fromJson(
await _send('POST', '/api/update/check', body: {'force': force})
as Map<String, dynamic>);
Future<AboutInfo> about() async =>
AboutInfo.fromJson(await _send('GET', '/api/about') as Map<String, dynamic>);
Future<ActionResult> openFolder(String path) async => ActionResult.fromJson(
await _send('POST', '/api/shell/open-folder', body: {'path': path})
as Map<String, dynamic>);
Future<ActionResult> openUrl(String url) async => ActionResult.fromJson(
await _send('POST', '/api/shell/open-url', body: {'url': url})
as Map<String, dynamic>);
/// 模型封面图地址(直接给 Image.network 用)。
String previewUrl(ModelInfo model) => '$baseUrl${model.previewUrl}';
}
+187
View File
@@ -0,0 +1,187 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'api_client.dart';
import 'i18n.dart';
import 'theme.dart';
/// 外壳状态:后端客户端 + 设置 + 健康状态 + 更新状态条。
///
/// 各页面只读这里的数据、通过这里的方法改后端,避免每页各持一份状态。
class ShellController extends ChangeNotifier {
ShellController({GcApi? api}) : api = api ?? GcApi();
final GcApi api;
int index = 0;
SettingsInfo? settings;
HealthInfo? health;
String? loadError;
bool updateBarVisible = false;
bool updateBusy = false;
double updateProgress = 0;
String updateStatus = '';
String updateDetail = '';
String launcherNotice = '';
/// 模型库版本号:安装 / 删除 / 下载完成后自增,首页据此重新拉列表。
///
/// 首页被 `Offstage` 保活,切走再切回不会重建;没有这个信号时,
/// 下载完模型回到首页仍然显示旧的空列表。
int modelsRevision = 0;
Timer? _retryTimer;
int _retryAttempt = 0;
bool get backendReady => settings != null;
Future<void> bootstrap() async {
_retryTimer?.cancel();
HealthInfo? healthResult;
SettingsInfo? settingsResult;
Object? firstError;
// 两个请求互不依赖,并行发;各自捕获异常,避免一方失败时
// 另一个的 Future 抛成未处理异常(Flutter 会在控制台打出恶性警告)。
await Future.wait<void>(<Future<void>>[
() async {
try {
healthResult = await api.health();
} catch (error) {
firstError ??= error;
}
}(),
() async {
try {
settingsResult = await api.settings();
} catch (error) {
firstError ??= error;
}
}(),
]);
if (healthResult != null) health = healthResult;
if (settingsResult != null) {
settings = settingsResult;
_applySettings(settingsResult!);
}
if (firstError != null && settingsResult == null) {
loadError = firstError.toString();
_scheduleRetry();
} else {
loadError = null;
_retryAttempt = 0;
}
notifyListeners();
}
/// 后端没起来时自动重试(2s、4s、8s…最多 5 次),不必让用户手动点。
void _scheduleRetry() {
if (_retryAttempt >= 5) return;
final seconds = 1 << _retryAttempt; // 1,2,4,8,16
_retryAttempt++;
_retryTimer?.cancel();
_retryTimer = Timer(Duration(seconds: seconds), () {
if (settings == null) bootstrap();
});
}
void _applySettings(SettingsInfo value) {
I18n.setLanguage(value.language);
GcPalette.apply(value.accentColor);
GcPalette.applyTheme(value.theme);
}
void goTo(int value) {
if (index == value) return;
index = value;
notifyListeners();
}
/// 模型库有变化(安装 / 删除 / 下载完成):通知首页刷新。
void modelsChanged() {
modelsRevision++;
notifyListeners();
}
Future<void> reloadSettings() async {
try {
settings = await api.settings();
loadError = null;
_applySettings(settings!);
} catch (error) {
loadError = error.toString();
}
notifyListeners();
}
Future<void> saveSettings(SettingsPatch patch) async {
try {
settings = await api.saveSettings(patch);
loadError = null;
_applySettings(settings!);
} catch (error) {
loadError = error.toString();
}
notifyListeners();
}
void setUpdateStatus({
bool? visible,
bool? busy,
double? progress,
String? status,
String? detail,
String? notice,
}) {
if (visible != null) updateBarVisible = visible;
if (busy != null) updateBusy = busy;
if (progress != null) updateProgress = progress;
if (status != null) updateStatus = status;
if (detail != null) updateDetail = detail;
if (notice != null) launcherNotice = notice;
notifyListeners();
}
/// 检查模型 / 启动器更新(设置页与状态条共用)。
Future<void> checkUpdate({bool force = true}) async {
if (updateBusy) return;
setUpdateStatus(
visible: true,
busy: true,
progress: 0,
status: T('update.checking'),
detail: '',
notice: '',
);
try {
final result = await api.checkUpdate(force: force);
setUpdateStatus(
busy: false,
progress: 1,
status: result.message.isEmpty ? T('update.done') : result.message,
detail: result.error ?? '',
notice: result.launcherMessage ?? '',
);
if (result.updatedModels > 0) modelsChanged();
} catch (error) {
setUpdateStatus(
busy: false,
status: T('update.offline'),
detail: error.toString(),
);
}
}
@override
void dispose() {
_retryTimer?.cancel();
super.dispose();
}
}
+300
View File
@@ -0,0 +1,300 @@
import 'package:flutter/widgets.dart';
/// 轻量 i18n:键值表 + 运行时切换,和后端 `GC/src/Assets/i18n/*.json` 的键保持一致。
class I18n {
I18n._();
static const List<String> supported = <String>['zh-CN', 'en'];
static final ValueNotifier<String> language = ValueNotifier<String>('zh-CN');
static const Map<String, Map<String, String>> _tables = <String, Map<String, String>>{
'zh-CN': <String, String>{
'app.name': 'Morris GC',
'app.tagline': '天文教学模型 · 可视化启动器',
'nav.home': '主页',
'nav.download': '下载',
'nav.settings': '设置',
'nav.about': '关于',
'home.title': '模型库',
'home.subtitle': '选择模型,用可交互的三维演示讲清自转、公转与四季成因。',
'home.launch': '启动模型',
'home.download': '下载模型',
'home.settings': '设置',
'home.installed': '已安装模型',
'home.count': '{0} 个模型',
'home.noDescription': '暂无简介',
'home.empty': '模型库还是空的',
'home.emptyHint': '启动时会自动检查并下载模型。若当前断网:可把模型文件夹放进 .GC/model/ 后重新打开,或联网后在「下载」页点重试。',
'home.emptyAction': '去下载模型',
'home.open': '打开目录',
'home.delete': '删除',
'home.deleteConfirm': '删除模型「{0}」?模型文件会从本地模型库移除。',
'home.stats.models': '已安装',
'home.stats.sources': '模型源',
'home.stats.memory': '内存预算',
'home.recent': '选择模型后点击「启动模型」',
'home.launchHint': '模型在自己的窗口里运行,可播放/暂停、切换视角并使用教学要点。',
'dl.title': '下载模型',
'dl.subtitle': '从内置模型源读取可下载模型;模型源在「设置」里查看。',
'dl.sources': '模型源',
'dl.refresh': '刷新',
'dl.available': '可用模型',
'dl.download': '下载',
'dl.installed': '已安装',
'dl.reinstall': '重新下载',
'dl.background': '后台任务',
'dl.bgEmpty': '暂无后台任务',
'dl.cancel': '取消',
'dl.retry': '重试',
'dl.clearDone': '清除已完成',
'dl.removeTask': '移除',
'dl.status.queued': '排队中',
'dl.status.downloading': '下载中',
'dl.status.done': '已完成',
'dl.status.failed': '失败',
'dl.status.canceled': '已取消',
'dl.empty': '这个源里没有模型',
'dl.emptyHint': '仓库需要包含 model/<模型ID>/<模型ID>.json 结构',
'dl.syncing': '正在读取模型源…',
'dl.ready': '共 {0} 个模型',
'dl.fromCache': '本地缓存',
'dl.pickSource': '选择一个模型源,查看可下载的模型',
'set.title': '设置',
'set.subtitle': '模型源、启动时内存分配与本地存储。',
'set.general': '通用',
'set.appearance': '外观',
'set.theme': '主题模式',
'set.theme.desc': '深色、浅色,或跟随系统设置。',
'set.theme.dark': '深色',
'set.theme.light': '浅色',
'set.theme.system': '跟随系统',
'set.accent': '主题颜色',
'set.accent.desc': '选择启动器的主色调,按钮、滑块与高亮会同步换色。',
'set.accent.custom': '自定义颜色',
'set.accent.hexHint': '格式 #RRGGBB,例如 #8FB6FF',
'set.accent.invalid': '颜色格式无效,请使用 #RRGGBB',
'set.language': '界面语言',
'set.language.auto': '跟随系统',
'set.fps': '渲染帧率',
'set.fps.desc': '越高越顺滑,CPU 占用也越高。',
'set.memory': '启动时运行内存分配',
'set.memory.desc': '启动器把这份预算交给模型:模型自己决定用它缓存多少数据(贴图分辨率、缓冲等)。',
'set.memory.current': '当前占用',
'set.memory.auto': '自动(根据设备内存分配)',
'set.memory.hint': '建议 2048 MB 以上,低配设备可选 1024 MB。',
'set.sources': '模型源',
'set.sources.desc': '停用的模型源不会出现在下载页。',
'set.sourceEnabled': '启用',
'set.storage': '存储',
'set.modelDir': '模型库目录',
'set.dataDir': '数据目录',
'set.openFolder': '打开文件夹',
'set.clearCache': '清理缓存',
'set.cacheCleared': '缓存已清理',
'set.about': '关于',
'set.version': '版本',
'set.platform': '平台',
'set.license': '许可',
'set.licenseValue': 'MIT',
'set.checkUpdate': '检查更新',
'set.checkUpdate.desc': '启动时自动检查模型与启动器是否为最新版。',
'set.backend': '后端服务',
'set.backend.desc': '界面(Flutter)与后端(.NET)分离,后端只监听本机回环地址。',
'set.backend.ui': '模型窗口宿主',
'set.backend.uiOk': '可用',
'set.backend.uiBad': '不可用',
'update.title': '自动更新',
'update.auto': '启动时自动检查更新',
'update.checkNow': '检查更新',
'update.source': '更新源',
'update.lastCheck': '上次检查',
'update.never': '尚未检查',
'update.none': '无',
'update.checking': '正在检查更新…',
'update.offline': '暂时无法连接更新服务器,继续使用本地模型',
'update.noChange': '模型与启动器均为最新版',
'update.applied': '已更新 {0} 个模型,立即生效',
'update.done': '更新检查完成',
'update.pendingReady': '启动器新版 {0} 已就绪,下次启动生效',
'common.cancel': '取消',
'common.confirm': '确定',
'common.delete': '删除',
'common.close': '关闭',
'common.open': '打开',
'common.applied': '已应用',
'common.confirmTitle': '请确认',
'common.retry': '重试',
'common.loading': '加载中…',
'common.error': '出错了',
'common.refresh': '刷新',
'about.developers': '开发者',
'about.contributorsHint': '来自仓库提交记录',
'about.repository': '仓库',
'about.openRepository': '打开仓库',
'about.contributions': '{0} 次提交',
'about.noContributors': '暂无贡献者信息',
'about.architecture': '架构',
'about.architectureValue': 'Flutter 前端 + .NET 后端(本地 HTTP)',
'about.sourceLanguage': '源码语言',
'about.frontend': '前端',
},
'en': <String, String>{
'app.name': 'Morris GC',
'app.tagline': 'Astronomy teaching models · visual launcher',
'nav.home': 'Home',
'nav.download': 'Download',
'nav.settings': 'Settings',
'nav.about': 'About',
'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',
'home.download': 'Get models',
'home.settings': 'Settings',
'home.installed': 'Installed models',
'home.count': '{0} models',
'home.noDescription': 'No description',
'home.empty': 'No models yet',
'home.emptyHint': 'Models are checked and downloaded on startup. Offline: drop model folders into .GC/model/ and reopen, or retry from the Download page once online.',
'home.emptyAction': 'Get models',
'home.open': 'Open folder',
'home.delete': 'Delete',
'home.deleteConfirm': 'Delete the model "{0}"? Its files will be removed from the local library.',
'home.stats.models': 'Installed',
'home.stats.sources': 'Sources',
'home.stats.memory': 'Memory budget',
'home.recent': 'Select a model, then press Launch',
'home.launchHint': 'Models open in their own window with play/pause, view controls and teaching notes.',
'dl.title': 'Download',
'dl.subtitle': 'Read downloadable models from the built-in sources; manage sources in Settings.',
'dl.sources': 'Sources',
'dl.refresh': 'Refresh',
'dl.available': 'Available models',
'dl.download': 'Download',
'dl.installed': 'Installed',
'dl.reinstall': 'Re-download',
'dl.background': 'Background tasks',
'dl.bgEmpty': 'No background tasks',
'dl.cancel': 'Cancel',
'dl.retry': 'Retry',
'dl.clearDone': 'Clear finished',
'dl.removeTask': 'Remove',
'dl.status.queued': 'Queued',
'dl.status.downloading': 'Downloading',
'dl.status.done': 'Completed',
'dl.status.failed': 'Failed',
'dl.status.canceled': 'Canceled',
'dl.empty': 'No models in this source',
'dl.emptyHint': 'A source needs model/<model-id>/<model-id>.json layout',
'dl.syncing': 'Reading model source…',
'dl.ready': '{0} models',
'dl.fromCache': 'cached',
'dl.pickSource': 'Select a source to see available models',
'set.title': 'Settings',
'set.subtitle': 'Model sources, startup memory allocation and local storage.',
'set.general': 'General',
'set.appearance': 'Appearance',
'set.theme': 'Theme mode',
'set.theme.desc': 'Dark, light, or follow the system setting.',
'set.theme.dark': 'Dark',
'set.theme.light': 'Light',
'set.theme.system': 'System',
'set.accent': 'Theme color',
'set.accent.desc': 'Pick the launcher accent color; buttons, sliders and highlights follow it.',
'set.accent.custom': 'Custom color',
'set.accent.hexHint': 'Format #RRGGBB, e.g. #8FB6FF',
'set.accent.invalid': 'Invalid color, use #RRGGBB',
'set.language': 'Language',
'set.language.auto': 'System',
'set.fps': 'Render frame rate',
'set.fps.desc': 'Higher is smoother but uses more CPU.',
'set.memory': 'Startup memory allocation',
'set.memory.desc': 'The launcher hands this budget to each model; models decide how much data to cache with it.',
'set.memory.current': 'In use',
'set.memory.auto': 'Auto (allocate based on device memory)',
'set.memory.hint': '2048 MB or more is recommended; 1024 MB for low-end devices.',
'set.sources': 'Model sources',
'set.sources.desc': 'Disabled sources are hidden from the Download page.',
'set.sourceEnabled': 'Enabled',
'set.storage': 'Storage',
'set.modelDir': 'Model library',
'set.dataDir': 'Data folder',
'set.openFolder': 'Open folder',
'set.clearCache': 'Clear cache',
'set.cacheCleared': 'Cache cleared',
'set.about': 'About',
'set.version': 'Version',
'set.platform': 'Platform',
'set.license': 'License',
'set.licenseValue': 'MIT',
'set.checkUpdate': 'Check for updates',
'set.checkUpdate.desc': 'Check on startup whether models and the launcher are up to date.',
'set.backend': 'Backend service',
'set.backend.desc': 'The UI (Flutter) and the backend (.NET) are separate; the backend only listens on loopback.',
'set.backend.ui': 'Model window host',
'set.backend.uiOk': 'available',
'set.backend.uiBad': 'unavailable',
'update.title': 'Auto update',
'update.auto': 'Check for updates on startup',
'update.checkNow': 'Check now',
'update.source': 'Update source',
'update.lastCheck': 'Last check',
'update.never': 'Never',
'update.none': 'None',
'update.checking': 'Checking for updates…',
'update.offline': 'Update server unavailable — continuing with local models',
'update.noChange': 'Models and launcher are up to date',
'update.applied': 'Updated {0} models, applied now',
'update.done': 'Update check complete',
'update.pendingReady': 'Launcher {0} is ready, applies on next start',
'common.cancel': 'Cancel',
'common.confirm': 'Confirm',
'common.delete': 'Delete',
'common.close': 'Close',
'common.open': 'Open',
'common.applied': 'Applied',
'common.confirmTitle': 'Please confirm',
'common.retry': 'Retry',
'common.loading': 'Loading…',
'common.error': 'Something went wrong',
'common.refresh': 'Refresh',
'about.developers': 'Developers',
'about.contributorsHint': 'From repository commits',
'about.repository': 'Repository',
'about.openRepository': 'Open repository',
'about.contributions': '{0} commits',
'about.noContributors': 'No contributor information',
'about.architecture': 'Architecture',
'about.architectureValue': 'Flutter frontend + .NET backend (local HTTP)',
'about.sourceLanguage': 'Source language',
'about.frontend': 'Frontend',
},
};
/// 取一条文案;`{0}` 这类占位符用 [args] 填充。
static String t(String key, [List<Object?> args = const <Object?>[]]) {
final table = _tables[language.value] ?? _tables['zh-CN']!;
var text = table[key] ?? _tables['zh-CN']![key] ?? key;
for (var i = 0; i < args.length; i++) {
text = text.replaceAll('{$i}', '${args[i]}');
}
return text;
}
/// 把后端语言设置(auto / zh-CN / en)解析成实际语言。
static String resolve(String? preference) {
if (preference != null && preference.isNotEmpty && preference != 'auto') {
return preference.startsWith('en') ? 'en' : 'zh-CN';
}
final locale = WidgetsBinding.instance.platformDispatcher.locale;
return locale.languageCode == 'zh' ? 'zh-CN' : 'en';
}
static void setLanguage(String code) {
final resolved = resolve(code);
if (language.value != resolved) language.value = resolved;
}
}
/// 便捷取词:`T('nav.home')`。
String T(String key, [List<Object?> args = const <Object?>[]]) => I18n.t(key, args);
+67
View File
@@ -0,0 +1,67 @@
import 'package:flutter/material.dart';
import 'controller.dart';
import 'i18n.dart';
import 'shell.dart';
import 'theme.dart';
void main() {
// 桌面端无需异步初始化外部插件:尽早绑定并直接渲染首帧,
// 让窗口在引擎就绪后立刻出现,后端探测在外壳里异步进行。
WidgetsFlutterBinding.ensureInitialized();
runApp(const GcUiApp());
}
/// GC-UI 前端:Flutter 桌面应用(Windows / macOS / Linux)。
///
/// 界面全部在这里;模型扫描、下载、更新、设置、模型窗口宿主都在后端
/// (GC-UI/backend/GC.UI.Server,本地 HTTP 服务)。
class GcUiApp extends StatefulWidget {
const GcUiApp({super.key});
@override
State<GcUiApp> createState() => _GcUiAppState();
}
class _GcUiAppState extends State<GcUiApp> {
final ShellController _controller = ShellController();
@override
Widget build(BuildContext context) {
// 语言、强调色、主题模式都会触发重建:只重建 MaterialApp 的主题层,
// 不触碰页面状态(页面由 ShellPage 自己持有)。
return ValueListenableBuilder<String>(
valueListenable: I18n.language,
builder: (context, language, _) {
return ValueListenableBuilder<Color>(
valueListenable: GcPalette.accent,
builder: (context, accent, _) {
return ValueListenableBuilder<ThemeMode>(
valueListenable: GcPalette.mode,
builder: (context, mode, _) {
return MaterialApp(
title: 'Morris GC',
debugShowCheckedModeBanner: false,
theme: buildGcTheme(Brightness.light),
darkTheme: buildGcTheme(Brightness.dark),
themeMode: mode,
// GcColors 是静态取值,必须按当前实际亮度(含跟随系统)绑定,
// 再用 key 强制子树重建,否则切主题后颜色仍是上一套。
builder: (context, child) {
final brightness = Theme.of(context).brightness;
GcColors.bind(brightness);
return KeyedSubtree(
key: ValueKey<bool>(brightness == Brightness.dark),
child: child ?? const SizedBox.shrink(),
);
},
home: ShellPage(controller: _controller),
);
},
);
},
);
},
);
}
}
File diff suppressed because it is too large. Load diff
+355
View File
@@ -0,0 +1,355 @@
import 'package:flutter/material.dart';
import 'controller.dart';
import 'i18n.dart';
import 'pages.dart';
import 'theme.dart';
/// 侧边栏导航项。
class _NavItem {
const _NavItem(this.icon, this.labelKey);
final IconData icon;
final String labelKey;
}
const List<_NavItem> _navItems = <_NavItem>[
_NavItem(Icons.grid_view_rounded, 'nav.home'),
_NavItem(Icons.download_rounded, 'nav.download'),
_NavItem(Icons.tune_rounded, 'nav.settings'),
_NavItem(Icons.info_outline_rounded, 'nav.about'),
];
/// 应用外壳:左侧导航 + 右侧内容 + 底部更新状态条。
class ShellPage extends StatefulWidget {
const ShellPage({super.key, required this.controller});
final ShellController controller;
@override
State<ShellPage> createState() => _ShellPageState();
}
class _ShellPageState extends State<ShellPage> {
/// 页面缓存:键为「索引:语言」。同一个页面只构建一次,切走时用
/// [Offstage] 保活(不参与布局/绘制),切回来无需重建、状态也不丢。
final Map<String, Widget> _pages = <String, Widget>{};
@override
void initState() {
super.initState();
widget.controller.bootstrap();
}
@override
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: widget.controller,
builder: (context, _) {
final controller = widget.controller;
return Scaffold(
backgroundColor: GcColors.appBg,
body: Row(
children: <Widget>[
_Sidebar(controller: controller),
Expanded(
child: Column(
children: <Widget>[
Expanded(child: _content(controller)),
if (controller.updateBarVisible)
_UpdateBar(controller: controller),
],
),
),
],
),
);
},
);
}
Widget _content(ShellController controller) {
if (!controller.backendReady) {
if (controller.loadError != null) {
return _BackendDown(controller: controller);
}
return const Center(
child: SizedBox(
width: 26,
height: 26,
child: CircularProgressIndicator(strokeWidth: 2.4),
),
);
}
// 只构建当前页;其余已访问页面保留在树上但处于 Offstage。
final key = '${controller.index}:${I18n.language.value}';
_pages.putIfAbsent(key, () => _buildPage(controller, controller.index));
final visibleKey = key;
return Stack(
children: <Widget>[
for (final entry in _pages.entries)
Offstage(
offstage: entry.key != visibleKey,
child: TickerMode(
enabled: entry.key == visibleKey,
child: entry.value,
),
),
],
);
}
Widget _buildPage(ShellController controller, int index) {
switch (index) {
case 1:
return DownloadPageView(controller: controller);
case 2:
return SettingsPageView(controller: controller);
case 3:
return AboutPageView(controller: controller);
default:
return HomePageView(controller: controller);
}
}
}
class _Sidebar extends StatelessWidget {
const _Sidebar({required this.controller});
final ShellController controller;
@override
Widget build(BuildContext context) {
final settings = controller.settings;
return Container(
width: 236,
color: GcColors.sideBg,
padding: const EdgeInsets.fromLTRB(16, 20, 16, 18),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
children: <Widget>[
Container(
width: 26,
height: 26,
decoration: BoxDecoration(
color: GcColors.surfaceAlt,
borderRadius: BorderRadius.circular(8),
),
alignment: Alignment.center,
child: Text(
'◎',
style: TextStyle(fontSize: 14, color: GcColors.accent),
),
),
const SizedBox(width: 10),
Expanded(
child: Text(
'Morris GC',
style: TextStyle(
fontSize: 13,
fontWeight: FontWeight.w600,
color: GcColors.ink,
),
),
),
],
),
const SizedBox(height: 6),
GcHint(T('app.tagline')),
const SizedBox(height: 26),
const Padding(
padding: EdgeInsets.only(left: 14, bottom: 6),
child: Text(
'MENU',
style: TextStyle(
fontSize: 9.5,
letterSpacing: 1.2,
fontWeight: FontWeight.w600,
color: Color(0xFF4C5F80),
),
),
),
for (var i = 0; i < _navItems.length; i++)
_NavButton(
item: _navItems[i],
active: controller.index == i,
onTap: () => controller.goTo(i),
),
const Spacer(),
Container(height: 1, color: GcColors.line),
const SizedBox(height: 10),
Padding(
padding: const EdgeInsets.only(left: 14),
child: Text(
'v${settings?.version ?? '—'}',
style: TextStyle(fontSize: 10.5, color: GcColors.faint),
),
),
Padding(
padding: const EdgeInsets.only(left: 14, top: 2),
child: Text(
settings?.platform ?? '—',
style: const TextStyle(fontSize: 10, color: Color(0xFF4F6080)),
),
),
],
),
);
}
}
class _NavButton extends StatelessWidget {
const _NavButton({
required this.item,
required this.active,
required this.onTap,
});
final _NavItem item;
final bool active;
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(bottom: 4),
child: Material(
color: active ? GcColors.surfaceAlt : Colors.transparent,
borderRadius: BorderRadius.circular(9),
child: InkWell(
borderRadius: BorderRadius.circular(9),
onTap: onTap,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
child: Row(
children: <Widget>[
Icon(
item.icon,
size: 16,
color: active ? GcColors.accent : GcColors.faint,
),
const SizedBox(width: 10),
Text(
T(item.labelKey),
style: TextStyle(
fontSize: 12.5,
fontWeight: active ? FontWeight.w600 : FontWeight.w400,
color: active ? GcColors.ink : GcColors.muted,
),
),
],
),
),
),
),
);
}
}
class _UpdateBar extends StatelessWidget {
const _UpdateBar({required this.controller});
final ShellController controller;
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
color: GcColors.surface,
border: Border(top: BorderSide(color: GcColors.line)),
),
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 9),
child: Row(
children: <Widget>[
Text('⟳',
style: TextStyle(fontSize: 16, color: GcColors.accent)),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
controller.updateStatus,
style: TextStyle(
fontSize: 12.5,
fontWeight: FontWeight.w600,
color: GcColors.ink,
),
overflow: TextOverflow.ellipsis,
),
if (controller.updateDetail.isNotEmpty)
Text(
controller.updateDetail,
style: TextStyle(fontSize: 11, color: GcColors.faint),
overflow: TextOverflow.ellipsis,
),
if (controller.launcherNotice.isNotEmpty)
Text(
controller.launcherNotice,
style: TextStyle(fontSize: 11, color: GcColors.warn),
),
],
),
),
if (controller.updateBusy)
const SizedBox(
width: 130,
child: LinearProgressIndicator(minHeight: 4),
),
const SizedBox(width: 14),
TextButton(
onPressed: controller.updateBusy
? null
: () => controller.checkUpdate(force: true),
child: Text(T('update.checkNow')),
),
],
),
);
}
}
class _BackendDown extends StatelessWidget {
const _BackendDown({required this.controller});
final ShellController controller;
@override
Widget build(BuildContext context) {
return Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 520),
child: GcCard(
padding: const EdgeInsets.all(28),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
T('common.error'),
style: TextStyle(
fontSize: 17,
fontWeight: FontWeight.w600,
color: GcColors.ink,
),
),
const SizedBox(height: 10),
GcHint(controller.loadError ?? ''),
const SizedBox(height: 6),
GcHint('后端地址:${controller.api.baseUrl}'),
const SizedBox(height: 16),
FilledButton(
onPressed: controller.bootstrap,
child: Text(T('common.retry')),
),
],
),
),
),
);
}
}
+273
View File
@@ -0,0 +1,273 @@
import 'package:flutter/material.dart';
/// 主题偏好(可在设置页切换,并持久化到后端 settings.theme)。
///
/// 支持深色 / 浅色 / 跟随系统三种;[mode] 变化会让 `main.dart` 重建
/// `MaterialApp`,`themeMode` 交给 Flutter 决定实际亮度。
class GcPalette {
GcPalette._();
/// 默认强调色,与 Avalonia 启动器一致。
static const Color defaultAccent = Color(0xFF8FB6FF);
static final ValueNotifier<Color> accent =
ValueNotifier<Color>(defaultAccent);
/// 当前主题模式(dark / light / system)。
static final ValueNotifier<ThemeMode> mode = ValueNotifier<ThemeMode>(ThemeMode.dark);
/// 设置页可选的预设色板。
static const List<Color> presets = <Color>[
Color(0xFF8FB6FF), // 极光蓝(默认)
Color(0xFF7C6CFF), // 星云紫
Color(0xFF4FD1C5), // 湖水青
Color(0xFF6BE3A2), // 极光绿
Color(0xFFFFC46B), // 暖阳橙
Color(0xFFFF8FB1), // 樱粉
Color(0xFFFF7A7A), // 珊瑚红
Color(0xFFB0BEC5), // 石墨灰
];
/// 把后端设置里的 `theme` 字符串转成 [ThemeMode](未知值按深色处理)。
static ThemeMode parseMode(String? value) {
switch ((value ?? '').trim().toLowerCase()) {
case 'light':
return ThemeMode.light;
case 'system':
return ThemeMode.system;
case 'dark':
default:
return ThemeMode.dark;
}
}
/// 把 [ThemeMode] 转回后端设置的字符串。
static String modeToName(ThemeMode value) {
switch (value) {
case ThemeMode.light:
return 'light';
case ThemeMode.system:
return 'system';
case ThemeMode.dark:
return 'dark';
}
}
/// 应用主题模式(来自后端设置)。
static void applyTheme(String? value) {
final next = parseMode(value);
if (mode.value != next) mode.value = next;
}
/// 把 `#RRGGBB` / `RRGGBB` 解析为颜色;非法返回 null。
static Color? parseHex(String? value) {
if (value == null) return null;
var hex = value.trim();
if (hex.startsWith('#')) hex = hex.substring(1);
if (hex.length == 8) hex = hex.substring(2); // 忽略 alpha
if (hex.length != 6) return null;
final parsed = int.tryParse(hex, radix: 16);
if (parsed == null) return null;
return Color(0xFF000000 | parsed);
}
/// 颜色转 `#RRGGBB`。
static String toHex(Color color) {
// ignore: deprecated_member_use
final rgb = color.value & 0xFFFFFF;
return '#${rgb.toRadixString(16).padLeft(6, '0').toUpperCase()}';
}
/// 应用颜色(来自后端设置或用户点选)。
static void apply(String? hex) {
final color = parseHex(hex);
if (color == null) return;
// ignore: deprecated_member_use
if (accent.value.value != color.value) accent.value = color;
}
}
/// 配色:浅色 / 深色两套,按当前 [Brightness] 取值。
///
/// 以前这里是 const 常量,主题只能是深色 —— 设置里的 `theme` 字段写了也没人读。
/// 改成 getter 后,所有引用点自动跟随主题;代价是不能再放进 const 上下文。
class GcColors {
GcColors._();
static bool _dark = true;
static bool get isDark => _dark;
/// 由 `MaterialApp.builder` 在每次构建前按实际亮度绑定。
static void bind(Brightness brightness) => _dark = brightness == Brightness.dark;
static Color _pick(int dark, int light) => Color(_dark ? dark : light);
static Color get appBg => _pick(0xFF0A1226, 0xFFF3F6FB);
static Color get sideBg => _pick(0xFF0C1529, 0xFFFFFFFF);
static Color get surface => _pick(0xFF111C33, 0xFFFFFFFF);
static Color get surfaceAlt => _pick(0xFF16233C, 0xFFE9EFFA);
static Color get line => _pick(0xFF1B2740, 0xFFD8E2F2);
static Color get ink => _pick(0xFFF2F6FF, 0xFF0F1B2D);
static Color get muted => _pick(0xFFA9B8D4, 0xFF46587A);
static Color get faint => _pick(0xFF7C90B4, 0xFF7286A6);
static Color get warn => _pick(0xFFFFC46B, 0xFFB26A00);
static Color get danger => _pick(0xFFFF7A7A, 0xFFC0392B);
static Color get ok => _pick(0xFF6BE3A2, 0xFF1E8E5A);
/// 侧栏「MENU」一类最弱的说明文字。
static Color get ghost => _pick(0xFF4C5F80, 0xFF97A8C4);
/// 当前强调色(动态,跟随设置)。
static Color get accent => GcPalette.accent.value;
/// 强调色的加深版本,用于主按钮 / 轨道。浅色主题下需要反向调整,
/// 否则强调色在浅背景上对比度不足。
static Color get accentStrong => _strongen(accent);
static Color _strongen(Color color) {
final hsl = HSLColor.fromColor(color);
final lightness = _dark ? hsl.lightness - 0.10 : hsl.lightness - 0.22;
return hsl
.withSaturation((hsl.saturation + 0.12).clamp(0.0, 1.0))
.withLightness(lightness.clamp(0.0, 1.0))
.toColor();
}
}
/// 按指定亮度构建主题。
///
/// 注意:不要在这里改 [GcColors] 的全局状态 —— MaterialApp 会同时构建
/// theme 与 darkTheme,后构建的那个会把状态写脏。亮度绑定由 `main.dart`
/// 的 builder 统一完成。
ThemeData buildGcTheme(Brightness brightness) {
final isDark = brightness == Brightness.dark;
final base = isDark
? ThemeData.dark(useMaterial3: true)
: ThemeData.light(useMaterial3: true);
Color pick(int dark, int light) => Color(isDark ? dark : light);
final appBg = pick(0xFF0A1226, 0xFFF3F6FB);
final surface = pick(0xFF111C33, 0xFFFFFFFF);
final surfaceAlt = pick(0xFF16233C, 0xFFE9EFFA);
final line = pick(0xFF1B2740, 0xFFD8E2F2);
final ink = pick(0xFFF2F6FF, 0xFF0F1B2D);
final danger = pick(0xFFFF7A7A, 0xFFC0392B);
final accent = GcPalette.accent.value;
final hsl = HSLColor.fromColor(accent);
final accentStrong = hsl
.withSaturation((hsl.saturation + 0.12).clamp(0.0, 1.0))
.withLightness((hsl.lightness - (isDark ? 0.10 : 0.22)).clamp(0.0, 1.0))
.toColor();
return base.copyWith(
scaffoldBackgroundColor: appBg,
colorScheme: base.colorScheme.copyWith(
brightness: brightness,
primary: accentStrong,
secondary: accent,
surface: surface,
error: danger,
),
textTheme: base.textTheme.apply(
bodyColor: ink,
displayColor: ink,
),
dividerColor: line,
cardTheme: CardTheme(
color: surface,
elevation: 0,
margin: EdgeInsets.zero,
),
sliderTheme: base.sliderTheme.copyWith(
activeTrackColor: accentStrong,
thumbColor: accent,
inactiveTrackColor: line,
),
switchTheme: SwitchThemeData(
thumbColor: WidgetStateProperty.resolveWith(
(states) => states.contains(WidgetState.selected) ? accent : GcColors.faint,
),
trackColor: WidgetStateProperty.resolveWith(
(states) => states.contains(WidgetState.selected)
? accentStrong.withOpacity(0.45)
: line,
),
),
progressIndicatorTheme: ProgressIndicatorThemeData(
color: accent,
linearTrackColor: line,
),
tooltipTheme: TooltipThemeData(
decoration: BoxDecoration(
color: surfaceAlt,
borderRadius: const BorderRadius.all(Radius.circular(6)),
),
textStyle: TextStyle(color: ink, fontSize: 12),
),
);
}
/// 通用卡片容器。
class GcCard extends StatelessWidget {
const GcCard({super.key, required this.child, this.padding, this.width});
final Widget child;
final EdgeInsetsGeometry? padding;
final double? width;
@override
Widget build(BuildContext context) {
return Container(
width: width,
padding: padding ?? const EdgeInsets.all(18),
decoration: BoxDecoration(
color: GcColors.surface,
borderRadius: BorderRadius.circular(14),
border: Border.all(color: GcColors.line),
),
child: child,
);
}
}
/// 小标题。
class GcSectionTitle extends StatelessWidget {
const GcSectionTitle(this.text, {super.key, this.trailing});
final String text;
final Widget? trailing;
@override
Widget build(BuildContext context) {
return Row(
children: <Widget>[
Expanded(
child: Text(
text,
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.w600,
color: GcColors.ink,
),
),
),
if (trailing != null) trailing!,
],
);
}
}
/// 说明文字。
class GcHint extends StatelessWidget {
const GcHint(this.text, {super.key});
final String text;
@override
Widget build(BuildContext context) => Text(
text,
style: TextStyle(fontSize: 12, color: GcColors.faint, height: 1.5),
);
}
+1
View File
@@ -0,0 +1 @@
flutter/ephemeral
+146
View File
@@ -0,0 +1,146 @@
# Project-level configuration.
cmake_minimum_required(VERSION 3.10)
project(runner LANGUAGES CXX)
# The name of the executable created for the application. Change this to change
# the on-disk name of your application.
set(BINARY_NAME "GC-UI")
# The unique GTK application identifier for this application. See:
# https://wiki.gnome.org/HowDoI/ChooseApplicationID
set(APPLICATION_ID "com.xhmcl.GC")
# Explicitly opt in to modern CMake behaviors to avoid warnings with recent
# versions of CMake.
cmake_policy(SET CMP0063 NEW)
# Load bundled libraries from the lib/ directory relative to the binary.
set(CMAKE_INSTALL_RPATH "$ORIGIN/lib")
# Root filesystem for cross-building.
if(FLUTTER_TARGET_PLATFORM_SYSROOT)
set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT})
set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT})
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
endif()
# Define build configuration options.
if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
set(CMAKE_BUILD_TYPE "Debug" CACHE
STRING "Flutter build mode" FORCE)
set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS
"Debug" "Profile" "Release")
endif()
# Compilation settings that should be applied to most targets.
#
# Be cautious about adding new options here, as plugins use this function by
# default. In most cases, you should add new options to specific targets instead
# of modifying this function.
function(APPLY_STANDARD_SETTINGS TARGET)
target_compile_features(${TARGET} PUBLIC cxx_std_14)
target_compile_options(${TARGET} PRIVATE -Wall -Werror)
target_compile_options(${TARGET} PRIVATE "$<$<NOT:$<CONFIG:Debug>>:-O3>")
target_compile_definitions(${TARGET} PRIVATE "$<$<NOT:$<CONFIG:Debug>>:NDEBUG>")
endfunction()
# Flutter library and tool build rules.
set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter")
add_subdirectory(${FLUTTER_MANAGED_DIR})
# System-level dependencies.
find_package(PkgConfig REQUIRED)
pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0)
add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}")
# Define the application target. To change its name, change BINARY_NAME above,
# not the value here, or `flutter run` will no longer work.
#
# Any new source files that you add to the application should be added here.
add_executable(${BINARY_NAME}
"main.cc"
"my_application.cc"
"${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc"
)
# Apply the standard set of build settings. This can be removed for applications
# that need different build settings.
apply_standard_settings(${BINARY_NAME})
# Add dependency libraries. Add any application-specific dependencies here.
target_link_libraries(${BINARY_NAME} PRIVATE flutter)
target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK)
# Run the Flutter tool portions of the build. This must not be removed.
add_dependencies(${BINARY_NAME} flutter_assemble)
# Only the install-generated bundle's copy of the executable will launch
# correctly, since the resources must in the right relative locations. To avoid
# people trying to run the unbundled copy, put it in a subdirectory instead of
# the default top-level location.
set_target_properties(${BINARY_NAME}
PROPERTIES
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run"
)
# Generated plugin build rules, which manage building the plugins and adding
# them to the application.
include(flutter/generated_plugins.cmake)
# === Installation ===
# By default, "installing" just makes a relocatable bundle in the build
# directory.
set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle")
# 无条件强制安装到 build 目录下的 bundle:某些环境下 CMAKE_INSTALL_PREFIX
# 会被初始化成 /usr/local,导致 flutter build linux 声称成功、却把产物装进
# 系统目录,build/.../bundle 是空的。
set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "Flutter bundle 输出目录" FORCE)
# Start with a clean build bundle directory every time.
install(CODE "
file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\")
" COMPONENT Runtime)
set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data")
set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib")
install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}"
COMPONENT Runtime)
install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}"
COMPONENT Runtime)
install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
COMPONENT Runtime)
foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES})
install(FILES "${bundled_library}"
DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
COMPONENT Runtime)
endforeach(bundled_library)
# Copy the native assets provided by the build.dart from all packages.
set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/")
install(DIRECTORY "${NATIVE_ASSETS_DIR}"
DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
COMPONENT Runtime)
# Fully re-copy the assets directory on each build to avoid having stale files
# from a previous install.
set(FLUTTER_ASSET_DIR_NAME "flutter_assets")
install(CODE "
file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\")
" COMPONENT Runtime)
install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}"
DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime)
# Install the AOT library on non-Debug builds only.
if(NOT CMAKE_BUILD_TYPE MATCHES "Debug")
install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
COMPONENT Runtime)
endif()
Loaded 100 of 419 files, more files were not shown because too many files have changed in this diff. Show more