Compare commits
18
Commits
82cab7b0e3
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3f1f48f54c | ||
|
|
8b4cabba28 | ||
|
|
40d9da1c3d | ||
|
|
cfd6809714 | ||
|
|
38781c9807 | ||
|
|
185a8905f9 | ||
|
|
ecb71ad347 | ||
|
|
e7c1429889 | ||
|
|
5b82a885f9 | ||
|
|
936ef8333e | ||
|
|
ab0cee8b40 | ||
|
|
b51ebd1a3d | ||
|
|
f64f2708a1 | ||
|
|
0d383f96fb | ||
|
|
c08206e7db | ||
|
|
2b036d2226 | ||
|
|
ea1fa6b6d1 | ||
|
|
b9cb56cb8b |
No files matched your search
@@ -0,0 +1,87 @@
|
||||
# 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,不需要额外安装。
|
||||
@@ -0,0 +1,342 @@
|
||||
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
|
||||
@@ -0,0 +1,309 @@
|
||||
name: build-release
|
||||
|
||||
# 在 Issue / PR 里评论触发「编译 + 发布正式版本」:
|
||||
# @build-release-bot build 1.1.3
|
||||
#
|
||||
# 与 build-bot 的区别:
|
||||
# build-bot 只编译,产物丢进 ip-prerelease(预发布,反复覆盖)
|
||||
# build-release 编译三平台,发一个 tag = 版本号的正式 Release(会更新 latest)
|
||||
#
|
||||
# 不会改动仓库里的 version.json:它由 GC-SAVEDOG 签名,CI 里没有签名私钥,
|
||||
# 重新 stamp 会产出一份客户端拒绝接受的清单。清单更新请走本地 ./build.sh stamp。
|
||||
|
||||
on:
|
||||
issue_comment:
|
||||
types: [created]
|
||||
|
||||
concurrency:
|
||||
group: release-manual
|
||||
cancel-in-progress: false
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
issues: write
|
||||
pull-requests: write
|
||||
|
||||
env:
|
||||
TZ: Asia/Shanghai
|
||||
DOTNET_VERSION: '8.0.x'
|
||||
FLUTTER_VERSION: '3.24.5'
|
||||
|
||||
jobs:
|
||||
prepare:
|
||||
if: |
|
||||
contains(github.event.comment.body, '@build-release-bot') &&
|
||||
(github.event.comment.author_association == 'OWNER' ||
|
||||
github.event.comment.author_association == 'MEMBER' ||
|
||||
github.event.comment.author_association == 'COLLABORATOR')
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
ok: ${{ steps.parse.outputs.ok }}
|
||||
version: ${{ steps.parse.outputs.version }}
|
||||
ref: ${{ steps.parse.outputs.ref }}
|
||||
reason: ${{ steps.parse.outputs.reason }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- id: parse
|
||||
name: 解析版本号并预检
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
BODY: ${{ github.event.comment.body }}
|
||||
run: |
|
||||
set -e
|
||||
# 只认 主.次.修订,其它写法直接忽略
|
||||
VER=$(printf '%s' "$BODY" \
|
||||
| grep -oiE '@build-release-bot[[:space:]]+build[[:space:]]+[0-9]+\.[0-9]+\.[0-9]+' \
|
||||
| head -1 \
|
||||
| awk '{print $NF}' || true)
|
||||
|
||||
if [ -z "$VER" ]; then
|
||||
echo "ok=false" >> "$GITHUB_OUTPUT"
|
||||
echo "reason=没有匹配到合法版本号(格式:@build-release-bot build 1.2.3)" >> "$GITHUB_OUTPUT"
|
||||
echo "未匹配到版本号,忽略"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "version=$VER" >> "$GITHUB_OUTPUT"
|
||||
echo "ref=${{ github.event.repository.default_branch }}" >> "$GITHUB_OUTPUT"
|
||||
echo "版本号=$VER"
|
||||
|
||||
# tag 已存在就不能再发:重复 tag 会让客户端拿到两份不同内容
|
||||
if gh api "repos/${{ github.repository }}/git/ref/tags/${VER}" >/dev/null 2>&1; then
|
||||
echo "ok=false" >> "$GITHUB_OUTPUT"
|
||||
echo "reason=tag ${VER} 已存在,请换一个版本号" >> "$GITHUB_OUTPUT"
|
||||
echo "tag ${VER} 已存在"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "ok=true" >> "$GITHUB_OUTPUT"
|
||||
echo "reason=" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: 回复「开始编译并发布」
|
||||
if: steps.parse.outputs.ok == 'true'
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
GH_REPO: ${{ github.repository }}
|
||||
ISSUE: ${{ github.event.issue.number }}
|
||||
VER: ${{ steps.parse.outputs.version }}
|
||||
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
|
||||
run: |
|
||||
set -e
|
||||
cat > ack.md <<EOF
|
||||
🔨 **开始编译并发布 \`${VER}\`**
|
||||
|
||||
平台:macOS (arm64) + Windows (amd64 / arm64)
|
||||
|
||||
- 实时日志:${RUN_URL}
|
||||
|
||||
编译完成后会在这里回复结果。
|
||||
EOF
|
||||
gh issue comment "$ISSUE" --body-file ack.md
|
||||
|
||||
- name: 回复「忽略原因」
|
||||
if: steps.parse.outputs.ok != 'true'
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
GH_REPO: ${{ github.repository }}
|
||||
ISSUE: ${{ github.event.issue.number }}
|
||||
REASON: ${{ steps.parse.outputs.reason }}
|
||||
run: |
|
||||
set -e
|
||||
gh issue comment "$ISSUE" --body "⏭ 未触发:${REASON}"
|
||||
|
||||
build-mac:
|
||||
needs: prepare
|
||||
if: needs.prepare.outputs.ok == 'true'
|
||||
runs-on: macos-14
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ needs.prepare.outputs.ref }}
|
||||
|
||||
- uses: actions/setup-dotnet@v4
|
||||
with:
|
||||
dotnet-version: ${{ env.DOTNET_VERSION }}
|
||||
|
||||
# NuGet 包缓存:依赖没变时省去冷下载
|
||||
- uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.nuget/packages
|
||||
key: ${{ runner.os }}-nuget-${{ hashFiles('**/*.csproj', '**/*.props', '**/packages.lock.json') }}
|
||||
restore-keys: ${{ runner.os }}-nuget-
|
||||
|
||||
- uses: subosito/flutter-action@v2
|
||||
with:
|
||||
flutter-version: ${{ env.FLUTTER_VERSION }}
|
||||
channel: stable
|
||||
cache: true
|
||||
|
||||
# CocoaPods:Pods/ 被 gitignore,Podfile.lock 没变时复用,省掉 pod install
|
||||
- uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
GC-UI/frontend/macos/Pods
|
||||
~/Library/Caches/CocoaPods
|
||||
key: ${{ runner.os }}-pods-${{ hashFiles('GC-UI/frontend/macos/Podfile.lock') }}
|
||||
restore-keys: ${{ runner.os }}-pods-
|
||||
|
||||
- name: 环境信息
|
||||
run: |
|
||||
sw_vers
|
||||
xcodebuild -version
|
||||
flutter --version
|
||||
|
||||
- name: 编译 macOS
|
||||
env:
|
||||
GC_NO_PROGRESS: '1'
|
||||
run: ./build.sh build --targets=mac -version=${{ needs.prepare.outputs.version }}
|
||||
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: mac-zip
|
||||
path: dist/mac-arm64/*.zip
|
||||
if-no-files-found: error
|
||||
retention-days: 5
|
||||
|
||||
build-win:
|
||||
needs: prepare
|
||||
if: needs.prepare.outputs.ok == 'true'
|
||||
runs-on: windows-latest
|
||||
defaults:
|
||||
run:
|
||||
shell: pwsh
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ needs.prepare.outputs.ref }}
|
||||
|
||||
- uses: actions/setup-dotnet@v4
|
||||
with:
|
||||
dotnet-version: ${{ env.DOTNET_VERSION }}
|
||||
|
||||
- uses: subosito/flutter-action@v2
|
||||
with:
|
||||
flutter-version: ${{ env.FLUTTER_VERSION }}
|
||||
channel: stable
|
||||
cache: true
|
||||
|
||||
- name: 编译 Windows(amd64 + arm64)
|
||||
run: ./build.ps1 build -Version ${{ needs.prepare.outputs.version }}
|
||||
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: win-zip
|
||||
path: |
|
||||
dist/win-amd64/*.zip
|
||||
dist/win-arm64/*.zip
|
||||
if-no-files-found: error
|
||||
retention-days: 5
|
||||
|
||||
publish:
|
||||
needs: [prepare, build-mac, build-win]
|
||||
if: needs.prepare.outputs.ok == 'true' && needs.build-mac.result == 'success' && needs.build-win.result == 'success'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
path: artifacts
|
||||
|
||||
- name: 汇总产物
|
||||
run: |
|
||||
set -e
|
||||
mkdir -p out
|
||||
find artifacts -name '*.zip' -exec cp {} out/ \;
|
||||
ls -lh out
|
||||
|
||||
- name: 生成 sha256 清单
|
||||
working-directory: out
|
||||
run: |
|
||||
set -e
|
||||
shasum -a 256 *.zip > SHA256SUMS.txt 2>/dev/null || sha256sum *.zip > SHA256SUMS.txt
|
||||
cat SHA256SUMS.txt
|
||||
|
||||
- name: 发布 Release
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
GH_REPO: ${{ github.repository }}
|
||||
VER: ${{ needs.prepare.outputs.version }}
|
||||
REF: ${{ needs.prepare.outputs.ref }}
|
||||
ACTOR: ${{ github.event.comment.user.login }}
|
||||
ISSUE: ${{ github.event.issue.number }}
|
||||
run: |
|
||||
set -e
|
||||
cat > notes.md <<EOF
|
||||
GC ${VER}
|
||||
|
||||
- macOS(arm64)
|
||||
- Windows(amd64 / arm64)
|
||||
|
||||
触发人:@${ACTOR}(#${ISSUE})
|
||||
构建来源:\`${REF}\`
|
||||
|
||||
各包 sha256 见 \`SHA256SUMS.txt\`。
|
||||
|
||||
> macOS 包为 ad-hoc 签名,首次打开需右键 →「打开」,或在「系统设置 → 隐私与安全性」里放行。
|
||||
EOF
|
||||
|
||||
gh release create "$VER" out/* \
|
||||
--target "$REF" \
|
||||
--title "GC ${VER}" \
|
||||
--notes-file notes.md
|
||||
|
||||
echo "https://github.com/${{ github.repository }}/releases/tag/$VER" >> "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
report:
|
||||
needs: [prepare, build-mac, build-win, publish]
|
||||
if: always() && needs.prepare.outputs.ok == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: 回帖结果
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
GH_REPO: ${{ github.repository }}
|
||||
ISSUE: ${{ github.event.issue.number }}
|
||||
VER: ${{ needs.prepare.outputs.version }}
|
||||
MAC: ${{ needs.build-mac.result }}
|
||||
WIN: ${{ needs.build-win.result }}
|
||||
PUB: ${{ needs.publish.result }}
|
||||
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
|
||||
run: |
|
||||
set -e
|
||||
REPO="${{ github.repository }}"
|
||||
|
||||
line() {
|
||||
case "$2" in
|
||||
success) echo "- $1:✅ 成功" ;;
|
||||
skipped) echo "- $1:⏭ 跳过" ;;
|
||||
cancelled) echo "- $1:⛔ 已取消" ;;
|
||||
*) echo "- $1:❌ 失败" ;;
|
||||
esac
|
||||
}
|
||||
|
||||
if [ "$PUB" = "success" ]; then
|
||||
HEADLINE="✅ **已发布 \`${VER}\`**"
|
||||
elif [ "$MAC" = "success" ] || [ "$WIN" = "success" ]; then
|
||||
HEADLINE="⚠️ **编译完成但未发布 \`${VER}\`**(需要两个平台都成功才会发 Release)"
|
||||
else
|
||||
HEADLINE="❌ **\`${VER}\` 编译失败**"
|
||||
fi
|
||||
|
||||
{
|
||||
echo "$HEADLINE"
|
||||
echo
|
||||
line "macOS" "$MAC"
|
||||
line "Windows" "$WIN"
|
||||
line "发布" "$PUB"
|
||||
echo
|
||||
if [ "$PUB" = "success" ]; then
|
||||
echo "- Release:https://github.com/${REPO}/releases/tag/${VER}"
|
||||
else
|
||||
echo "- 日志:${RUN_URL}"
|
||||
fi
|
||||
} > result.md
|
||||
|
||||
gh issue comment "$ISSUE" --body-file result.md
|
||||
@@ -0,0 +1,144 @@
|
||||
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
|
||||
@@ -0,0 +1,207 @@
|
||||
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
|
||||
+14
@@ -54,3 +54,17 @@ 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
|
||||
@@ -65,3 +65,266 @@
|
||||
- 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,重复签到被拒,人品值按本地日重置
|
||||
@@ -13,16 +13,12 @@
|
||||
<LangVersion>latest</LangVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>disable</ImplicitUsings>
|
||||
<!--
|
||||
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>
|
||||
<MvvmVersion>8.2.2</MvvmVersion>
|
||||
<Version>1.1.1</Version>
|
||||
<!-- 模型窗口仍由 Avalonia 承载(模型契约返回 Avalonia Control),
|
||||
界面本身是 Flutter。Avalonia.BuildServices 的遥测会向用户目录写日志,
|
||||
在只读目录 / CI 里会直接让编译失败,build.sh / build.ps1 已默认关闭。 -->
|
||||
<AvaloniaVersion>11.3.9</AvaloniaVersion>
|
||||
<Version>1.1.2</Version>
|
||||
<Company>Morris</Company>
|
||||
<Product>GC</Product>
|
||||
<NeutralLanguage>zh-Hans</NeutralLanguage>
|
||||
|
||||
+42
-4
@@ -4,6 +4,7 @@ using System.IO;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using GC.Services;
|
||||
using GC.UI.Server;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
|
||||
@@ -20,15 +21,16 @@ namespace GC;
|
||||
/// 后端跑在进程内而不是单独一个 exe:两者用的是同一套 .NET 运行时,
|
||||
/// 拆成两个自包含进程等于把 60MB 运行时复制两份,发布包会白白大一倍。
|
||||
///
|
||||
/// 缺 Flutter 前端时返回 <c>false</c>,由调用方回退到内置 Avalonia 界面——
|
||||
/// 这样 `dotnet run`、只编了启动器的开发场景都能正常打开。
|
||||
/// 缺 Flutter 前端时返回 <c>false</c>,由调用方提示用户安装完整发布包
|
||||
/// (内置 Avalonia 界面已移除,界面只有 Flutter 一套)。
|
||||
/// </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) };
|
||||
// 使用共享 HttpClient(短超时,仅用于健康检查)
|
||||
private static readonly HttpClient Http = SharedHttpClientFactory.GetDefault();
|
||||
|
||||
private static WebApplication? _backend;
|
||||
|
||||
@@ -38,6 +40,12 @@ internal static class FlutterShell
|
||||
var uiPath = FindUi(dir);
|
||||
if (uiPath == null) return false;
|
||||
|
||||
// 确定要用 Flutter 界面了:本进程只当后端宿主,不要另占一个 Dock 图标
|
||||
// (否则「后端 + UI」会出现两个图标)。回退 Avalonia 的分支不会走到这里。
|
||||
MacDock.HideFromDock();
|
||||
if (OperatingSystem.IsMacOS())
|
||||
Console.WriteLine("[shell] 启动器以 UIElement 运行(不占 Dock,界面由 GC-UI.app 显示)");
|
||||
|
||||
// 本次会话的一次性令牌:进程内后端与 Flutter 前端都从这里拿到同一个值。
|
||||
// 只有我们拉起的后端才持有它,同机其他进程伪造的健康响应过不了 IsHealthy 的身份校验。
|
||||
// 允许外部预设(自动化测试 / 高级部署固定令牌),未预设才现场生成随机值。
|
||||
@@ -89,7 +97,7 @@ internal static class FlutterShell
|
||||
|
||||
// 前端窗口已拉起。模型窗口由 Avalonia 承载,而 macOS 的 AppKit 要求
|
||||
// NSApplication 必须在**主线程**——所以事件循环要跑在这里(当前正是主线程),
|
||||
// 不能再丢到副线程,否则一点「启动模型」就会把整个后端带崩。
|
||||
// 不能丢到副线程,否则一点「启动模型」就会把整个后端带崩。
|
||||
ui.EnableRaisingEvents = true;
|
||||
var closed = 0;
|
||||
void RequestClose()
|
||||
@@ -115,6 +123,35 @@ internal static class FlutterShell
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 找不到 Flutter 前端时的提示。
|
||||
/// 已经没有任何内置界面可以回退,所以必须在终端/弹窗里说清楚,
|
||||
/// 否则用户只会看到一个进程一闪而过。
|
||||
/// </summary>
|
||||
public static void ReportMissingUi()
|
||||
{
|
||||
const string message = "找不到 Flutter 前端(GC-UI.app / GC-UI.exe)。请使用完整发布包。";
|
||||
Console.Error.WriteLine(message);
|
||||
|
||||
if (!OperatingSystem.IsMacOS()) return;
|
||||
try
|
||||
{
|
||||
// 发布包是从 Finder 双击启动的,没有终端可看:用系统弹窗告知
|
||||
var psi = new ProcessStartInfo("/usr/bin/osascript")
|
||||
{
|
||||
UseShellExecute = false,
|
||||
RedirectStandardError = true,
|
||||
};
|
||||
psi.ArgumentList.Add("-e");
|
||||
psi.ArgumentList.Add($"display alert \"{message}\" as critical");
|
||||
Process.Start(psi);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 提示失败也不影响退出码
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 产物定位
|
||||
|
||||
/// <summary>
|
||||
@@ -154,6 +191,7 @@ internal static class FlutterShell
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
uiHost = null;
|
||||
Console.Error.WriteLine($"[shell] 后端启动失败(端口 {port}): {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -12,11 +12,6 @@
|
||||
<BuiltInComInteropSupport>true</BuiltInComInteropSupport>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
|
||||
<PackageReference Include="Avalonia.Desktop" Version="$(AvaloniaVersion)" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- 后端以库的方式编进启动器:发布包只需要一个 exe,不用再带一份运行时 -->
|
||||
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace GC;
|
||||
|
||||
/// <summary>
|
||||
/// macOS Dock 图标控制。
|
||||
///
|
||||
/// 有 Flutter 前端时,启动器(GC.app 的主进程)只承担后端宿主,界面全在 GC-UI.app 里。
|
||||
/// 两个 .app 各自带 Dock 图标 → 用户会看到两个图标。
|
||||
///
|
||||
/// 三重保险,任意一条生效就够了:
|
||||
/// 1. 打包时 Info.plist 写 <c>LSUIElement=true</c>(buildsh/lib/package.sh);
|
||||
/// 2. 运行期 <c>TransformProcessType</c> 转成 UIElement(Carbon 老 API,但对已启动的
|
||||
/// 进程最可靠,不依赖 LaunchServices 缓存);
|
||||
/// 3. 运行期 <c>[NSApp setActivationPolicy:accessory]</c>。
|
||||
/// 只用其中一条都出现过「某些机器上仍是两个图标」,所以三条一起上。
|
||||
/// </summary>
|
||||
internal static class MacDock
|
||||
{
|
||||
private const string Objc = "/usr/lib/libobjc.dylib";
|
||||
private const string Carbon =
|
||||
"/System/Library/Frameworks/ApplicationServices.framework/ApplicationServices";
|
||||
|
||||
// NSApplicationActivationPolicy: Regular=0, Accessory=1, Prohibited=2
|
||||
private const long ActivationPolicyAccessory = 1;
|
||||
|
||||
// ProcessApplicationTransformState: kProcessTransformToUIElementApplication = 4
|
||||
private const int TransformToUIElement = 4;
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct ProcessSerialNumber
|
||||
{
|
||||
public uint HighLongOfPSN;
|
||||
public uint LowLongOfPSN;
|
||||
}
|
||||
|
||||
[DllImport(Objc)]
|
||||
private static extern IntPtr objc_getClass(string name);
|
||||
|
||||
[DllImport(Objc)]
|
||||
private static extern IntPtr sel_registerName(string name);
|
||||
|
||||
[DllImport(Objc, EntryPoint = "objc_msgSend")]
|
||||
private static extern IntPtr objc_msgSend(IntPtr receiver, IntPtr selector);
|
||||
|
||||
[DllImport(Objc, EntryPoint = "objc_msgSend")]
|
||||
private static extern IntPtr objc_msgSend_int(IntPtr receiver, IntPtr selector, long arg);
|
||||
|
||||
[DllImport(Carbon)]
|
||||
private static extern int GetCurrentProcess(out ProcessSerialNumber psn);
|
||||
|
||||
[DllImport(Carbon)]
|
||||
private static extern int TransformProcessType(ref ProcessSerialNumber psn, int transformState);
|
||||
|
||||
/// <summary>把当前进程从 Dock 隐藏掉(仅 macOS,其它平台空操作)。</summary>
|
||||
public static void HideFromDock()
|
||||
{
|
||||
if (!OperatingSystem.IsMacOS()) return;
|
||||
|
||||
// 2. Carbon:对「已经在运行」的进程最直接
|
||||
try
|
||||
{
|
||||
if (GetCurrentProcess(out var psn) == 0)
|
||||
TransformProcessType(ref psn, TransformToUIElement);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 旧系统 / 沙箱下可能不可用,继续尝试下一条
|
||||
}
|
||||
|
||||
// 3. AppKit:需要先有 NSApplication 实例
|
||||
try
|
||||
{
|
||||
var cls = objc_getClass("NSApplication");
|
||||
if (cls == IntPtr.Zero) return;
|
||||
|
||||
var app = objc_msgSend(cls, sel_registerName("sharedApplication"));
|
||||
if (app == IntPtr.Zero) return;
|
||||
|
||||
objc_msgSend_int(app, sel_registerName("setActivationPolicy:"), ActivationPolicyAccessory);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 无窗口/沙箱环境下 NSApplication 不可用,忽略即可:
|
||||
// 最多是多一个 Dock 图标,不影响功能。
|
||||
}
|
||||
}
|
||||
}
|
||||
+4
-8
@@ -1,5 +1,4 @@
|
||||
using System;
|
||||
using Avalonia;
|
||||
using GC.Services;
|
||||
using GC.Download;
|
||||
|
||||
@@ -21,14 +20,11 @@ internal static class Program
|
||||
// 上次下载的启动器新版,到这次启动才应用
|
||||
if (DownloadModuleHost.Factory.TryApplyPending(paths)) return;
|
||||
|
||||
// 发布包带 Flutter 前端时,界面交给它;没带则回退到内置 Avalonia 界面。
|
||||
// 界面只有 Flutter 一套(内置 Avalonia 界面已移除)。
|
||||
if (FlutterShell.TryRun(args)) return;
|
||||
|
||||
BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
|
||||
// 找不到前端:给出明确提示后退出,不要静默启动一个没有界面的后端进程。
|
||||
FlutterShell.ReportMissingUi();
|
||||
Environment.Exit(1);
|
||||
}
|
||||
|
||||
public static AppBuilder BuildAvaloniaApp()
|
||||
=> AppBuilder.Configure<App>()
|
||||
.UsePlatformDetect()
|
||||
.LogToTrace();
|
||||
}
|
||||
@@ -17,7 +17,8 @@ namespace GC.Services;
|
||||
public sealed class DirectoryRemote : IModelRemote
|
||||
{
|
||||
private readonly string _root;
|
||||
private static readonly HttpClient Http = new() { Timeout = TimeSpan.FromMinutes(5) };
|
||||
// 使用共享 HttpClient(长超时版本)
|
||||
private static readonly HttpClient Http = SharedHttpClientFactory.GetLongTimeout();
|
||||
private string? _rawManifest;
|
||||
private string _launcherVersion = "";
|
||||
|
||||
|
||||
@@ -25,17 +25,8 @@ public sealed class GitCodeReleaseRemote : IModelRemote
|
||||
private readonly string _releasesUrl;
|
||||
private readonly Dictionary<string, (string Url, string? Sha256, long Size, string Name)> _assets = new();
|
||||
|
||||
// 共享静态 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;
|
||||
}
|
||||
// 使用共享 HttpClient 工厂,统一连接池管理
|
||||
private static readonly HttpClient Http = SharedHttpClientFactory.GetDefault();
|
||||
|
||||
public GitCodeReleaseRemote(string? manifestUrl, string? repository)
|
||||
{
|
||||
@@ -80,7 +71,8 @@ public sealed class GitCodeReleaseRemote : IModelRemote
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"[gitcode] 读取 Release 失败: {ex.Message}");
|
||||
GcLog.Warn($"读取 Release 失败: {ex.Message}",
|
||||
$"Failed to read Release: {ex.Message}");
|
||||
gotRelease = false;
|
||||
}
|
||||
|
||||
@@ -93,12 +85,13 @@ public sealed class GitCodeReleaseRemote : IModelRemote
|
||||
var n = version?.Launcher.Packages.Count ?? 0;
|
||||
if (v.Length == 0 || n == 0)
|
||||
{
|
||||
Console.WriteLine($"[gitcode] {DisplayName}: 没有 Release,清单里也没有启动器包");
|
||||
GcLog.Warn($"{DisplayName}: 没有 Release,清单里也没有启动器包",
|
||||
$"{DisplayName}: No Release, no launcher packages in manifest");
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine(
|
||||
$"[gitcode] {DisplayName}: 没有 Release,改用清单声明的 v{v}({n} 个平台包,去 dist/ 找产物)");
|
||||
GcLog.Info($"没有 Release,改用清单声明的 v{v}({n} 个平台包,去 dist/ 找产物)",
|
||||
$"No Release; using manifest version v{v} ({n} platform packages, looking in dist/)");
|
||||
}
|
||||
}
|
||||
return version;
|
||||
|
||||
@@ -42,9 +42,8 @@ public sealed class GitCodeRemote : IModelRemote
|
||||
_displayName = string.IsNullOrWhiteSpace(repository)
|
||||
? DefaultRepository : repository!.TrimEnd('/');
|
||||
|
||||
_http = new HttpClient { Timeout = TimeSpan.FromMinutes(2) };
|
||||
_http.DefaultRequestHeaders.UserAgent.ParseAdd("GC-Updater/1.0");
|
||||
_http.DefaultRequestHeaders.Accept.ParseAdd("application/json");
|
||||
// 使用共享 HttpClient,统一连接池管理
|
||||
_http = SharedHttpClientFactory.GetDefault();
|
||||
|
||||
if (string.IsNullOrWhiteSpace(manifestUrl))
|
||||
{
|
||||
@@ -136,7 +135,8 @@ public sealed class GitCodeRemote : IModelRemote
|
||||
|
||||
if (verification.Trust == ManifestTrust.Invalid)
|
||||
{
|
||||
Console.Error.WriteLine($"[gitcode] 清单验签失败,已拒绝: {verification.Error}");
|
||||
GcLog.Warn($"清单验签失败,已拒绝: {verification.Error}",
|
||||
$"Manifest signature check failed: {verification.Error}");
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -146,7 +146,8 @@ public sealed class GitCodeRemote : IModelRemote
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"版本清单解析失败 {url}: {ex.Message}");
|
||||
GcLog.Warn($"版本清单解析失败 {url}: {ex.Message}",
|
||||
$"Failed to parse version manifest {url}: {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -179,7 +180,8 @@ public sealed class GitCodeRemote : IModelRemote
|
||||
try { text = await GetWithRetryAsync(url, ct); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"列目录失败 {repoPath}: {ex.Message}");
|
||||
GcLog.Warn($"列目录失败 {repoPath}: {ex.Message}",
|
||||
$"Failed to list directory {repoPath}: {ex.Message}");
|
||||
return;
|
||||
}
|
||||
if (!text.TrimStart().StartsWith("[", StringComparison.Ordinal)) return;
|
||||
@@ -338,7 +340,8 @@ public sealed class GitCodeRemote : IModelRemote
|
||||
if (bytes != null) return bytes;
|
||||
}
|
||||
|
||||
Console.Error.WriteLine("[gitcode] 找不到可用的启动器包(Release 附件与 dist 目录都没对上)");
|
||||
GcLog.Warn("找不到可用的启动器包(Release 附件与 dist 目录都没对上)",
|
||||
"Could not find a usable launcher package");
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -351,7 +354,8 @@ public sealed class GitCodeRemote : IModelRemote
|
||||
try { bytes = await _http.GetByteArrayAsync(url!, ct); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"[gitcode] 下载失败 {Short(url!)}: {ex.Message}");
|
||||
GcLog.Warn($"下载失败 {Short(url!)}: {ex.Message}",
|
||||
$"Download failed {Short(url!)}: {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
if (bytes.Length == 0) return null;
|
||||
@@ -361,12 +365,14 @@ public sealed class GitCodeRemote : IModelRemote
|
||||
var actual = Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant();
|
||||
if (!string.Equals(actual, sha256.Trim(), StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
Console.Error.WriteLine($"[gitcode] 包校验不符,换下一个来源: {Short(url!)}");
|
||||
GcLog.Warn($"包校验不符,换下一个来源: {Short(url!)}",
|
||||
$"Package hash mismatch, trying next source: {Short(url!)}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Console.WriteLine($"[gitcode] 启动器包来源: {Short(url!)}");
|
||||
GcLog.Info($"启动器包来源: {Short(url!)}",
|
||||
$"Launcher package source: {Short(url!)}");
|
||||
return bytes;
|
||||
}
|
||||
|
||||
@@ -431,7 +437,8 @@ public sealed class GitCodeRemote : IModelRemote
|
||||
match = 0;
|
||||
}
|
||||
|
||||
Console.WriteLine($"[gitcode] 在 {dir} 找到编译产物: {zips[match].Name}");
|
||||
GcLog.Info($"在 {dir} 找到编译产物: {zips[match].Name}",
|
||||
$"Found build artifact in {dir}: {zips[match].Name}");
|
||||
return await ResolveFileUrlAsync(zips[match].Path, ct);
|
||||
}
|
||||
catch (Exception)
|
||||
|
||||
+32
-21
@@ -22,17 +22,10 @@ namespace GC.Services;
|
||||
public sealed class GiteaRemote : IModelRemote
|
||||
{
|
||||
private readonly SourcePreset _preset;
|
||||
private static readonly HttpClient Http = CreateHttp();
|
||||
// 使用共享 HttpClient,统一连接池管理
|
||||
private static readonly HttpClient Http = SharedHttpClientFactory.GetDefault();
|
||||
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;
|
||||
@@ -44,6 +37,18 @@ 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>
|
||||
@@ -86,7 +91,8 @@ public sealed class GiteaRemote : IModelRemote
|
||||
}
|
||||
|
||||
// 没有 Release:清空启动器版本,让上层知道"这个源没有可升级的启动器"
|
||||
Console.WriteLine($"[gitea] {_preset.Name}: Release 为空(模型清单仍可用)");
|
||||
GcLog.Warn($"{_preset.Name}: Release 为空(模型清单仍可用)",
|
||||
$"{_preset.Name}: No Release found (model manifest still available)");
|
||||
result.Launcher.Version = "";
|
||||
result.Launcher.Packages.Clear();
|
||||
|
||||
@@ -110,7 +116,8 @@ public sealed class GiteaRemote : IModelRemote
|
||||
// 清单验签失败或格式不对时直接返回 null,不再把不可信清单交给上层
|
||||
if (verification.Trust == ManifestTrust.Invalid)
|
||||
{
|
||||
Console.Error.WriteLine($"[gitea] 清单验签失败,已拒绝: {verification.Error}");
|
||||
GcLog.Warn($"清单验签失败,已拒绝: {verification.Error}",
|
||||
$"Manifest signature verification failed: {verification.Error}");
|
||||
return null;
|
||||
}
|
||||
if (doc != null)
|
||||
@@ -121,7 +128,8 @@ public sealed class GiteaRemote : IModelRemote
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"[gitea] version.json 读取失败 {url}: {ex.Message}");
|
||||
GcLog.Warn($"version.json 读取失败 {url}: {ex.Message}",
|
||||
$"Failed to read version.json {url}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
return null;
|
||||
@@ -135,7 +143,7 @@ public sealed class GiteaRemote : IModelRemote
|
||||
{
|
||||
try
|
||||
{
|
||||
var json = await Http.GetStringAsync($"{RepoApi}/releases", ct);
|
||||
var json = await Http.GetStringAsync(ReleasesUrl(), ct);
|
||||
using var doc = JsonDocument.Parse(json);
|
||||
if (doc.RootElement.ValueKind != JsonValueKind.Array) return null;
|
||||
|
||||
@@ -152,7 +160,8 @@ public sealed class GiteaRemote : IModelRemote
|
||||
if (candidates.Count == 0)
|
||||
{
|
||||
// 还没发布 Release 是正常状态:交给上层去问另一个源
|
||||
Console.WriteLine($"[gitea] {_preset.Name}: Release 列表为空");
|
||||
GcLog.Info($"{_preset.Name}: Release 列表为空",
|
||||
$"{_preset.Name}: Empty Release list");
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -194,7 +203,8 @@ public sealed class GiteaRemote : IModelRemote
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"[gitea] Release 读取失败({_preset.Name}): {ex.Message}");
|
||||
GcLog.Warn($"Release 读取失败({_preset.Name}): {ex.Message}",
|
||||
$"Failed to read Release ({_preset.Name}): {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -226,12 +236,13 @@ public sealed class GiteaRemote : IModelRemote
|
||||
{
|
||||
if (depth > 8) return;
|
||||
|
||||
var url = $"{RepoRepoContentsUrl()}/{apiPath}";
|
||||
var url = ContentsUrl(apiPath);
|
||||
string json;
|
||||
try { json = await Http.GetStringAsync(url, ct); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"[gitea] 列目录失败 {apiPath}: {ex.Message}");
|
||||
GcLog.Warn($"列目录失败 {apiPath}: {ex.Message}",
|
||||
$"Failed to list directory {apiPath}: {ex.Message}");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -268,8 +279,6 @@ 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() ?? "" : "";
|
||||
@@ -329,12 +338,14 @@ public sealed class GiteaRemote : IModelRemote
|
||||
System.Security.Cryptography.SHA256.HashData(bytes)).ToLowerInvariant();
|
||||
if (!string.Equals(actual, package.Sha256.Trim(), StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
Console.Error.WriteLine($"[gitea] 包校验不符,换下一个来源: {candidate}");
|
||||
GcLog.Warn($"包校验不符,换下一个来源: {candidate}",
|
||||
$"Package hash mismatch, trying next source: {candidate}");
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
Console.WriteLine($"[gitea] 启动器包来源: {candidate}");
|
||||
GcLog.Info($"启动器包来源: {candidate}",
|
||||
$"Launcher package source: {candidate}");
|
||||
return bytes;
|
||||
}
|
||||
return null;
|
||||
|
||||
@@ -21,16 +21,11 @@ namespace GC.Services;
|
||||
public sealed class ModelSourceClient : IModelSourceClient
|
||||
{
|
||||
private readonly AppPaths _paths;
|
||||
private static readonly HttpClient Http = CreateHttp();
|
||||
|
||||
public ModelSourceClient(AppPaths paths) => _paths = paths;
|
||||
|
||||
private static HttpClient CreateHttp()
|
||||
{
|
||||
var client = new HttpClient { Timeout = TimeSpan.FromMinutes(5) };
|
||||
client.DefaultRequestHeaders.UserAgent.ParseAdd("GC/1.0 (+model-source)");
|
||||
return client;
|
||||
}
|
||||
// 使用共享 HttpClient(长超时版本用于大文件下载)
|
||||
private static readonly HttpClient Http = SharedHttpClientFactory.GetLongTimeout();
|
||||
|
||||
public async Task<SourceIndex> FetchAsync(ModelSource source, bool force, IProgress<string>? log, CancellationToken ct)
|
||||
{
|
||||
|
||||
@@ -9,22 +9,18 @@ using System.Threading.Tasks;
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 双源选择:Xhmcl 与 GitCode 是同一份仓库的两个镜像。
|
||||
/// 多源选择:Xhmcl 与 GitHub 是同一份仓库的两个镜像。
|
||||
///
|
||||
/// 启动更新 / 下载页面 / 检查更新时,先并发探测两边的 version.json 响应时间,
|
||||
/// 启动更新 / 下载页面 / 检查更新时,先并发探测各源的 version.json 响应时间,
|
||||
/// 取**最快且内容可用**的那个作为本次下载源;探测结果缓存一段时间,
|
||||
/// 避免每次点下载都重新测速。
|
||||
/// 避免每次点下载都重新测速。单个源探测超时 2 秒,慢源不会拖住整体。
|
||||
/// </summary>
|
||||
public sealed class SourceSelector : ISourceSelector
|
||||
{
|
||||
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;
|
||||
}
|
||||
/// <summary>单源探测超时:超过 2 秒视为不可用(用户可见的「ping 2s」)。</summary>
|
||||
private static readonly TimeSpan ProbeTimeout = TimeSpan.FromSeconds(2);
|
||||
// 使用共享 HttpClient 工厂,统一连接管理,避免端口耗尽
|
||||
private static readonly HttpClient Http = SharedHttpClientFactory.GetDefault();
|
||||
|
||||
private readonly object _lock = new();
|
||||
private SourcePreset? _cached;
|
||||
@@ -71,7 +67,8 @@ public sealed class SourceSelector : ISourceSelector
|
||||
var chosen = usable.Count > 0 ? usable[0].Preset : fallback;
|
||||
|
||||
if (usable.Count == 0)
|
||||
Console.WriteLine($"[selector] 所有源探测失败,退回主源 {chosen.Name}(稍后由实际请求再判定)");
|
||||
GcLog.Warn($"所有源探测失败,退回主源 {chosen.Name}",
|
||||
$"All probes failed, fallback to {chosen.Name}");
|
||||
|
||||
lock (_lock)
|
||||
{
|
||||
@@ -81,17 +78,19 @@ public sealed class SourceSelector : ISourceSelector
|
||||
_cachedAt = usable.Count > 0 ? DateTime.UtcNow : DateTime.MinValue;
|
||||
}
|
||||
|
||||
Console.WriteLine("[selector] 测速:" + string.Join(" ",
|
||||
results.Select(r => $"{r.Preset.Name}={r.Ms}ms{(r.Ok ? "" : "(不可用)")}"))
|
||||
+ $" → 选择 {chosen.Name}");
|
||||
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}");
|
||||
|
||||
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>
|
||||
@@ -102,7 +101,7 @@ public sealed class SourceSelector : ISourceSelector
|
||||
try
|
||||
{
|
||||
using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
cts.CancelAfter(TimeSpan.FromSeconds(5));
|
||||
cts.CancelAfter(ProbeTimeout);
|
||||
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");
|
||||
@@ -121,7 +120,7 @@ public sealed class SourceSelector : ISourceSelector
|
||||
try
|
||||
{
|
||||
using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
cts.CancelAfter(TimeSpan.FromSeconds(5));
|
||||
cts.CancelAfter(ProbeTimeout);
|
||||
var text = await Http.GetStringAsync(url, cts.Token);
|
||||
if (text.TrimStart().StartsWith('{')) return true;
|
||||
}
|
||||
@@ -134,6 +133,9 @@ public sealed class SourceSelector : ISourceSelector
|
||||
public static IModelRemote CreateRemote(SourcePreset preset) => preset.Kind switch
|
||||
{
|
||||
"gitea" => new GiteaRemote(preset),
|
||||
_ => new GitCodeReleaseRemote(null, preset.HomeUrl)
|
||||
// GitHub 的 contents / releases API 与 Gitea 同构,复用同一实现
|
||||
"github" => new GiteaRemote(preset),
|
||||
"gitcode" => new GitCodeReleaseRemote(null, preset.HomeUrl),
|
||||
_ => throw new InvalidOperationException($"未知的源类型: {preset.Kind}")
|
||||
};
|
||||
}
|
||||
@@ -123,6 +123,31 @@ 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,
|
||||
|
||||
@@ -30,15 +30,13 @@ public static class BackendServer
|
||||
{
|
||||
/// <summary>按命令行 / GC_UI_PORT 解析端口并构建(未启动)的后端。</summary>
|
||||
public static WebApplication StartFromCommandLine(string[] args)
|
||||
=> Start(args, ResolvePort(args), out _);
|
||||
|
||||
/// <summary>同上,并交出模型窗口宿主(独立进程入口用:主线程留给 Avalonia)。</summary>
|
||||
public static WebApplication StartFromCommandLine(string[] args, out AvaloniaHost uiHost)
|
||||
=> Start(args, ResolvePort(args), out uiHost);
|
||||
=> Start(args, ResolvePort(args));
|
||||
|
||||
/// <summary>
|
||||
/// 构建后端。返回的 <see cref="WebApplication"/> 尚未启动:
|
||||
/// 独立进程直接 <c>Run()</c>,启动器用 <c>StartAsync()</c> 之后继续拉起界面。
|
||||
///
|
||||
/// 界面是 Flutter,但**模型窗口仍由 Avalonia 承载**(模型契约返回的是 Avalonia Control)。
|
||||
/// </summary>
|
||||
public static WebApplication Start(string[] args, int port)
|
||||
=> Start(args, port, out _);
|
||||
@@ -55,6 +53,7 @@ public static class BackendServer
|
||||
DownloadModuleHost.Factory = new DownloadModuleFactory();
|
||||
|
||||
var services = AppServices.Create();
|
||||
var userService = new UserService(services.Paths.HomeRoot);
|
||||
var host = new AvaloniaHost(services);
|
||||
uiHost = host;
|
||||
|
||||
@@ -200,12 +199,203 @@ public static class BackendServer
|
||||
|
||||
// ---- 健康检查 -------------------------------------------------------------
|
||||
|
||||
app.MapGet("/api/health", () => Results.Ok(new HealthDto(
|
||||
// ---- 用户系统 -----------------------------------------------------------------
|
||||
|
||||
// 简单 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,
|
||||
host.IsAvailable,
|
||||
host.LastError,
|
||||
// 界面在客户端内渲染,后端不存在「窗口宿主不可用」的状态
|
||||
true,
|
||||
(string?)null,
|
||||
GcUiContract.DeriveSessionProof(sessionToken))));
|
||||
|
||||
// ---- 已安装模型 -----------------------------------------------------------
|
||||
@@ -225,6 +415,8 @@ public static class BackendServer
|
||||
return Results.File(package.PreviewPath, GuessImageContentType(package.PreviewPath));
|
||||
});
|
||||
|
||||
// 模型改为客户端内渲染(Flutter):这里只确认模型存在并把 id 交回去,
|
||||
// 不再拉起 Avalonia 窗口。保留接口是为了老客户端不至于 404。
|
||||
app.MapPost("/api/models/{id}/launch", async (string id) =>
|
||||
{
|
||||
if (!IsSafeId(id)) return Results.BadRequest(new LaunchResultDto(false, "模型标识无效"));
|
||||
@@ -239,7 +431,6 @@ public static class BackendServer
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// 细节只写日志,不回显给调用方,避免泄漏本机路径等内部信息。
|
||||
Console.Error.WriteLine($"[launch] 启动模型 {id} 失败: {ex}");
|
||||
return Results.Json(new LaunchResultDto(false, "模型启动失败,请查看后端日志"), statusCode: 503);
|
||||
}
|
||||
@@ -435,6 +626,45 @@ public static class BackendServer
|
||||
.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 () =>
|
||||
@@ -497,7 +727,7 @@ public static class BackendServer
|
||||
|
||||
// ---- 启动 -----------------------------------------------------------------
|
||||
|
||||
WriteEndpointFile(services, port);
|
||||
WriteEndpointFile(services, port, sessionToken);
|
||||
Console.WriteLine($"[GC-UI] 后端已启动: http://127.0.0.1:{port}");
|
||||
Console.WriteLine($"[GC-UI] 模型库: {services.Paths.ModelRoot}");
|
||||
|
||||
@@ -509,7 +739,7 @@ public static class BackendServer
|
||||
|
||||
|
||||
|
||||
static void WriteEndpointFile(AppServices services, int port)
|
||||
static void WriteEndpointFile(AppServices services, int port, string? token)
|
||||
{
|
||||
try
|
||||
{
|
||||
@@ -521,10 +751,19 @@ public static class BackendServer
|
||||
url = $"http://127.0.0.1:{port}",
|
||||
version = LauncherRuntimeInfo.CurrentLauncherVersion,
|
||||
platform = LauncherRuntimeInfo.CurrentRid,
|
||||
startedAt = DateTimeOffset.UtcNow.ToString("o")
|
||||
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)
|
||||
{
|
||||
|
||||
@@ -5,8 +5,8 @@
|
||||
· 后端(本工程):模型扫描 / 下载 / 更新 / 设置 / 模型窗口宿主,只暴露本地 HTTP API
|
||||
· 前端(GC-UI/frontend,Flutter):只做界面,通过 HTTP 调后端
|
||||
|
||||
模型窗口仍然由 .NET 侧承载:模型 dll 返回的是 Avalonia Control,
|
||||
换掉渲染栈等于换掉模型契约,所以「渲染留在 .NET,界面交给 Flutter」是唯一不破坏模型生态的切法。
|
||||
模型渲染也已并入 Flutter(lib/models/):模型不再返回 Avalonia Control,
|
||||
后端只剩纯 HTTP API,不再依赖任何 UI 框架。
|
||||
-->
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
@@ -15,16 +15,10 @@
|
||||
<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" />
|
||||
|
||||
@@ -1,22 +1,8 @@
|
||||
using GC.UI.Server;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
|
||||
// 独立进程入口:`GC.UI.Server --port 17890`
|
||||
// 启动器在进程内直接调用 BackendServer.Start,不会走到这里。
|
||||
var app = BackendServer.StartFromCommandLine(args, out var host);
|
||||
var app = BackendServer.StartFromCommandLine(args);
|
||||
|
||||
// 模型窗口由 Avalonia 承载,macOS 的 AppKit 要求 NSApplication 在主线程。
|
||||
// 所以后端交给 Kestrel 自己的线程池在后台跑,主线程留给 Avalonia 事件循环。
|
||||
app.StartAsync().GetAwaiter().GetResult();
|
||||
host.RunOnCurrentThread();
|
||||
|
||||
if (host.IsAvailable)
|
||||
{
|
||||
// 事件循环结束 → 收尾后端
|
||||
app.StopAsync().GetAwaiter().GetResult();
|
||||
}
|
||||
else
|
||||
{
|
||||
// 无图形环境(无头调试):退化为纯后端常驻
|
||||
app.WaitForShutdown();
|
||||
}
|
||||
// 纯 HTTP 后端(模型渲染在 Flutter 客户端里),跑起来常驻即可。
|
||||
app.Run();
|
||||
@@ -0,0 +1,696 @@
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace GC.UI.Server;
|
||||
|
||||
/// <summary>
|
||||
/// 本地用户系统:注册 / 登录 / 签到 / 积分 / 主题色。
|
||||
///
|
||||
/// 目录结构(都在 .GC/user 下):
|
||||
/// .GC/user/user.yaml 本地登录信息(当前用户 + session token)
|
||||
/// .GC/user/<用户名>/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;
|
||||
}
|
||||
}
|
||||
@@ -138,6 +138,26 @@ class JobInfo {
|
||||
final bool isDone;
|
||||
}
|
||||
|
||||
/// 「重新下载启动器」的结果。
|
||||
///
|
||||
/// State: Ready(已下载并通过 sha256 校验)/ UpToDate(已是最新,无需重下)/ Failed。
|
||||
class LauncherRedownloadInfo {
|
||||
LauncherRedownloadInfo.fromJson(Map<String, dynamic> json)
|
||||
: state = json['state'] as String? ?? '',
|
||||
version = json['version'] as String? ?? '',
|
||||
message = json['message'] as String? ?? '',
|
||||
steps = ((json['steps'] as List<dynamic>?) ?? const <dynamic>[])
|
||||
.map((e) => e.toString())
|
||||
.toList();
|
||||
|
||||
final String state;
|
||||
final String version;
|
||||
final String message;
|
||||
final List<String> steps;
|
||||
|
||||
bool get ok => state == 'Ready' || state == 'UpToDate';
|
||||
}
|
||||
|
||||
/// 界面语言选项。
|
||||
class LanguageInfo {
|
||||
LanguageInfo.fromJson(Map<String, dynamic> json)
|
||||
@@ -336,6 +356,14 @@ class ActionResult {
|
||||
List<String> _stringList(dynamic value) =>
|
||||
(value as List<dynamic>? ?? const []).map((e) => e.toString()).toList();
|
||||
|
||||
/// 握手文件内容。
|
||||
class _Endpoint {
|
||||
const _Endpoint(this.url, this.token);
|
||||
|
||||
final String url;
|
||||
final String? token;
|
||||
}
|
||||
|
||||
/// GC-UI 后端客户端。
|
||||
///
|
||||
/// 后端是本地伴随进程,端口由启动器(GC-BOOT)选定后通过 `GC_UI_PORT`
|
||||
@@ -345,6 +373,9 @@ class GcApi {
|
||||
GcApi({String? baseUrl})
|
||||
: baseUrl = baseUrl ?? defaultBaseUrl;
|
||||
|
||||
/// 后端地址。可被 [rediscover] 更新(后端换端口 / 首次靠握手文件发现)。
|
||||
String baseUrl;
|
||||
|
||||
/// 复用同一个 HTTP 连接:轮询(下载任务每秒一次)时每次都新建连接
|
||||
/// 会不断握手,桌面端也能明显看到延迟抖动。
|
||||
static final http.Client _client = http.Client();
|
||||
@@ -363,63 +394,165 @@ class GcApi {
|
||||
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;
|
||||
// 没有环境变量(例如直接从 Finder 打开 GC-UI.app):读后端写的握手文件。
|
||||
final discovered = _readEndpointFile();
|
||||
if (discovered != null) return discovered.url;
|
||||
|
||||
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;
|
||||
/// 后端启动时写的握手文件:地址 + 会话令牌。
|
||||
static _Endpoint? _endpoint;
|
||||
|
||||
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 (_) {
|
||||
// 文件损坏 / 无权限:退回默认端口即可
|
||||
/// 依次尝试的运行目录。打包后 GC-UI.app 在 GC.app/Contents/MacOS/ 下,
|
||||
/// 直接 Finder 打开时 Directory.current 可能是 `/`,所以要把可执行文件周围都试一遍。
|
||||
static List<String> _candidateRoots() {
|
||||
final roots = <String>[];
|
||||
void add(String path) {
|
||||
if (path.isEmpty) return;
|
||||
final root = path.endsWith('/') ? path.substring(0, path.length - 1) : path;
|
||||
if (!roots.contains(root)) roots.add(root);
|
||||
}
|
||||
return null;
|
||||
|
||||
add(Platform.environment['GC_UI_HOME'] ?? '');
|
||||
try {
|
||||
add(Directory.current.path);
|
||||
} catch (_) {}
|
||||
|
||||
try {
|
||||
var dir = File(Platform.resolvedExecutable).parent;
|
||||
// GC-UI.app/Contents/MacOS -> 逐级向上都可能是 .GC 所在目录
|
||||
for (var i = 0; i < 4; i++) {
|
||||
add(dir.path);
|
||||
if (dir.parent.path == dir.path) break;
|
||||
dir = dir.parent;
|
||||
}
|
||||
} catch (_) {}
|
||||
|
||||
return roots;
|
||||
}
|
||||
|
||||
final String baseUrl;
|
||||
static _Endpoint? _readEndpointFile({bool refresh = false}) {
|
||||
if (!refresh && _endpoint != null) return _endpoint;
|
||||
|
||||
/// 启动器注入的一次性会话令牌。后端在发布包模式下会校验它,
|
||||
/// 防止前端误连到同机其他进程伪造的「后端」。
|
||||
static final String? _sessionToken = _readSessionToken();
|
||||
for (final root in _candidateRoots()) {
|
||||
try {
|
||||
final file = File('$root/.GC/ui-backend.json');
|
||||
try {
|
||||
final logFile = File('${Directory.systemTemp.path}/gc-api-debug.log');
|
||||
logFile.writeAsStringSync('[api] 检查: $root/.GC/ui-backend.json (exists=${file.existsSync()})\n', mode: FileMode.append);
|
||||
} catch (_) {}
|
||||
if (!file.existsSync()) continue;
|
||||
|
||||
// 只认 24 小时内的记录:更早的多半是上次遗留,连过去只会得到「无法连接」
|
||||
final age = DateTime.now().difference(file.lastModifiedSync());
|
||||
if (age.inHours >= 24) continue;
|
||||
|
||||
final decoded = jsonDecode(file.readAsStringSync());
|
||||
if (decoded is! Map<String, dynamic>) continue;
|
||||
|
||||
String? url;
|
||||
final rawUrl = decoded['url'];
|
||||
if (rawUrl is String && rawUrl.startsWith('http://127.0.0.1:')) {
|
||||
url = rawUrl;
|
||||
} else {
|
||||
final port = (decoded['port'] as num?)?.toInt();
|
||||
if (port != null && port > 0 && port < 65536) {
|
||||
url = 'http://127.0.0.1:$port';
|
||||
}
|
||||
}
|
||||
if (url == null) continue;
|
||||
|
||||
final token = decoded['token'];
|
||||
return _endpoint = _Endpoint(url, token is String && token.isNotEmpty ? token : null);
|
||||
} catch (_) {
|
||||
// 文件损坏 / 无权限:试下一个候选目录
|
||||
}
|
||||
}
|
||||
return _endpoint = null;
|
||||
}
|
||||
|
||||
/// 重新解析后端地址与令牌(后端重启换端口、或环境变量缺失时用)。
|
||||
/// 返回 true 表示地址或令牌发生了变化,值得重试一次。
|
||||
bool rediscover() {
|
||||
final before = (_endpoint?.url, _sessionToken);
|
||||
_endpoint = null;
|
||||
final endpoint = _readEndpointFile(refresh: true);
|
||||
|
||||
if (endpoint?.token != null && endpoint!.token != _sessionToken) {
|
||||
_sessionToken = endpoint.token;
|
||||
}
|
||||
|
||||
final envUrl = Platform.environment['GC_UI_BASE_URL'];
|
||||
final envPort = int.tryParse(Platform.environment['GC_UI_PORT'] ?? '');
|
||||
final resolved = (envUrl != null && envUrl.isNotEmpty)
|
||||
? envUrl
|
||||
: (envPort != null
|
||||
? 'http://127.0.0.1:$envPort'
|
||||
: (endpoint?.url ?? 'http://127.0.0.1:$fallbackPort'));
|
||||
|
||||
if (resolved != baseUrl) {
|
||||
baseUrl = resolved;
|
||||
return true;
|
||||
}
|
||||
return (before.$1 != _endpoint?.url) || (before.$2 != _sessionToken);
|
||||
}
|
||||
|
||||
/// 启动器注入的一次性会话令牌:环境变量优先,其次握手文件。
|
||||
/// 后端在发布包模式下校验它,防止前端连到同机伪造的「后端」。
|
||||
static String? _sessionToken = _readSessionToken();
|
||||
|
||||
static String? _readSessionToken() {
|
||||
const fromDefine = String.fromEnvironment('GC_UI_TOKEN');
|
||||
if (fromDefine.isNotEmpty) return fromDefine;
|
||||
final fromEnv = Platform.environment['GC_UI_TOKEN'];
|
||||
return (fromEnv != null && fromEnv.isNotEmpty) ? fromEnv : null;
|
||||
if (fromEnv != null && fromEnv.isNotEmpty) return fromEnv;
|
||||
// 环境变量没传进来(Finder 直接打开 GC-UI.app):用握手文件里的令牌
|
||||
return _readEndpointFile()?.token;
|
||||
}
|
||||
|
||||
/// 是否拿到了会话令牌(诊断用)。
|
||||
bool get hasSessionToken => _sessionToken != null;
|
||||
|
||||
/// 用户 session token:登录时后端返回,只放内存。
|
||||
/// 持久化由后端负责(写 .GC/user/user.yaml),下次启动后端会用它自动登录,
|
||||
/// 前端不需要自己去猜 .GC 在哪。
|
||||
static String? _userToken;
|
||||
static String? get userToken => _userToken;
|
||||
|
||||
/// 带会话令牌的请求头;没有令牌时返回 const 空 map(调试/独立后端模式)。
|
||||
Map<String, String> get _authHeaders =>
|
||||
_sessionToken == null ? const {} : {'X-GC-UI-Token': _sessionToken!};
|
||||
Map<String, String> get _authHeaders => {
|
||||
if (_sessionToken != null) 'X-GC-UI-Token': _sessionToken!,
|
||||
if (_userToken != null) 'X-User-Token': _userToken!,
|
||||
};
|
||||
|
||||
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 {
|
||||
{Map<String, String>? query,
|
||||
Object? body,
|
||||
Duration? timeout}) async {
|
||||
try {
|
||||
return await _sendOnce(method, path,
|
||||
query: query, body: body, timeout: timeout);
|
||||
} on ApiException catch (e) {
|
||||
// HTTP 层错误(后端明确回了 4xx/5xx)不是连接问题,直接抛。
|
||||
if (e.statusCode != null) rethrow;
|
||||
// 连接层失败:可能是电脑睡眠唤醒后旧连接已死,或后端换了端口。
|
||||
// 重新解析地址后重试一次。只对 GET 自动重试——POST(签到/扣积分)
|
||||
// 在连接不确定的情况下重发可能重复计费,宁可让用户手动再点。
|
||||
if (method != 'GET') rethrow;
|
||||
if (!rediscover()) rethrow;
|
||||
return await _sendOnce(method, path,
|
||||
query: query, body: body, timeout: timeout);
|
||||
}
|
||||
}
|
||||
|
||||
Future<dynamic> _sendOnce(String method, String path,
|
||||
{Map<String, String>? query,
|
||||
Object? body,
|
||||
Duration? timeout}) async {
|
||||
final uri = _uri(path, query);
|
||||
final auth = _authHeaders;
|
||||
late http.Response response;
|
||||
@@ -427,18 +560,18 @@ class GcApi {
|
||||
switch (method) {
|
||||
case 'GET':
|
||||
response = await _client.get(uri, headers: auth)
|
||||
.timeout(const Duration(seconds: 30));
|
||||
.timeout(timeout ?? const Duration(seconds: 30));
|
||||
break;
|
||||
case 'POST':
|
||||
response = await _client
|
||||
.post(uri,
|
||||
headers: <String, String>{...auth, 'Content-Type': 'application/json'},
|
||||
body: body == null ? null : jsonEncode(body))
|
||||
.timeout(const Duration(seconds: 120));
|
||||
.timeout(timeout ?? const Duration(seconds: 120));
|
||||
break;
|
||||
case 'DELETE':
|
||||
response = await _client.delete(uri, headers: auth)
|
||||
.timeout(const Duration(seconds: 30));
|
||||
.timeout(timeout ?? const Duration(seconds: 30));
|
||||
break;
|
||||
default:
|
||||
throw ApiException('不支持的方法 $method');
|
||||
@@ -502,6 +635,14 @@ class GcApi {
|
||||
'force': force.toString(),
|
||||
}) as Map<String, dynamic>);
|
||||
|
||||
/// 重新下载本机启动器包,返回时后端已完成 sha256 完整性校验。
|
||||
Future<LauncherRedownloadInfo> redownloadLauncher() async =>
|
||||
LauncherRedownloadInfo.fromJson(await _send(
|
||||
'POST',
|
||||
'/api/launcher/redownload',
|
||||
timeout: const Duration(minutes: 10),
|
||||
) as Map<String, dynamic>);
|
||||
|
||||
Future<List<JobInfo>> jobs() async =>
|
||||
_asList(await _send('GET', '/api/download/jobs')).map(JobInfo.fromJson).toList();
|
||||
|
||||
@@ -546,4 +687,92 @@ class GcApi {
|
||||
'X-GC-UI-Token': _sessionToken!,
|
||||
}).toString();
|
||||
}
|
||||
|
||||
// ==================== 用户系统 ====================
|
||||
|
||||
/// 取一个人机验证题(算术题,5 分钟内有效、一次性)。
|
||||
Future<CaptchaInfo> captcha() async {
|
||||
final r = await _send('GET', '/api/user/captcha');
|
||||
return CaptchaInfo.fromJson(r as Map<String, dynamic>);
|
||||
}
|
||||
|
||||
/// 当前登录用户;未登录返回 null(后端会用 .GC/user/user.yaml 自动登录)。
|
||||
Future<Map<String, dynamic>?> me() async {
|
||||
try {
|
||||
final r = await _send('GET', '/api/user/me');
|
||||
return r as Map<String, dynamic>?;
|
||||
} on ApiException catch (e) {
|
||||
if (e.statusCode == 401 || e.statusCode == 403) {
|
||||
_userToken = null;
|
||||
return null;
|
||||
}
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
Future<Map<String, dynamic>> register(String username, String password,
|
||||
{required String captchaId, required String captchaAnswer}) async {
|
||||
final r = await _send('POST', '/api/user/register', body: {
|
||||
'username': username,
|
||||
'password': password,
|
||||
'captchaId': captchaId,
|
||||
'captcha': captchaAnswer,
|
||||
});
|
||||
return r as Map<String, dynamic>;
|
||||
}
|
||||
|
||||
Future<Map<String, dynamic>> login(String username, String password) async {
|
||||
final r = await _send('POST', '/api/user/login',
|
||||
body: {'username': username, 'password': password});
|
||||
final result = r as Map<String, dynamic>;
|
||||
_userToken = result['session_token'] as String?;
|
||||
return result;
|
||||
}
|
||||
|
||||
/// 退出登录:清掉后端的 user.yaml 与内存 token。
|
||||
Future<void> logout() async {
|
||||
try {
|
||||
await _send('POST', '/api/user/logout');
|
||||
} catch (_) {
|
||||
// 后端连不上也要让界面退出
|
||||
}
|
||||
_userToken = null;
|
||||
}
|
||||
|
||||
Future<Map<String, dynamic>> signin() async {
|
||||
final r = await _send('POST', '/api/user/signin');
|
||||
return r as Map<String, dynamic>;
|
||||
}
|
||||
|
||||
/// 换主题色:只传颜色,价格由后端判定(预置 50 / 自定义 150)。
|
||||
Future<Map<String, dynamic>> changeTheme(String color) async {
|
||||
final r = await _send('POST', '/api/user/theme', body: {'color': color});
|
||||
return r as Map<String, dynamic>;
|
||||
}
|
||||
|
||||
/// 摇人品值。价格由后端算:当天第一次免费,之后按当日次数阶梯计费。
|
||||
Future<Map<String, dynamic>> rollFortune() async {
|
||||
final r = await _send('POST', '/api/user/fortune');
|
||||
return r as Map<String, dynamic>;
|
||||
}
|
||||
|
||||
/// 二选一。当天第一次免费,之后每次 0.5 积分。
|
||||
Future<Map<String, dynamic>> pickOne(String optionA, String optionB) async {
|
||||
final r = await _send('POST', '/api/user/pick',
|
||||
body: {'optionA': optionA, 'optionB': optionB});
|
||||
return r as Map<String, dynamic>;
|
||||
}
|
||||
}
|
||||
|
||||
/// 人机验证题
|
||||
class CaptchaInfo {
|
||||
const CaptchaInfo({required this.id, required this.question});
|
||||
|
||||
final String id;
|
||||
final String question;
|
||||
|
||||
factory CaptchaInfo.fromJson(Map<String, dynamic> json) => CaptchaInfo(
|
||||
id: json['id'] as String? ?? '',
|
||||
question: json['question'] as String? ?? '',
|
||||
);
|
||||
}
|
||||
@@ -67,6 +67,8 @@ class ShellController extends ChangeNotifier {
|
||||
if (settingsResult != null) {
|
||||
settings = settingsResult;
|
||||
_applySettings(settingsResult!);
|
||||
// 主题色现在归用户账号所有(设置页不再提供),启动时按当前用户恢复
|
||||
unawaited(_applyUserTheme());
|
||||
}
|
||||
|
||||
if (firstError != null && settingsResult == null) {
|
||||
@@ -80,29 +82,50 @@ class ShellController extends ChangeNotifier {
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
/// 后端没起来时自动重试(2s、4s、8s…最多 5 次),不必让用户手动点。
|
||||
/// 后端没起来时自动重试(1s、2s、4s、之后每次 8s,共 10 次 ≈ 70 秒),
|
||||
/// 不必让用户手动点。重试前 rediscover() 重新解析地址与令牌。
|
||||
void _scheduleRetry() {
|
||||
if (_retryAttempt >= 5) return;
|
||||
final seconds = 1 << _retryAttempt; // 1,2,4,8,16
|
||||
if (_retryAttempt >= 10) return;
|
||||
final seconds = 1 << _retryAttempt.clamp(0, 3); // 1,2,4,8,8,8…(封顶 8s)
|
||||
_retryAttempt++;
|
||||
_retryTimer?.cancel();
|
||||
_retryTimer = Timer(Duration(seconds: seconds), () {
|
||||
if (settings == null) bootstrap();
|
||||
if (settings == null) {
|
||||
// 后端可能刚换端口(端口占用)或刚写好握手文件:重试前重新解析一次
|
||||
api.rediscover();
|
||||
bootstrap();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void _applySettings(SettingsInfo value) {
|
||||
I18n.setLanguage(value.language);
|
||||
GcPalette.apply(value.accentColor);
|
||||
// 强调色不再来自设置:由用户账号的 theme_color 决定(见 _applyUserTheme)
|
||||
GcPalette.applyTheme(value.theme);
|
||||
}
|
||||
|
||||
/// 按当前登录用户的 theme_color 应用强调色;未登录时保持默认。
|
||||
Future<void> applyUserTheme() => _applyUserTheme();
|
||||
|
||||
Future<void> _applyUserTheme() async {
|
||||
try {
|
||||
final resp = await api.me();
|
||||
final hex = resp?['theme_color'] as String?;
|
||||
if (hex != null && hex.isNotEmpty) GcPalette.apply('#$hex');
|
||||
} catch (_) {
|
||||
// 后端没起来或未登录:保持当前颜色即可
|
||||
}
|
||||
}
|
||||
|
||||
void goTo(int value) {
|
||||
if (index == value) return;
|
||||
index = value;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
// 模型视图已回退为后端开 Avalonia 独立窗口(见 AvaloniaHost),
|
||||
// Flutter 内嵌的 activeModelId / openModel / ModelViewPage 一套已移除。
|
||||
|
||||
/// 模型库有变化(安装 / 删除 / 下载完成):通知首页刷新。
|
||||
void modelsChanged() {
|
||||
modelsRevision++;
|
||||
|
||||
+130
-12
@@ -17,6 +17,7 @@ class I18n {
|
||||
'nav.download': '下载',
|
||||
'nav.settings': '设置',
|
||||
'nav.about': '关于',
|
||||
'nav.user': '用户',
|
||||
'home.title': '模型库',
|
||||
'home.subtitle': '选择模型,用可交互的三维演示讲清自转、公转与四季成因。',
|
||||
'home.launch': '启动模型',
|
||||
@@ -35,7 +36,11 @@ class I18n {
|
||||
'home.stats.sources': '模型源',
|
||||
'home.stats.memory': '内存预算',
|
||||
'home.recent': '选择模型后点击「启动模型」',
|
||||
'home.launchHint': '模型在自己的窗口里运行,可播放/暂停、切换视角并使用教学要点。',
|
||||
'home.noBuiltin': '「{0}」暂时没有内置渲染实现',
|
||||
'model.back': '返回',
|
||||
'model.missing': '这个模型还没有 Flutter 实现',
|
||||
'model.missingHint': '模型窗口已全部改为应用内渲染,该模型暂未迁移。',
|
||||
'home.launchHint': '模型直接在应用内运行,可播放/暂停、切换视角并使用教学要点。',
|
||||
'dl.title': '下载模型',
|
||||
'dl.subtitle': '从内置模型源读取可下载模型;模型源在「设置」里查看。',
|
||||
'dl.sources': '模型源',
|
||||
@@ -70,11 +75,6 @@ class I18n {
|
||||
'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': '渲染帧率',
|
||||
@@ -133,6 +133,10 @@ class I18n {
|
||||
'about.contributorsHint': '来自仓库提交记录',
|
||||
'about.repository': '仓库',
|
||||
'about.openRepository': '打开仓库',
|
||||
'about.redownload': '重新下载启动器',
|
||||
'about.redownloading': '正在下载并校验…',
|
||||
'about.redownloadOk': '已下载 v{0},完整性校验通过(sha256 一致),重启后生效',
|
||||
'about.redownloadFail': '重新下载失败',
|
||||
'about.contributions': '{0} 次提交',
|
||||
'about.noContributors': '暂无贡献者信息',
|
||||
'about.architecture': '架构',
|
||||
@@ -144,6 +148,61 @@ class I18n {
|
||||
'about.thanksHint': '特别感谢以下朋友的支持',
|
||||
'about.thanksGit': 'Git 服务与部署支持',
|
||||
'about.thanksGeo': '地理学科内容指导',
|
||||
'user.points': '积分',
|
||||
'user.days': '连续签到',
|
||||
'user.signin': '签到',
|
||||
'user.login': '登录',
|
||||
'user.register': '注册',
|
||||
'user.pick': '二选一',
|
||||
'user.themeColor': '主题颜色',
|
||||
'user.username': '用户名',
|
||||
'user.password': '密码',
|
||||
'user.option1': '选项一',
|
||||
'user.option2': '选项二',
|
||||
'user.pickRandom': '随机选择',
|
||||
'user.switchToRegister': '没有账号?去注册',
|
||||
'user.switchToLogin': '已有账号?去登录',
|
||||
'user.loginSuccess': '登录成功',
|
||||
'user.registerSuccess': '注册成功',
|
||||
'user.signinSuccess': '签到成功',
|
||||
'user.alreadySigned': '今天已经签到过了',
|
||||
'user.fillAll': '请填写用户名和密码',
|
||||
'user.fillOptions': '请填写两个选项',
|
||||
'user.loginFirst': '请先登录',
|
||||
'user.notLoggedIn': '未登录',
|
||||
'user.loginHint': '登录后可签到攒积分、解锁主题色',
|
||||
'user.logout': '退出登录',
|
||||
'user.logoutDone': '已退出登录',
|
||||
'user.cycleDay': '第 {0} / {1} 天',
|
||||
'user.signedToday': '今天已签到,明天再来',
|
||||
'user.signedTodayShort': '已签到',
|
||||
'user.nextReward': '现在签到可得 {0} 积分',
|
||||
'user.refunded': '已退回',
|
||||
'user.usernameRule': '1–20 个字符,不能有空格,不能与他人重复',
|
||||
'user.captcha': '人机验证',
|
||||
'user.captchaMissing': '请先获取人机验证题',
|
||||
'user.captchaAnswer': '验证码答案',
|
||||
'user.fillCaptcha': '请填写验证码答案',
|
||||
'user.refreshCaptcha': '换一题',
|
||||
'user.noRecharge': '积分只能通过每日签到获得,不提供任何充值渠道。',
|
||||
'user.fortune': '人品值',
|
||||
'user.fortuneDesc': '每天可以无限次计算,纯属娱乐,不影响积分。',
|
||||
'user.fortuneIdle': '点一下,看看今天手气',
|
||||
'user.fortuneRoll': '开始计算',
|
||||
'user.fortuneAgain': '再算一次',
|
||||
'user.pickDesc': '填两个选项,随机帮你选一个。',
|
||||
'user.pickResult': '结果:',
|
||||
'user.themeDesc': '默认蓝色免费;预置色 50 积分一个,自定义色 150 积分一个。',
|
||||
'user.custom': '自定义',
|
||||
'user.customColor': '自定义颜色',
|
||||
'user.customColorCost': '自定义颜色需要 {0} 积分。',
|
||||
'user.confirmBuy': '购买并应用',
|
||||
'user.hexInvalid': '格式应为 #RRGGBB',
|
||||
'user.free': '免费',
|
||||
'user.themeUpdated': '主题色已更新',
|
||||
'user.refundHint': '1 小时内换色可退 80%,当前可退(剩余 {0})',
|
||||
'user.minutes': '分钟',
|
||||
'user.seconds': '秒',
|
||||
},
|
||||
'en': <String, String>{
|
||||
'app.name': 'Morris GC',
|
||||
@@ -153,6 +212,7 @@ class I18n {
|
||||
'nav.download': 'Download',
|
||||
'nav.settings': 'Settings',
|
||||
'nav.about': 'About',
|
||||
'nav.user': 'User',
|
||||
'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',
|
||||
@@ -171,7 +231,11 @@ class I18n {
|
||||
'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.',
|
||||
'home.noBuiltin': '"{0}" has no built-in renderer yet',
|
||||
'model.back': 'Back',
|
||||
'model.missing': 'No Flutter renderer for this model',
|
||||
'model.missingHint': 'Model windows are rendered in-app now; this model has not been migrated yet.',
|
||||
'home.launchHint': 'Models render inside the app 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',
|
||||
@@ -206,11 +270,6 @@ class I18n {
|
||||
'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',
|
||||
@@ -269,6 +328,10 @@ class I18n {
|
||||
'about.contributorsHint': 'From repository commits',
|
||||
'about.repository': 'Repository',
|
||||
'about.openRepository': 'Open repository',
|
||||
'about.redownload': 'Re-download launcher',
|
||||
'about.redownloading': 'Downloading and verifying…',
|
||||
'about.redownloadOk': 'Downloaded v{0}, integrity verified (sha256 matched); applies after restart',
|
||||
'about.redownloadFail': 'Re-download failed',
|
||||
'about.contributions': '{0} commits',
|
||||
'about.noContributors': 'No contributor information',
|
||||
'about.architecture': 'Architecture',
|
||||
@@ -280,6 +343,61 @@ class I18n {
|
||||
'about.thanksHint': 'Special thanks to',
|
||||
'about.thanksGit': 'Git hosting and deployment',
|
||||
'about.thanksGeo': 'Geography content guidance',
|
||||
'user.points': 'Points',
|
||||
'user.days': 'Streak',
|
||||
'user.signin': 'Sign In',
|
||||
'user.login': 'Login',
|
||||
'user.register': 'Register',
|
||||
'user.pick': 'Pick One',
|
||||
'user.themeColor': 'Theme Color',
|
||||
'user.username': 'Username',
|
||||
'user.password': 'Password',
|
||||
'user.option1': 'Option A',
|
||||
'user.option2': 'Option B',
|
||||
'user.pickRandom': 'Random',
|
||||
'user.switchToRegister': 'No account? Register',
|
||||
'user.switchToLogin': 'Have account? Login',
|
||||
'user.loginSuccess': 'Login successful',
|
||||
'user.registerSuccess': 'Registration successful',
|
||||
'user.signinSuccess': 'Signed in',
|
||||
'user.alreadySigned': 'Already signed in today',
|
||||
'user.fillAll': 'Please fill in username and password',
|
||||
'user.fillOptions': 'Please fill in both options',
|
||||
'user.loginFirst': 'Please login first',
|
||||
'user.notLoggedIn': 'Not signed in',
|
||||
'user.loginHint': 'Sign in to earn points and unlock theme colors',
|
||||
'user.logout': 'Sign out',
|
||||
'user.logoutDone': 'Signed out',
|
||||
'user.cycleDay': 'Day {0} / {1}',
|
||||
'user.signedToday': 'Signed in today, come back tomorrow',
|
||||
'user.signedTodayShort': 'Signed',
|
||||
'user.nextReward': 'Sign in now for {0} points',
|
||||
'user.refunded': 'refunded',
|
||||
'user.usernameRule': '1–20 chars, no spaces, must be unique',
|
||||
'user.captcha': 'Verification',
|
||||
'user.captchaMissing': 'Please load the verification question first',
|
||||
'user.captchaAnswer': 'Answer',
|
||||
'user.fillCaptcha': 'Please answer the verification question',
|
||||
'user.refreshCaptcha': 'New question',
|
||||
'user.noRecharge': 'Points come from daily check-ins only. There is no way to buy points.',
|
||||
'user.fortune': 'Luck Meter',
|
||||
'user.fortuneDesc': 'Unlimited rolls per day. Just for fun — no points involved.',
|
||||
'user.fortuneIdle': 'Tap to see how lucky you are today',
|
||||
'user.fortuneRoll': 'Roll',
|
||||
'user.fortuneAgain': 'Roll again',
|
||||
'user.pickDesc': 'Two options, one random pick.',
|
||||
'user.pickResult': 'Result:',
|
||||
'user.themeDesc': 'Default blue is free; preset colors cost 50, custom colors 150.',
|
||||
'user.custom': 'Custom',
|
||||
'user.customColor': 'Custom color',
|
||||
'user.customColorCost': 'A custom color costs {0} points.',
|
||||
'user.confirmBuy': 'Buy & apply',
|
||||
'user.hexInvalid': 'Format must be #RRGGBB',
|
||||
'user.free': 'Free',
|
||||
'user.themeUpdated': 'Theme color updated',
|
||||
'user.refundHint': 'Change within 1 hour for a 80% refund (left {0})',
|
||||
'user.minutes': 'min',
|
||||
'user.seconds': 's',
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
import 'dart:async';
|
||||
import 'dart:math' as math;
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// 模型通用接口,所有 Flutter 模型实现此接口。
|
||||
abstract class GcModel {
|
||||
String get id;
|
||||
String name();
|
||||
String description();
|
||||
Widget buildView(BuildContext context);
|
||||
}
|
||||
@@ -1,378 +0,0 @@
|
||||
import 'dart:math' as math;
|
||||
import 'package:flutter/material.dart';
|
||||
import 'base.dart';
|
||||
import 'contour_model.dart';
|
||||
|
||||
/// 等高线模型 Flutter 实现
|
||||
class ContourModelFlutter implements GcModel {
|
||||
@override
|
||||
final String id = 'contour-map-flutter';
|
||||
|
||||
@override
|
||||
String name() => '等高线地形图 (Flutter)';
|
||||
|
||||
@override
|
||||
String description() => '纯 Flutter 实现的等高线地形模型,支持五大地形切换';
|
||||
|
||||
@override
|
||||
Widget buildView(BuildContext context) {
|
||||
return const _ContourModelView();
|
||||
}
|
||||
}
|
||||
|
||||
class _ContourModelView extends StatefulWidget {
|
||||
const _ContourModelView();
|
||||
|
||||
@override
|
||||
State<_ContourModelView> createState() => _ContourModelViewState();
|
||||
}
|
||||
|
||||
class _ContourModelViewState extends State<_ContourModelView>
|
||||
with TickerProviderStateMixin {
|
||||
late AnimationController _animController;
|
||||
TerrainKind _selectedTerrain = TerrainKind.mountain;
|
||||
bool _isPlaying = false;
|
||||
bool _colored = false;
|
||||
bool _isTopView = false;
|
||||
double _progress = 0;
|
||||
|
||||
final List<TerrainKind> _terrains = [
|
||||
TerrainKind.plain,
|
||||
TerrainKind.hill,
|
||||
TerrainKind.mountain,
|
||||
TerrainKind.plateau,
|
||||
TerrainKind.basin,
|
||||
];
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_animController = AnimationController(
|
||||
vsync: this,
|
||||
duration: const Duration(seconds: 8),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_animController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _togglePlay() {
|
||||
setState(() {
|
||||
_isPlaying = !_isPlaying;
|
||||
});
|
||||
if (_isPlaying) {
|
||||
_animController.repeat();
|
||||
} else {
|
||||
_animController.stop();
|
||||
}
|
||||
}
|
||||
|
||||
void _reset() {
|
||||
setState(() {
|
||||
_isPlaying = false;
|
||||
_progress = 0;
|
||||
_colored = false;
|
||||
_isTopView = false;
|
||||
});
|
||||
_animController.stop();
|
||||
}
|
||||
|
||||
void _selectTerrain(TerrainKind terrain) {
|
||||
setState(() {
|
||||
_selectedTerrain = terrain;
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final isDark = Theme.of(context).brightness == Brightness.dark;
|
||||
final bgColor = isDark ? const Color(0xFF0B1524) : const Color(0xFFE8F0FE);
|
||||
final panelColor = isDark ? const Color(0xFF101E31) : const Color(0xFFF5F7FA);
|
||||
final inkColor = isDark ? const Color(0xFFEAF2FF) : const Color(0xFF111A2E);
|
||||
final mutedColor = isDark ? const Color(0xFF93A8C6) : const Color(0xFF5C6A80);
|
||||
|
||||
return Scaffold(
|
||||
backgroundColor: bgColor,
|
||||
body: Column(
|
||||
children: [
|
||||
// 标题栏
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 12),
|
||||
color: panelColor,
|
||||
child: Row(
|
||||
children: [
|
||||
Text(
|
||||
'等高线地形 · 五大地形',
|
||||
style: TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: inkColor,
|
||||
),
|
||||
),
|
||||
const Spacer(),
|
||||
TextButton.icon(
|
||||
onPressed: _reset,
|
||||
icon: const Icon(Icons.refresh_rounded, size: 16),
|
||||
label: const Text('重置'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
// 五大地形切换
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||
color: panelColor,
|
||||
child: Row(
|
||||
children: [
|
||||
Text(
|
||||
'五大地形:',
|
||||
style: TextStyle(fontSize: 12, color: mutedColor),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
..._terrains.map((t) => _terrainChip(t, _selectedTerrain == t, () => _selectTerrain(t))),
|
||||
],
|
||||
),
|
||||
),
|
||||
// 画布区域
|
||||
Expanded(
|
||||
child: _ContourCanvas(
|
||||
terrain: _selectedTerrain,
|
||||
isPlaying: _isPlaying,
|
||||
progress: _progress,
|
||||
colored: _colored,
|
||||
isTopView: _isTopView,
|
||||
animProgress: _animController.value,
|
||||
),
|
||||
),
|
||||
// 底部控制栏
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
||||
color: panelColor,
|
||||
child: Row(
|
||||
children: [
|
||||
_controlBtn(
|
||||
icon: _isPlaying ? Icons.pause_rounded : Icons.play_arrow_rounded,
|
||||
label: _isPlaying ? '暂停' : '播放',
|
||||
color: const Color(0xFF4D8CFF),
|
||||
onPressed: _togglePlay,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
_controlBtn(
|
||||
icon: Icons.map_rounded,
|
||||
label: _isTopView ? '立体图' : '俯视图',
|
||||
color: panelColor,
|
||||
onPressed: () => setState(() => _isTopView = !_isTopView),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
_controlBtn(
|
||||
icon: Icons.palette_rounded,
|
||||
label: _colored ? '取消上色' : '上色',
|
||||
color: _colored ? const Color(0xFF4D8CFF) : panelColor,
|
||||
onPressed: () => setState(() => _colored = !_colored),
|
||||
),
|
||||
const Spacer(),
|
||||
Expanded(
|
||||
child: LinearProgressIndicator(
|
||||
value: _progress,
|
||||
minHeight: 4,
|
||||
backgroundColor: isDark ? const Color(0xFF1E3350) : const Color(0xFFE3E8F3),
|
||||
valueColor: const AlwaysStoppedAnimation<Color>(Color(0xFF4D8CFF)),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _terrainChip(TerrainKind terrain, bool selected, VoidCallback onTap) {
|
||||
final names = {
|
||||
TerrainKind.plain: '平原',
|
||||
TerrainKind.hill: '丘陵',
|
||||
TerrainKind.mountain: '山地',
|
||||
TerrainKind.plateau: '高原',
|
||||
TerrainKind.basin: '盆地',
|
||||
};
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(right: 6),
|
||||
child: FilterChip(
|
||||
label: Text(names[terrain] ?? ''),
|
||||
selected: selected,
|
||||
onSelected: (_) => onTap(),
|
||||
selectedColor: const Color(0xFF4D8CFF).withOpacity(0.2),
|
||||
checkmarkColor: const Color(0xFF4D8CFF),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _controlBtn({
|
||||
required IconData icon,
|
||||
required String label,
|
||||
required Color color,
|
||||
required VoidCallback onPressed,
|
||||
}) {
|
||||
return TextButton.icon(
|
||||
onPressed: onPressed,
|
||||
icon: Icon(icon, size: 16, color: color),
|
||||
label: Text(label, style: TextStyle(fontSize: 12, color: color)),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 等高线画布
|
||||
class _ContourCanvas extends StatelessWidget {
|
||||
final TerrainKind terrain;
|
||||
final bool isPlaying;
|
||||
final double progress;
|
||||
final bool colored;
|
||||
final bool isTopView;
|
||||
final double animProgress;
|
||||
|
||||
const _ContourCanvas({
|
||||
required this.terrain,
|
||||
required this.isPlaying,
|
||||
required this.progress,
|
||||
required this.colored,
|
||||
required this.isTopView,
|
||||
required this.animProgress,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return CustomPaint(
|
||||
size: Size.infinite,
|
||||
painter: _ContourPainter(
|
||||
terrain: terrain,
|
||||
isPlaying: isPlaying,
|
||||
progress: progress,
|
||||
colored: colored,
|
||||
isTopView: isTopView,
|
||||
animProgress: animProgress,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ContourPainter extends CustomPainter {
|
||||
final TerrainKind terrain;
|
||||
final bool isPlaying;
|
||||
final double progress;
|
||||
final bool colored;
|
||||
final bool isTopView;
|
||||
final double animProgress;
|
||||
|
||||
_ContourPainter({
|
||||
required this.terrain,
|
||||
required this.isPlaying,
|
||||
required this.progress,
|
||||
required this.colored,
|
||||
required this.isTopView,
|
||||
required this.animProgress,
|
||||
});
|
||||
|
||||
@override
|
||||
void paint(Canvas canvas, Size size) {
|
||||
final bgColor = const Color(0xFF08111E);
|
||||
final lineColor = const Color(0xFF4D8CFF);
|
||||
final fillColor = const Color(0xFF1C5FA8);
|
||||
|
||||
canvas.drawColor(bgColor, BlendMode.src);
|
||||
|
||||
// 绘制等高线
|
||||
final center = Offset(size.width / 2, size.height / 2);
|
||||
final radius = math.min(size.width, size.height) * 0.35;
|
||||
|
||||
int contourCount;
|
||||
double maxHeight;
|
||||
|
||||
switch (terrain) {
|
||||
case TerrainKind.plain:
|
||||
contourCount = 3;
|
||||
maxHeight = 60;
|
||||
break;
|
||||
case TerrainKind.hill:
|
||||
contourCount = 8;
|
||||
maxHeight = 180;
|
||||
break;
|
||||
case TerrainKind.mountain:
|
||||
contourCount = 12;
|
||||
maxHeight = 1200;
|
||||
break;
|
||||
case TerrainKind.plateau:
|
||||
contourCount = 10;
|
||||
maxHeight = 1250;
|
||||
break;
|
||||
case TerrainKind.basin:
|
||||
contourCount = 10;
|
||||
maxHeight = 1060;
|
||||
break;
|
||||
}
|
||||
|
||||
final interval = maxHeight / contourCount;
|
||||
|
||||
for (int i = 0; i < contourCount; i++) {
|
||||
final ratio = (i + 1) / contourCount;
|
||||
final progressRatio = isPlaying ? animProgress : progress;
|
||||
|
||||
if (ratio > progressRatio) continue;
|
||||
|
||||
final alpha = colored ? (1 - ratio).clamp(0.2, 1.0) : 1.0;
|
||||
final paint = Paint()
|
||||
..color = colored
|
||||
? fillColor.withOpacity(alpha * 0.3)
|
||||
: lineColor.withOpacity(alpha)
|
||||
..style = colored ? PaintingStyle.fill : PaintingStyle.stroke
|
||||
..strokeWidth = 1.5;
|
||||
|
||||
Path path;
|
||||
if (terrain == TerrainKind.basin) {
|
||||
final r = radius * ratio;
|
||||
path = Path()..addOval(Rect.fromCircle(center: center, radius: r));
|
||||
} else if (terrain == TerrainKind.plateau) {
|
||||
final r = ratio < 0.5
|
||||
? radius * 0.5
|
||||
: radius * (0.5 + (ratio - 0.5) * 0.8);
|
||||
path = Path()..addOval(Rect.fromCircle(center: center, radius: r));
|
||||
} else {
|
||||
final spacing = terrain == TerrainKind.plain ? 0.15 : (terrain == TerrainKind.hill ? 0.1 : 0.08);
|
||||
final r = radius * (1 - ratio * (1 - spacing));
|
||||
path = Path()..addOval(Rect.fromCircle(center: center, radius: r));
|
||||
}
|
||||
|
||||
canvas.drawPath(path, paint);
|
||||
}
|
||||
|
||||
// 绘制山峰标记
|
||||
if (!isTopView && terrain != TerrainKind.plain) {
|
||||
final peakPaint = Paint()
|
||||
..color = const Color(0xFFFFD166)
|
||||
..style = PaintingStyle.fill;
|
||||
canvas.drawCircle(center, radius * 0.08, peakPaint);
|
||||
|
||||
final textPainter = TextPainter(
|
||||
text: TextSpan(
|
||||
text: '${maxHeight.toInt()}m',
|
||||
style: const TextStyle(fontSize: 11, color: Color(0xFFEAF2FF)),
|
||||
),
|
||||
textDirection: TextDirection.ltr,
|
||||
);
|
||||
textPainter.layout();
|
||||
textPainter.paint(canvas, Offset(center.dx + 15, center.dy - 20));
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
bool shouldRepaint(covariant _ContourPainter oldDelegate) {
|
||||
return oldDelegate.terrain != terrain ||
|
||||
oldDelegate.isPlaying != isPlaying ||
|
||||
oldDelegate.progress != progress ||
|
||||
oldDelegate.colored != colored ||
|
||||
oldDelegate.isTopView != isTopView ||
|
||||
oldDelegate.animProgress != animProgress;
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
/// 五大地形枚举(对应 C# TerrainKind)
|
||||
enum TerrainKind {
|
||||
plain, // 平原
|
||||
hill, // 丘陵
|
||||
mountain, // 山地
|
||||
plateau, // 高原
|
||||
basin, // 盆地
|
||||
}
|
||||
|
||||
/// 五大典型地貌部位(对应 C# LandformKind)
|
||||
enum LandformKind {
|
||||
peak, // 山峰
|
||||
ridge, // 山脊
|
||||
valley, // 山谷
|
||||
saddle, // 鞍部
|
||||
cliff, // 陡崖
|
||||
}
|
||||
|
||||
/// 等高线模型状态
|
||||
class ContourState {
|
||||
TerrainKind terrain = TerrainKind.mountain;
|
||||
LandformKind? selectedLandform;
|
||||
double progress = 0;
|
||||
bool isPlaying = false;
|
||||
bool colored = false;
|
||||
bool isTopView = false;
|
||||
}
|
||||
@@ -1,376 +0,0 @@
|
||||
import 'dart:math' as math;
|
||||
import 'package:flutter/material.dart';
|
||||
import 'base.dart';
|
||||
import 'geography_model.dart';
|
||||
|
||||
/// 地球地理模型 Flutter 实现
|
||||
class GeographyModelFlutter implements GcModel {
|
||||
@override
|
||||
final String id = 'earth-geography-flutter';
|
||||
|
||||
@override
|
||||
String name() => '地球地理 (Flutter)';
|
||||
|
||||
@override
|
||||
String description() => '纯 Flutter 实现的地球地理模型,支持五带划分、七大洲四大洋';
|
||||
|
||||
@override
|
||||
Widget buildView(BuildContext context) {
|
||||
return const _GeographyModelView();
|
||||
}
|
||||
|
||||
/// 示例数据:五带
|
||||
List<GeoZone> get defaultZones => [
|
||||
GeoZone(
|
||||
id: 'torrid',
|
||||
nameZh: '热带',
|
||||
nameEn: 'Torrid Zone',
|
||||
latMin: -23.5,
|
||||
latMax: 23.5,
|
||||
descZh: '南北回归线之间,有太阳直射,终年高温。',
|
||||
descEn: 'Between the tropics; the Sun is overhead at some time each year.',
|
||||
),
|
||||
GeoZone(
|
||||
id: 'north-temperate',
|
||||
nameZh: '北温带',
|
||||
nameEn: 'North Temperate',
|
||||
latMin: 23.5,
|
||||
latMax: 66.5,
|
||||
descZh: '北回归线与北极圈之间,四季分明。',
|
||||
descEn: 'Between Tropic of Cancer and Arctic Circle; four distinct seasons.',
|
||||
),
|
||||
GeoZone(
|
||||
id: 'south-temperate',
|
||||
nameZh: '南温带',
|
||||
nameEn: 'South Temperate',
|
||||
latMin: -66.5,
|
||||
latMax: -23.5,
|
||||
descZh: '南回归线与南极圈之间,四季分明。',
|
||||
descEn: 'Between Tropic of Capricorn and Antarctic Circle; four seasons.',
|
||||
),
|
||||
GeoZone(
|
||||
id: 'north-frigid',
|
||||
nameZh: '北寒带',
|
||||
nameEn: 'North Frigid',
|
||||
latMin: 66.5,
|
||||
latMax: 90,
|
||||
descZh: '北极圈以北,终年寒冷,有极昼极夜。',
|
||||
descEn: 'Beyond the Arctic Circle; perpetually cold with polar day/night.',
|
||||
),
|
||||
GeoZone(
|
||||
id: 'south-frigid',
|
||||
nameZh: '南寒带',
|
||||
nameEn: 'South Frigid',
|
||||
latMin: -90,
|
||||
latMax: -66.5,
|
||||
descZh: '南极圈以南,终年寒冷,有极昼极夜。',
|
||||
descEn: 'Beyond the Antarctic Circle; perpetually cold with polar day/night.',
|
||||
),
|
||||
];
|
||||
|
||||
/// 示例数据:五大洲简化轮廓
|
||||
List<Continent> get defaultContinents => [
|
||||
Continent(
|
||||
nameZh: '亚洲',
|
||||
nameEn: 'Asia',
|
||||
points: [
|
||||
[60, 70], [100, 70], [140, 65], [180, 60],
|
||||
[180, 40], [140, 20], [120, 10], [100, 5],
|
||||
[80, 10], [60, 20], [50, 30], [40, 40],
|
||||
],
|
||||
),
|
||||
Continent(
|
||||
nameZh: '非洲',
|
||||
nameEn: 'Africa',
|
||||
points: [
|
||||
[35, 35], [50, 35], [50, 15], [40, 5],
|
||||
[30, -5], [20, -20], [15, -30], [20, -35],
|
||||
[30, -35], [35, -25], [40, -10], [35, 5],
|
||||
],
|
||||
),
|
||||
Continent(
|
||||
nameZh: '欧洲',
|
||||
nameEn: 'Europe',
|
||||
points: [
|
||||
[10, 70], [40, 70], [50, 60], [40, 50],
|
||||
[30, 45], [20, 45], [10, 50], [0, 55],
|
||||
],
|
||||
),
|
||||
Continent(
|
||||
nameZh: '北美洲',
|
||||
nameEn: 'North America',
|
||||
points: [
|
||||
[-170, 70], [-130, 70], [-80, 70], [-60, 50],
|
||||
[-60, 30], [-80, 20], [-100, 20], [-120, 30],
|
||||
[-160, 50], [-170, 60],
|
||||
],
|
||||
),
|
||||
Continent(
|
||||
nameZh: '南美洲',
|
||||
nameEn: 'South America',
|
||||
points: [
|
||||
[-80, 10], [-60, 10], [-35, -5], [-35, -20],
|
||||
[-50, -30], [-65, -50], [-75, -55], [-75, -40],
|
||||
[-70, -20], [-80, 0],
|
||||
],
|
||||
),
|
||||
Continent(
|
||||
nameZh: '大洋洲',
|
||||
nameEn: 'Oceania',
|
||||
points: [
|
||||
[115, -15], [150, -15], [160, -25], [150, -35],
|
||||
[130, -38], [115, -35], [113, -25],
|
||||
],
|
||||
),
|
||||
Continent(
|
||||
nameZh: '南极洲',
|
||||
nameEn: 'Antarctica',
|
||||
points: [
|
||||
[-180, -65], [-90, -65], [0, -65], [90, -65],
|
||||
[180, -65], [180, -90], [-180, -90],
|
||||
],
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
class _GeographyModelView extends StatefulWidget {
|
||||
const _GeographyModelView();
|
||||
|
||||
@override
|
||||
State<_GeographyModelView> createState() => _GeographyModelViewState();
|
||||
}
|
||||
|
||||
class _GeographyModelViewState extends State<_GeographyModelView> {
|
||||
String _activeView = 'zones'; // zones, coast, plates
|
||||
bool _showZones = true;
|
||||
bool _showCoast = true;
|
||||
bool _showPlates = false;
|
||||
|
||||
final GeographyModelFlutter _model = GeographyModelFlutter();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final isDark = Theme.of(context).brightness == Brightness.dark;
|
||||
final bgColor = isDark ? const Color(0xFF0B1524) : const Color(0xFFE8F0FE);
|
||||
final panelColor = isDark ? const Color(0xFF101E31) : const Color(0xFFF5F7FA);
|
||||
final inkColor = isDark ? const Color(0xFFEAF2FF) : const Color(0xFF111A2E);
|
||||
|
||||
return Scaffold(
|
||||
backgroundColor: bgColor,
|
||||
body: Column(
|
||||
children: [
|
||||
// 标题栏
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 12),
|
||||
color: panelColor,
|
||||
child: Row(
|
||||
children: [
|
||||
Text(
|
||||
'地球地理 · 五带与七大洲',
|
||||
style: TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: inkColor,
|
||||
),
|
||||
),
|
||||
const Spacer(),
|
||||
_viewButton('五带', _activeView == 'zones', () => setState(() => _activeView = 'zones')),
|
||||
_viewButton('大洲', _activeView == 'coast', () => setState(() => _activeView = 'coast')),
|
||||
TextButton.icon(
|
||||
onPressed: () => setState(() {
|
||||
_showZones = !_showZones;
|
||||
_showCoast = !_showCoast;
|
||||
}),
|
||||
icon: const Icon(Icons.tune_rounded, size: 16),
|
||||
label: const Text('图层'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
// 地图区域
|
||||
Expanded(
|
||||
child: _GeographyMap(
|
||||
zones: _model.defaultZones,
|
||||
continents: _model.defaultContinents,
|
||||
showZones: _showZones,
|
||||
showCoast: _showCoast,
|
||||
activeView: _activeView,
|
||||
),
|
||||
),
|
||||
// 底部说明
|
||||
if (_activeView == 'zones' && _showZones)
|
||||
Container(
|
||||
padding: const EdgeInsets.all(12),
|
||||
color: panelColor,
|
||||
child: Text(
|
||||
'热带:南北回归线之间 | 温带:回归线与极圈之间 | 寒带:极圈以内',
|
||||
style: TextStyle(fontSize: 12, color: isDark ? const Color(0xFF93A8C6) : const Color(0xFF5C6A80)),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _viewButton(String label, bool active, VoidCallback onTap) {
|
||||
return TextButton(
|
||||
onPressed: onTap,
|
||||
style: TextButton.styleFrom(
|
||||
backgroundColor: active ? const Color(0xFF4D8CFF) : null,
|
||||
foregroundColor: active ? Colors.white : null,
|
||||
),
|
||||
child: Text(label, style: const TextStyle(fontSize: 12)),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _GeographyMap extends StatelessWidget {
|
||||
final List<GeoZone> zones;
|
||||
final List<Continent> continents;
|
||||
final bool showZones;
|
||||
final bool showCoast;
|
||||
final String activeView;
|
||||
|
||||
const _GeographyMap({
|
||||
required this.zones,
|
||||
required this.continents,
|
||||
required this.showZones,
|
||||
required this.showCoast,
|
||||
required this.activeView,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return CustomPaint(
|
||||
size: Size.infinite,
|
||||
painter: _GeographyPainter(
|
||||
zones: zones,
|
||||
continents: continents,
|
||||
showZones: showZones,
|
||||
showCoast: showCoast,
|
||||
activeView: activeView,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _GeographyPainter extends CustomPainter {
|
||||
final List<GeoZone> zones;
|
||||
final List<Continent> continents;
|
||||
final bool showZones;
|
||||
final bool showCoast;
|
||||
final String activeView;
|
||||
|
||||
_GeographyPainter({
|
||||
required this.zones,
|
||||
required this.continents,
|
||||
required this.showZones,
|
||||
required this.showCoast,
|
||||
required this.activeView,
|
||||
});
|
||||
|
||||
/// 经纬度转画布坐标
|
||||
Offset _latLonToOffset(double lon, double lat, Size size) {
|
||||
final x = (lon + 180) / 360 * size.width;
|
||||
final y = (90 - lat) / 180 * size.height;
|
||||
return Offset(x, y);
|
||||
}
|
||||
|
||||
@override
|
||||
void paint(Canvas canvas, Size size) {
|
||||
final bgColor = const Color(0xFF0E2A4A);
|
||||
final oceanColor = const Color(0xFF0E2A4A);
|
||||
final zoneColors = {
|
||||
'torrid': const Color(0xFFFF6B35),
|
||||
'north-temperate': const Color(0xFFFFD93D),
|
||||
'south-temperate': const Color(0xFF6BCB77),
|
||||
'north-frigid': const Color(0xFF4D8CFF),
|
||||
'south-frigid': const Color(0xFF8B5CF6),
|
||||
};
|
||||
|
||||
// 海洋背景
|
||||
canvas.drawColor(oceanColor, BlendMode.src);
|
||||
|
||||
// 绘制五带
|
||||
if (showZones && activeView == 'zones') {
|
||||
final bandHeight = size.height / 9; // 180度纬度分9份
|
||||
final bandColors = [
|
||||
zoneColors['north-frigid']!,
|
||||
zoneColors['north-temperate']!,
|
||||
zoneColors['torrid']!,
|
||||
zoneColors['south-temperate']!,
|
||||
zoneColors['south-frigid']!,
|
||||
];
|
||||
final bandLatRanges = [
|
||||
(66.5, 90),
|
||||
(23.5, 66.5),
|
||||
(-23.5, 23.5),
|
||||
(-66.5, -23.5),
|
||||
(-90, -66.5),
|
||||
];
|
||||
|
||||
for (int i = 0; i < 5; i++) {
|
||||
final (latMin, latMax) = bandLatRanges[i];
|
||||
final y1 = (90 - latMax) / 180 * size.height;
|
||||
final y2 = (90 - latMin) / 180 * size.height;
|
||||
canvas.drawRect(
|
||||
Rect.fromLTWH(0, y1, size.width, y2 - y1),
|
||||
Paint()..color = bandColors[i].withOpacity(0.3),
|
||||
);
|
||||
}
|
||||
|
||||
// 绘制回归线和极圈
|
||||
for (final lat in [23.5, -23.5, 66.5, -66.5]) {
|
||||
final y = (90 - lat) / 180 * size.height;
|
||||
canvas.drawLine(
|
||||
Offset(0, y),
|
||||
Offset(size.width, y),
|
||||
Paint()
|
||||
..color = Colors.white.withOpacity(0.4)
|
||||
..strokeWidth = 1
|
||||
..style = PaintingStyle.stroke
|
||||
..style = PaintingStyle.stroke,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 绘制大陆轮廓
|
||||
if (showCoast && activeView == 'coast') {
|
||||
for (final continent in continents) {
|
||||
if (continent.points.length < 2) continue;
|
||||
|
||||
final path = Path();
|
||||
final start = _latLonToOffset(continent.points[0][0], continent.points[0][1], size);
|
||||
path.moveTo(start.dx, start.dy);
|
||||
|
||||
for (int i = 1; i < continent.points.length; i++) {
|
||||
final p = _latLonToOffset(continent.points[i][0], continent.points[i][1], size);
|
||||
path.lineTo(p.dx, p.dy);
|
||||
}
|
||||
path.close();
|
||||
|
||||
canvas.drawPath(
|
||||
path,
|
||||
Paint()
|
||||
..color = const Color(0xFF4E8C4C)
|
||||
..style = PaintingStyle.fill,
|
||||
);
|
||||
canvas.drawPath(
|
||||
path,
|
||||
Paint()
|
||||
..color = Colors.white.withOpacity(0.6)
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = 1,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
bool shouldRepaint(covariant _GeographyPainter oldDelegate) {
|
||||
return oldDelegate.showZones != showZones ||
|
||||
oldDelegate.showCoast != showCoast ||
|
||||
oldDelegate.activeView != activeView;
|
||||
}
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// 地球地理模型数据
|
||||
class GeoZone {
|
||||
final String id;
|
||||
final String nameZh;
|
||||
final String nameEn;
|
||||
final double latMin;
|
||||
final double latMax;
|
||||
final String descZh;
|
||||
final String descEn;
|
||||
|
||||
GeoZone({
|
||||
required this.id,
|
||||
required this.nameZh,
|
||||
required this.nameEn,
|
||||
required this.latMin,
|
||||
required this.latMax,
|
||||
required this.descZh,
|
||||
required this.descEn,
|
||||
});
|
||||
}
|
||||
|
||||
/// 大陆板块数据
|
||||
class Continent {
|
||||
final String nameZh;
|
||||
final String nameEn;
|
||||
final List<List<double>> points; // [lon, lat]
|
||||
|
||||
Continent({
|
||||
required this.nameZh,
|
||||
required this.nameEn,
|
||||
required this.points,
|
||||
});
|
||||
}
|
||||
|
||||
/// 板块数据
|
||||
class Plate {
|
||||
final String id;
|
||||
final String nameZh;
|
||||
final String nameEn;
|
||||
final List<List<double>> points;
|
||||
|
||||
Plate({
|
||||
required this.id,
|
||||
required this.nameZh,
|
||||
required this.nameEn,
|
||||
required this.points,
|
||||
});
|
||||
}
|
||||
|
||||
/// 洲界线
|
||||
class Border {
|
||||
final String betweenZh;
|
||||
final String betweenEn;
|
||||
final String nameZh;
|
||||
final String nameEn;
|
||||
final List<List<double>> points;
|
||||
|
||||
Border({
|
||||
required this.betweenZh,
|
||||
required this.betweenEn,
|
||||
required this.nameZh,
|
||||
required this.nameEn,
|
||||
required this.points,
|
||||
});
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
/// 模型注册表:所有 Flutter 实现的模型都在这里注册。
|
||||
library;
|
||||
|
||||
export 'base.dart';
|
||||
export 'contour_model.dart';
|
||||
export 'contour_flutter.dart';
|
||||
export 'geography_model.dart';
|
||||
export 'geography_flutter.dart';
|
||||
export 'rotation_flutter.dart';
|
||||
export 'revolution_flutter.dart';
|
||||
export 'scale_model.dart';
|
||||
export 'scale_flutter.dart';
|
||||
|
||||
import 'base.dart';
|
||||
import 'contour_flutter.dart';
|
||||
import 'geography_flutter.dart';
|
||||
import 'rotation_flutter.dart';
|
||||
import 'revolution_flutter.dart';
|
||||
import 'scale_flutter.dart';
|
||||
|
||||
/// 所有可用的 Flutter 模型实例。
|
||||
final List<GcModel> allGcModels = [
|
||||
ContourModelFlutter(),
|
||||
GeographyModelFlutter(),
|
||||
RotationModelFlutter(),
|
||||
RevolutionModelFlutter(),
|
||||
ScaleCalculatorModelFlutter(),
|
||||
];
|
||||
|
||||
/// 根据 id 查找模型。
|
||||
GcModel? findModel(String id) {
|
||||
try {
|
||||
return allGcModels.firstWhere((m) => m.id == id);
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,252 +0,0 @@
|
||||
import 'dart:math' as math;
|
||||
import 'package:flutter/material.dart';
|
||||
import 'base.dart';
|
||||
import 'revolution_model.dart';
|
||||
|
||||
/// 地球公转模型 Flutter 实现
|
||||
class RevolutionModelFlutter implements GcModel {
|
||||
@override
|
||||
final String id = 'earth-revolution-flutter';
|
||||
|
||||
@override
|
||||
String name() => '地球公转 (Flutter)';
|
||||
|
||||
@override
|
||||
String description() => '纯 Flutter 实现的地球公转模型,观察四季成因';
|
||||
|
||||
@override
|
||||
Widget buildView(BuildContext context) {
|
||||
return const _RevolutionModelView();
|
||||
}
|
||||
|
||||
List<Season> get defaultSeasons => [
|
||||
Season(key: 'spring', date: '3/21', declinationDeg: 0, angleDeg: 0,
|
||||
teachingZh: '太阳直射赤道,全球昼夜平分。', teachingEn: 'Sun overhead at equator.'),
|
||||
Season(key: 'summer', date: '6/22', declinationDeg: 23.5, angleDeg: 90,
|
||||
teachingZh: '太阳直射北回归线,北半球昼最长。', teachingEn: 'Sun at Tropic of Cancer.'),
|
||||
Season(key: 'autumn', date: '9/23', declinationDeg: 0, angleDeg: 180,
|
||||
teachingZh: '太阳再次直射赤道,昼夜平分。', teachingEn: 'Sun back at equator.'),
|
||||
Season(key: 'winter', date: '12/22', declinationDeg: -23.5, angleDeg: 270,
|
||||
teachingZh: '太阳直射南回归线,北半球昼最短。', teachingEn: 'Sun at Tropic of Capricorn.'),
|
||||
];
|
||||
}
|
||||
|
||||
class _RevolutionModelView extends StatefulWidget {
|
||||
const _RevolutionModelView();
|
||||
|
||||
@override
|
||||
State<_RevolutionModelView> createState() => _RevolutionModelViewState();
|
||||
}
|
||||
|
||||
class _RevolutionModelViewState extends State<_RevolutionModelView>
|
||||
with TickerProviderStateMixin {
|
||||
late AnimationController _orbitController;
|
||||
bool _isPlaying = true;
|
||||
double _speed = 1.0;
|
||||
int _selectedSeason = 0;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_orbitController = AnimationController(
|
||||
vsync: this,
|
||||
duration: const Duration(seconds: 12),
|
||||
)..repeat();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_orbitController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _togglePlay() {
|
||||
setState(() => _isPlaying = !_isPlaying);
|
||||
if (_isPlaying) _orbitController.repeat();
|
||||
else _orbitController.stop();
|
||||
}
|
||||
|
||||
void _reset() {
|
||||
setState(() {
|
||||
_isPlaying = true;
|
||||
_speed = 1.0;
|
||||
_selectedSeason = 0;
|
||||
});
|
||||
_orbitController.repeat();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final isDark = Theme.of(context).brightness == Brightness.dark;
|
||||
final bgColor = isDark ? const Color(0xFF0B1524) : const Color(0xFFE8F0FE);
|
||||
final panelColor = isDark ? const Color(0xFF101E31) : const Color(0xFFF5F7FA);
|
||||
final inkColor = isDark ? const Color(0xFFEAF2FF) : const Color(0xFF111A2E);
|
||||
|
||||
return Scaffold(
|
||||
backgroundColor: bgColor,
|
||||
body: Column(
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 12),
|
||||
color: panelColor,
|
||||
child: Row(
|
||||
children: [
|
||||
Text('地球公转 · 四季成因', style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: inkColor)),
|
||||
const Spacer(),
|
||||
...['春分', '夏至', '秋分', '冬至'].asMap().entries.map((e) =>
|
||||
Padding(padding: const EdgeInsets.only(left: 6),
|
||||
child: FilterChip(
|
||||
label: Text(e.value, style: const TextStyle(fontSize: 11)),
|
||||
selected: _selectedSeason == e.key,
|
||||
onSelected: (_) => setState(() => _selectedSeason = e.key),
|
||||
selectedColor: const Color(0xFF4D8CFF).withOpacity(0.2),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: _RevolutionOrbit(
|
||||
progress: _orbitController.value,
|
||||
selectedSeason: _selectedSeason,
|
||||
),
|
||||
),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
||||
color: panelColor,
|
||||
child: Row(
|
||||
children: [
|
||||
IconButton(onPressed: _togglePlay, icon: Icon(_isPlaying ? Icons.pause_rounded : Icons.play_arrow_rounded), color: const Color(0xFF4D8CFF)),
|
||||
const SizedBox(width: 16),
|
||||
Text('速度:', style: TextStyle(fontSize: 12, color: isDark ? const Color(0xFF93A8C6) : const Color(0xFF5C6A80))),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(child: Slider(value: _speed, min: 0.1, max: 3.0, divisions: 29, onChanged: (v) => setState(() => _speed = v))),
|
||||
Text('${_speed.toStringAsFixed(1)}x'),
|
||||
const Spacer(),
|
||||
TextButton.icon(onPressed: _reset, icon: const Icon(Icons.refresh_rounded, size: 16), label: const Text('重置')),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _RevolutionOrbit extends StatelessWidget {
|
||||
final double progress;
|
||||
final int selectedSeason;
|
||||
|
||||
const _RevolutionOrbit({required this.progress, required this.selectedSeason});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return CustomPaint(
|
||||
size: Size.infinite,
|
||||
painter: _RevolutionPainter(progress: progress, selectedSeason: selectedSeason),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _RevolutionPainter extends CustomPainter {
|
||||
final double progress;
|
||||
final int selectedSeason;
|
||||
|
||||
_RevolutionPainter({required this.progress, required this.selectedSeason});
|
||||
|
||||
@override
|
||||
void paint(Canvas canvas, Size size) {
|
||||
final bgColor = const Color(0xFF08111E);
|
||||
final sunColor = const Color(0xFFFFC24B);
|
||||
final orbitColor = const Color(0xFF4D8CFF);
|
||||
final earthColor = const Color(0xFF1C5FA8);
|
||||
|
||||
canvas.drawColor(bgColor, BlendMode.src);
|
||||
|
||||
final center = Offset(size.width / 2, size.height / 2);
|
||||
final orbitRadius = math.min(size.width, size.height) * 0.35;
|
||||
|
||||
// 绘制轨道
|
||||
canvas.drawCircle(center, orbitRadius, Paint()
|
||||
..color = orbitColor.withOpacity(0.3)
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = 1.5
|
||||
|
||||
..style = PaintingStyle.stroke);
|
||||
|
||||
// 绘制太阳
|
||||
canvas.drawCircle(center, 30, Paint()
|
||||
..color = sunColor
|
||||
..style = PaintingStyle.fill);
|
||||
|
||||
// 太阳发光效果
|
||||
for (int i = 4; i > 0; i--) {
|
||||
canvas.drawCircle(center, 30 + i * 12, Paint()
|
||||
..color = sunColor.withOpacity(0.1 * (5 - i))
|
||||
..style = PaintingStyle.fill);
|
||||
}
|
||||
|
||||
// 绘制地球位置(根据进度)
|
||||
final angle = progress * 2 * math.pi;
|
||||
final earthX = center.dx + math.cos(angle) * orbitRadius;
|
||||
final earthY = center.dy + math.sin(angle) * orbitRadius;
|
||||
|
||||
// 地球
|
||||
canvas.drawCircle(Offset(earthX, earthY), 15, Paint()
|
||||
..color = earthColor
|
||||
..style = PaintingStyle.fill);
|
||||
|
||||
// 地轴(倾斜23.5度)
|
||||
final tiltAngle = 23.5 * math.pi / 180;
|
||||
canvas.drawLine(
|
||||
Offset(earthX - math.sin(tiltAngle) * 25, earthY - math.cos(tiltAngle) * 25),
|
||||
Offset(earthX + math.sin(tiltAngle) * 25, earthY + math.cos(tiltAngle) * 25),
|
||||
Paint()
|
||||
..color = const Color(0xFFFF6B35)
|
||||
..strokeWidth = 2
|
||||
..style = PaintingStyle.stroke);
|
||||
|
||||
// 标注四个关键位置
|
||||
final seasonLabels = ['春分', '夏至', '秋分', '冬至'];
|
||||
final seasonColors = [const Color(0xFF6BCB77), const Color(0xFFFFD93D), const Color(0xFF4D8CFF), const Color(0xFF8B5CF6)];
|
||||
|
||||
for (int i = 0; i < 4; i++) {
|
||||
final seasonAngle = i * math.pi / 2;
|
||||
final sx = center.dx + math.cos(seasonAngle) * orbitRadius;
|
||||
final sy = center.dy + math.sin(seasonAngle) * orbitRadius;
|
||||
|
||||
// 小圆点标记
|
||||
canvas.drawCircle(Offset(sx, sy), 5, Paint()
|
||||
..color = seasonColors[i]
|
||||
..style = PaintingStyle.fill);
|
||||
|
||||
// 标签
|
||||
final labelX = sx + math.cos(seasonAngle) * 25;
|
||||
final labelY = sy + math.sin(seasonAngle) * 25;
|
||||
final textPainter = TextPainter(
|
||||
text: TextSpan(text: seasonLabels[i], style: const TextStyle(fontSize: 10, color: Color(0xFFEAF2FF))),
|
||||
textDirection: TextDirection.ltr,
|
||||
);
|
||||
textPainter.layout();
|
||||
textPainter.paint(canvas, Offset(labelX - 15, labelY - 8));
|
||||
}
|
||||
|
||||
// 当前选中季节高亮
|
||||
if (selectedSeason >= 0 && selectedSeason < 4) {
|
||||
final selAngle = selectedSeason * math.pi / 2;
|
||||
final selX = center.dx + math.cos(selAngle) * orbitRadius;
|
||||
final selY = center.dy + math.sin(selAngle) * orbitRadius;
|
||||
|
||||
canvas.drawCircle(Offset(selX, selY), 8, Paint()
|
||||
..color = seasonColors[selectedSeason].withOpacity(0.5)
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = 2);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
bool shouldRepaint(covariant _RevolutionPainter oldDelegate) {
|
||||
return oldDelegate.progress != progress || oldDelegate.selectedSeason != selectedSeason;
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// 节气数据
|
||||
class Season {
|
||||
final String key;
|
||||
final String date;
|
||||
final double declinationDeg;
|
||||
final double angleDeg;
|
||||
final String teachingZh;
|
||||
final String teachingEn;
|
||||
|
||||
Season({
|
||||
required this.key,
|
||||
required this.date,
|
||||
required this.declinationDeg,
|
||||
required this.angleDeg,
|
||||
required this.teachingZh,
|
||||
required this.teachingEn,
|
||||
});
|
||||
}
|
||||
|
||||
/// 教学要点
|
||||
class Lesson {
|
||||
final String titleZh;
|
||||
final String titleEn;
|
||||
final String bodyZh;
|
||||
final String bodyEn;
|
||||
final String view;
|
||||
final double? angleDeg;
|
||||
|
||||
Lesson({
|
||||
required this.titleZh,
|
||||
required this.titleEn,
|
||||
required this.bodyZh,
|
||||
required this.bodyEn,
|
||||
required this.view,
|
||||
this.angleDeg,
|
||||
});
|
||||
}
|
||||
@@ -1,330 +0,0 @@
|
||||
import 'dart:math' as math;
|
||||
import 'package:flutter/material.dart';
|
||||
import 'base.dart';
|
||||
|
||||
/// 地球自转模型 Flutter 实现
|
||||
class RotationModelFlutter implements GcModel {
|
||||
@override
|
||||
final String id = 'earth-rotation-flutter';
|
||||
|
||||
@override
|
||||
String name() => '地球自转 (Flutter)';
|
||||
|
||||
@override
|
||||
String description() => '纯 Flutter 实现的地球自转模型,观察昼夜交替、晨昏线';
|
||||
|
||||
@override
|
||||
Widget buildView(BuildContext context) {
|
||||
return const _RotationModelView();
|
||||
}
|
||||
}
|
||||
|
||||
class _RotationModelView extends StatefulWidget {
|
||||
const _RotationModelView();
|
||||
|
||||
@override
|
||||
State<_RotationModelView> createState() => _RotationModelViewState();
|
||||
}
|
||||
|
||||
class _RotationModelViewState extends State<_RotationModelView>
|
||||
with TickerProviderStateMixin {
|
||||
late AnimationController _spinController;
|
||||
late AnimationController _tiltController;
|
||||
bool _isPlaying = true;
|
||||
double _speed = 1.0;
|
||||
bool _showLabels = true;
|
||||
bool _showTilt = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_spinController = AnimationController(
|
||||
vsync: this,
|
||||
duration: const Duration(seconds: 10),
|
||||
)..repeat();
|
||||
_tiltController = AnimationController(
|
||||
vsync: this,
|
||||
duration: const Duration(milliseconds: 500),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_spinController.dispose();
|
||||
_tiltController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _togglePlay() {
|
||||
setState(() {
|
||||
_isPlaying = !_isPlaying;
|
||||
});
|
||||
if (_isPlaying) {
|
||||
_spinController.repeat();
|
||||
} else {
|
||||
_spinController.stop();
|
||||
}
|
||||
}
|
||||
|
||||
void _reset() {
|
||||
setState(() {
|
||||
_isPlaying = true;
|
||||
_speed = 1.0;
|
||||
_showLabels = true;
|
||||
_showTilt = false;
|
||||
});
|
||||
_spinController.repeat();
|
||||
_tiltController.reset();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final isDark = Theme.of(context).brightness == Brightness.dark;
|
||||
final bgColor = isDark ? const Color(0xFF0B1524) : const Color(0xFFE8F0FE);
|
||||
final panelColor = isDark ? const Color(0xFF101E31) : const Color(0xFFF5F7FA);
|
||||
final inkColor = isDark ? const Color(0xFFEAF2FF) : const Color(0xFF111A2E);
|
||||
|
||||
return Scaffold(
|
||||
backgroundColor: bgColor,
|
||||
body: Column(
|
||||
children: [
|
||||
// 标题栏
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 12),
|
||||
color: panelColor,
|
||||
child: Row(
|
||||
children: [
|
||||
Text(
|
||||
'地球自转 · 昼夜交替',
|
||||
style: TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: inkColor,
|
||||
),
|
||||
),
|
||||
const Spacer(),
|
||||
_toggleButton('标注', _showLabels, () => setState(() => _showLabels = !_showLabels)),
|
||||
_toggleButton('倾角', _showTilt, () => setState(() => _showTilt = !_showTilt)),
|
||||
const SizedBox(width: 8),
|
||||
TextButton.icon(
|
||||
onPressed: _reset,
|
||||
icon: const Icon(Icons.refresh_rounded, size: 16),
|
||||
label: const Text('重置'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
// 地球动画
|
||||
Expanded(
|
||||
child: _RotationEarth(
|
||||
animProgress: _spinController.value,
|
||||
showLabels: _showLabels,
|
||||
showTilt: _showTilt,
|
||||
isPlaying: _isPlaying,
|
||||
),
|
||||
),
|
||||
// 底部控制栏
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
||||
color: panelColor,
|
||||
child: Row(
|
||||
children: [
|
||||
IconButton(
|
||||
onPressed: _togglePlay,
|
||||
icon: Icon(_isPlaying ? Icons.pause_rounded : Icons.play_arrow_rounded),
|
||||
color: const Color(0xFF4D8CFF),
|
||||
),
|
||||
const SizedBox(width: 16),
|
||||
Text('速度:', style: TextStyle(fontSize: 12, color: isDark ? const Color(0xFF93A8C6) : const Color(0xFF5C6A80))),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Slider(
|
||||
value: _speed,
|
||||
min: 0.1,
|
||||
max: 3.0,
|
||||
divisions: 29,
|
||||
onChanged: (v) => setState(() => _speed = v),
|
||||
),
|
||||
),
|
||||
Text('${_speed.toStringAsFixed(1)}x', style: const TextStyle(fontSize: 12)),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _toggleButton(String label, bool active, VoidCallback onTap) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(left: 8),
|
||||
child: FilterChip(
|
||||
label: Text(label, style: const TextStyle(fontSize: 12)),
|
||||
selected: active,
|
||||
onSelected: (_) => onTap(),
|
||||
selectedColor: const Color(0xFF4D8CFF).withOpacity(0.2),
|
||||
checkmarkColor: const Color(0xFF4D8CFF),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _RotationEarth extends StatelessWidget {
|
||||
final double animProgress;
|
||||
final bool showLabels;
|
||||
final bool showTilt;
|
||||
final bool isPlaying;
|
||||
|
||||
const _RotationEarth({
|
||||
required this.animProgress,
|
||||
required this.showLabels,
|
||||
required this.showTilt,
|
||||
required this.isPlaying,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return CustomPaint(
|
||||
size: Size.infinite,
|
||||
painter: _RotationPainter(
|
||||
animProgress: animProgress,
|
||||
showLabels: showLabels,
|
||||
showTilt: showTilt,
|
||||
isPlaying: isPlaying,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _RotationPainter extends CustomPainter {
|
||||
final double animProgress;
|
||||
final bool showLabels;
|
||||
final bool showTilt;
|
||||
final bool isPlaying;
|
||||
|
||||
_RotationPainter({
|
||||
required this.animProgress,
|
||||
required this.showLabels,
|
||||
required this.showTilt,
|
||||
required this.isPlaying,
|
||||
});
|
||||
|
||||
@override
|
||||
void paint(Canvas canvas, Size size) {
|
||||
final bgColor = const Color(0xFF08111E);
|
||||
final earthColor = const Color(0xFF1C5FA8);
|
||||
final landColor = const Color(0xFF4E8C4C);
|
||||
final iceColor = const Color(0xFFE9EFF6);
|
||||
final axisColor = const Color(0xFFFF6B35);
|
||||
final labelColor = const Color(0xFFEAF2FF);
|
||||
|
||||
canvas.drawColor(bgColor, BlendMode.src);
|
||||
|
||||
final center = Offset(size.width / 2, size.height / 2);
|
||||
final radius = math.min(size.width, size.height) * 0.3;
|
||||
|
||||
// 绘制地球球体
|
||||
final earthPaint = Paint()
|
||||
..color = earthColor
|
||||
..style = PaintingStyle.fill;
|
||||
canvas.drawCircle(center, radius, earthPaint);
|
||||
|
||||
// 绘制大陆(简化版,用椭圆模拟)
|
||||
final continents = [
|
||||
(center.dx - radius * 0.3, center.dy - radius * 0.2, radius * 0.25, radius * 0.35), // 亚洲
|
||||
(center.dx + radius * 0.2, center.dy - radius * 0.1, radius * 0.2, radius * 0.25), // 欧洲
|
||||
(center.dx - radius * 0.1, center.dy + radius * 0.2, radius * 0.15, radius * 0.3), // 非洲
|
||||
(center.dx + radius * 0.35, center.dy + radius * 0.1, radius * 0.2, radius * 0.25), // 北美
|
||||
(center.dx + radius * 0.3, center.dy + radius * 0.4, radius * 0.15, radius * 0.2), // 南美
|
||||
];
|
||||
|
||||
for (final cont in continents) {
|
||||
canvas.drawOval(
|
||||
Rect.fromLTWH(cont.$1 - cont.$3 / 2, cont.$2 - cont.$4 / 2, cont.$3, cont.$4),
|
||||
Paint()..color = landColor,
|
||||
);
|
||||
}
|
||||
|
||||
// 绘制极冰
|
||||
canvas.drawOval(
|
||||
Rect.fromLTWH(center.dx - radius * 0.15, center.dy - radius * 0.95, radius * 0.3, radius * 0.15),
|
||||
Paint()..color = iceColor,
|
||||
);
|
||||
canvas.drawOval(
|
||||
Rect.fromLTWH(center.dx - radius * 0.15, center.dy + radius * 0.8, radius * 0.3, radius * 0.15),
|
||||
Paint()..color = iceColor,
|
||||
);
|
||||
|
||||
// 绘制地轴
|
||||
if (showTilt) {
|
||||
final tiltAngle = 23.5 * math.pi / 180;
|
||||
final axisLength = radius * 1.4;
|
||||
final topY = center.dy - axisLength / 2;
|
||||
final bottomY = center.dy + axisLength / 2;
|
||||
final offsetX = math.sin(tiltAngle) * axisLength / 2;
|
||||
|
||||
canvas.drawLine(
|
||||
Offset(center.dx - offsetX, topY),
|
||||
Offset(center.dx + offsetX, bottomY),
|
||||
Paint()
|
||||
..color = axisColor
|
||||
..strokeWidth = 2
|
||||
..style = PaintingStyle.stroke,
|
||||
);
|
||||
|
||||
// 北极标注
|
||||
if (showLabels) {
|
||||
final textPainter = TextPainter(
|
||||
text: const TextSpan(text: '北极', style: TextStyle(fontSize: 11, color: Color(0xFFFF6B35))),
|
||||
textDirection: TextDirection.ltr,
|
||||
);
|
||||
textPainter.layout();
|
||||
textPainter.paint(canvas, Offset(center.dx + offsetX + 10, topY - 5));
|
||||
}
|
||||
}
|
||||
|
||||
// 绘制晨昏线(昼夜分界)
|
||||
final sunAngle = animProgress * 2 * math.pi;
|
||||
final terminatorX = center.dx + math.cos(sunAngle) * radius * 0.3;
|
||||
|
||||
// 昼半球高光
|
||||
final dayPaint = Paint()
|
||||
..color = Colors.yellow.withOpacity(0.15)
|
||||
..style = PaintingStyle.fill;
|
||||
canvas.drawCircle(
|
||||
Offset(terminatorX + math.cos(sunAngle) * radius * 0.3, center.dy),
|
||||
radius * 0.9,
|
||||
dayPaint,
|
||||
);
|
||||
|
||||
// 标注直射点
|
||||
if (showLabels) {
|
||||
final subsolarX = center.dx + math.cos(sunAngle) * radius;
|
||||
final subsolarY = center.dy + math.sin(sunAngle * 0.3) * radius * 0.5;
|
||||
|
||||
// 太阳光线
|
||||
canvas.drawLine(
|
||||
Offset(subsolarX + math.cos(sunAngle) * 20, subsolarY + math.sin(sunAngle) * 20),
|
||||
Offset(subsolarX + math.cos(sunAngle) * 50, subsolarY + math.sin(sunAngle) * 50),
|
||||
Paint()
|
||||
..color = const Color(0xFFFFC24B)
|
||||
..strokeWidth = 2
|
||||
..style = PaintingStyle.stroke,
|
||||
);
|
||||
|
||||
final textPainter = TextPainter(
|
||||
text: const TextSpan(text: '直射点', style: TextStyle(fontSize: 10, color: Color(0xFFFFC24B))),
|
||||
textDirection: TextDirection.ltr,
|
||||
);
|
||||
textPainter.layout();
|
||||
textPainter.paint(canvas, Offset(subsolarX + 15, subsolarY - 10));
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
bool shouldRepaint(covariant _RotationPainter oldDelegate) {
|
||||
return oldDelegate.animProgress != animProgress ||
|
||||
oldDelegate.showLabels != showLabels ||
|
||||
oldDelegate.showTilt != showTilt;
|
||||
}
|
||||
}
|
||||
@@ -1,217 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'base.dart';
|
||||
import 'scale_model.dart';
|
||||
|
||||
class ScaleCalculatorModelFlutter implements GcModel {
|
||||
@override
|
||||
final String id = 'scale-calculator-flutter';
|
||||
@override
|
||||
String name() => '比例尺计算器 (Flutter)';
|
||||
@override
|
||||
String description() => '纯 Flutter 实现的比例尺计算器';
|
||||
@override
|
||||
Widget buildView(BuildContext context) => const _ScaleCalculatorView();
|
||||
|
||||
List<ScalePreset> get presets => [
|
||||
ScalePreset(n: 10000, nameKey: 'preset.campus', noteKey: 'preset.campusNote'),
|
||||
ScalePreset(n: 50000, nameKey: 'preset.town', noteKey: 'preset.townNote'),
|
||||
ScalePreset(n: 250000, nameKey: 'preset.city', noteKey: 'preset.cityNote'),
|
||||
ScalePreset(n: 1000000, nameKey: 'preset.province', noteKey: 'preset.provinceNote'),
|
||||
ScalePreset(n: 10000000, nameKey: 'preset.china', noteKey: 'preset.chinaNote'),
|
||||
ScalePreset(n: 100000000, nameKey: 'preset.world', noteKey: 'preset.worldNote'),
|
||||
];
|
||||
|
||||
List<ScaleSpectrum> get spectrum => [
|
||||
ScaleSpectrum(n: 10000, labelKey: 'spec.campus', scopeKey: 'spec.campusScope'),
|
||||
ScaleSpectrum(n: 250000, labelKey: 'spec.city', scopeKey: 'spec.cityScope'),
|
||||
ScaleSpectrum(n: 10000000, labelKey: 'spec.china', scopeKey: 'spec.chinaScope'),
|
||||
ScaleSpectrum(n: 100000000, labelKey: 'spec.world', scopeKey: 'spec.worldScope'),
|
||||
];
|
||||
|
||||
List<Landmark> get landmarks => [
|
||||
Landmark(nameKey: 'lm.classroom', meters: 10),
|
||||
Landmark(nameKey: 'lm.track', meters: 400),
|
||||
Landmark(nameKey: 'lm.marathon', meters: 42195),
|
||||
Landmark(nameKey: 'lm.beijingShanghai', meters: 1080000),
|
||||
Landmark(nameKey: 'lm.equator', meters: 40000000),
|
||||
];
|
||||
}
|
||||
|
||||
class _ScaleCalculatorView extends StatefulWidget {
|
||||
const _ScaleCalculatorView();
|
||||
@override
|
||||
State<_ScaleCalculatorView> createState() => _ScaleCalculatorViewState();
|
||||
}
|
||||
|
||||
class _ScaleCalculatorViewState extends State<_ScaleCalculatorView> {
|
||||
String _mode = 'real';
|
||||
double _mapDist = 10;
|
||||
double _realDist = 100000;
|
||||
double _scaleN = 10000.0;
|
||||
String _unit = 'cm';
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final isDark = Theme.of(context).brightness == Brightness.dark;
|
||||
final bgColor = isDark ? const Color(0xFF0B1524) : const Color(0xFFE8F0FE);
|
||||
final panelColor = isDark ? const Color(0xFF101E31) : const Color(0xFFF5F7FA);
|
||||
final inkColor = isDark ? const Color(0xFFEAF2FF) : const Color(0xFF111A2E);
|
||||
|
||||
return Scaffold(
|
||||
backgroundColor: bgColor,
|
||||
body: Column(
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 12),
|
||||
color: panelColor,
|
||||
child: Row(
|
||||
children: [
|
||||
Text('比例尺计算器', style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: inkColor)),
|
||||
const Spacer(),
|
||||
_modeBtn('求实地距离', _mode == 'real'),
|
||||
_modeBtn('求图上距离', _mode == 'map'),
|
||||
_modeBtn('求比例尺', _mode == 'scale'),
|
||||
],
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: _ScaleCanvas(
|
||||
mode: _mode,
|
||||
mapDist: _mapDist,
|
||||
realDist: _realDist,
|
||||
scaleN: _scaleN,
|
||||
unit: _unit,
|
||||
),
|
||||
),
|
||||
Container(
|
||||
padding: const EdgeInsets.all(16),
|
||||
color: panelColor,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text('已知量:', style: TextStyle(fontSize: 12, color: isDark ? const Color(0xFF93A8C6) : const Color(0xFF5C6A80))),
|
||||
const SizedBox(height: 8),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: TextField(
|
||||
decoration: const InputDecoration(labelText: '图上距离 (cm)'),
|
||||
keyboardType: TextInputType.number,
|
||||
onChanged: (v) => setState(() => _mapDist = double.tryParse(v) ?? 0),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: TextField(
|
||||
decoration: const InputDecoration(labelText: '比例尺 N'),
|
||||
keyboardType: TextInputType.number,
|
||||
onChanged: (v) => setState(() => _scaleN = double.tryParse(v) ?? 10000.0),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Row(
|
||||
children: [
|
||||
Text('结果:', style: TextStyle(fontSize: 12, color: isDark ? const Color(0xFF93A8C6) : const Color(0xFF5C6A80))),
|
||||
const SizedBox(width: 8),
|
||||
Text('实地距离 = ${(_mapDist * _scaleN / 100).toStringAsFixed(2)} m', style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w600, color: Color(0xFF4D8CFF))),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _modeBtn(String label, bool active) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(left: 6),
|
||||
child: FilterChip(
|
||||
label: Text(label, style: const TextStyle(fontSize: 12)),
|
||||
selected: active,
|
||||
onSelected: (_) => setState(() => _mode = active ? 'real' : 'real'),
|
||||
selectedColor: const Color(0xFF4D8CFF).withOpacity(0.2),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ScaleCanvas extends StatelessWidget {
|
||||
final String mode;
|
||||
final double mapDist;
|
||||
final double realDist;
|
||||
final double scaleN;
|
||||
final String unit;
|
||||
|
||||
const _ScaleCanvas({required this.mode, required this.mapDist, required this.realDist, required this.scaleN, required this.unit});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return CustomPaint(
|
||||
size: Size.infinite,
|
||||
painter: _ScalePainter(mode: mode, mapDist: mapDist, realDist: realDist, scaleN: scaleN, unit: unit),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ScalePainter extends CustomPainter {
|
||||
final String mode;
|
||||
final double mapDist;
|
||||
final double realDist;
|
||||
final double scaleN;
|
||||
final String unit;
|
||||
|
||||
_ScalePainter({required this.mode, required this.mapDist, required this.realDist, required this.scaleN, required this.unit});
|
||||
|
||||
@override
|
||||
void paint(Canvas canvas, Size size) {
|
||||
final isDark = true;
|
||||
final bgColor = const Color(0xFF08111E);
|
||||
final barColor = const Color(0xFF4D8CFF);
|
||||
final inkColor = const Color(0xFFEAF2FF);
|
||||
|
||||
canvas.drawColor(bgColor, BlendMode.src);
|
||||
|
||||
final centerY = size.height / 2;
|
||||
final double barHeight = 40.0;
|
||||
final barY = centerY - barHeight / 2;
|
||||
final maxBarWidth = size.width * 0.8;
|
||||
final startX = (size.width - maxBarWidth) / 2;
|
||||
|
||||
// 绘制标尺
|
||||
canvas.drawRRect(
|
||||
RRect.fromRectAndRadius(Rect.fromLTWH(startX, barY, maxBarWidth, barHeight), Radius.circular(4.0)),
|
||||
Paint()..color = barColor.withOpacity(0.2),
|
||||
);
|
||||
|
||||
// 刻度
|
||||
final double tickCount = 20.0;
|
||||
for (int i = 0; i <= tickCount; i++) {
|
||||
final x = startX + (maxBarWidth * i / tickCount);
|
||||
final double tickHeight = i % 5 == 0 ? 15.0 : 8.0;
|
||||
canvas.drawLine(
|
||||
Offset(x, barY + (barHeight - tickHeight) / 2),
|
||||
Offset(x, barY + (barHeight + tickHeight) / 2),
|
||||
Paint()
|
||||
..color = inkColor
|
||||
..strokeWidth = 1,
|
||||
);
|
||||
}
|
||||
|
||||
// 数值标注
|
||||
final textPainter = TextPainter(
|
||||
text: TextSpan(text: '1 : $scaleN', style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w600, color: Color(0xFF4D8CFF))),
|
||||
textDirection: TextDirection.ltr,
|
||||
);
|
||||
textPainter.layout();
|
||||
textPainter.paint(canvas, Offset(size.width / 2 - 40, barY + barHeight + 16));
|
||||
}
|
||||
|
||||
@override
|
||||
bool shouldRepaint(covariant _ScalePainter oldDelegate) {
|
||||
return oldDelegate.mode != mode || oldDelegate.scaleN != scaleN;
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// 比例尺预设
|
||||
class ScalePreset {
|
||||
final int n;
|
||||
final String nameKey;
|
||||
final String noteKey;
|
||||
|
||||
ScalePreset({required this.n, required this.nameKey, required this.noteKey});
|
||||
}
|
||||
|
||||
/// 比例尺光谱
|
||||
class ScaleSpectrum {
|
||||
final int n;
|
||||
final String labelKey;
|
||||
final String scopeKey;
|
||||
|
||||
ScaleSpectrum({required this.n, required this.labelKey, required this.scopeKey});
|
||||
}
|
||||
|
||||
/// 真实地标
|
||||
class Landmark {
|
||||
final String nameKey;
|
||||
final double meters;
|
||||
|
||||
Landmark({required this.nameKey, required this.meters});
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
/// 用户记录(对应后端 UserPayload)
|
||||
class UserRecord {
|
||||
const UserRecord({
|
||||
required this.username,
|
||||
required this.points,
|
||||
required this.consecutiveDays,
|
||||
required this.cycleDay,
|
||||
required this.cycleDays,
|
||||
required this.todaySigned,
|
||||
required this.nextReward,
|
||||
this.lastSignIn,
|
||||
this.themeColor,
|
||||
this.themePaid = 0,
|
||||
this.refundSeconds = 0,
|
||||
});
|
||||
|
||||
final String username;
|
||||
|
||||
/// 积分,精确到 0.01
|
||||
final double points;
|
||||
|
||||
/// 连续签到天数(断签会重置)
|
||||
final int consecutiveDays;
|
||||
|
||||
/// 当前处在 30 天周期的第几天(1–30)
|
||||
final int cycleDay;
|
||||
|
||||
/// 周期长度,固定 30
|
||||
final int cycleDays;
|
||||
|
||||
/// 今天是否已签到
|
||||
final bool todaySigned;
|
||||
|
||||
/// 下一次签到能拿多少分
|
||||
final int nextReward;
|
||||
|
||||
final String? lastSignIn;
|
||||
|
||||
/// 形如 `4A90D9`(不带 #)
|
||||
final String? themeColor;
|
||||
|
||||
/// 当前这个颜色实际花了多少分
|
||||
final double themePaid;
|
||||
|
||||
/// 退款窗口剩余秒数(0 表示没有可退的)
|
||||
final int refundSeconds;
|
||||
|
||||
factory UserRecord.fromJson(Map<String, dynamic> json) {
|
||||
return UserRecord(
|
||||
username: json['username'] as String? ?? '',
|
||||
points: (json['points'] as num?)?.toDouble() ?? 0,
|
||||
consecutiveDays: (json['consecutive_days'] as num?)?.toInt() ?? 0,
|
||||
cycleDay: (json['cycle_day'] as num?)?.toInt() ?? 1,
|
||||
cycleDays: (json['cycle_days'] as num?)?.toInt() ?? 30,
|
||||
todaySigned: json['today_signed'] as bool? ?? false,
|
||||
nextReward: (json['next_reward'] as num?)?.toInt() ?? 10,
|
||||
lastSignIn: json['last_sign_in'] as String?,
|
||||
themeColor: json['theme_color'] as String?,
|
||||
themePaid: (json['theme_paid'] as num?)?.toDouble() ?? 0,
|
||||
refundSeconds: (json['refund_seconds'] as num?)?.toInt() ?? 0,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 签到奖励:30 天一循环,第 7/14/21/28 天给周奖励,第 30 天给满月奖励。
|
||||
/// 与后端 `UserService.GetSignInReward` 保持一致。
|
||||
class SignInRewards {
|
||||
static const int cycleDays = 30;
|
||||
|
||||
static int getReward(int day) {
|
||||
var d = day;
|
||||
if (d < 1) d = 1;
|
||||
if (d > cycleDays) d = ((d - 1) % cycleDays) + 1;
|
||||
switch (d) {
|
||||
case 7:
|
||||
return 30;
|
||||
case 14:
|
||||
return 40;
|
||||
case 21:
|
||||
return 50;
|
||||
case 28:
|
||||
return 60;
|
||||
case 30:
|
||||
return 100;
|
||||
}
|
||||
if (d <= 6) return 10;
|
||||
if (d <= 13) return 15;
|
||||
if (d <= 20) return 20;
|
||||
if (d <= 27) return 25;
|
||||
return 40;
|
||||
}
|
||||
}
|
||||
|
||||
/// 主题颜色:预置色 50 分一个,自定义色 150 分一个,默认蓝免费。
|
||||
class ThemeColor {
|
||||
const ThemeColor({required this.name, required this.hex, required this.cost});
|
||||
|
||||
final String name;
|
||||
final String hex;
|
||||
final int cost;
|
||||
|
||||
/// 默认色(免费)
|
||||
static const String defaultHex = '4A90D9';
|
||||
|
||||
/// 预置色单价
|
||||
static const int presetCost = 50;
|
||||
|
||||
/// 自定义色单价
|
||||
static const int customCost = 150;
|
||||
|
||||
/// 购买后 1 小时内换色可退 80%
|
||||
static const Duration refundWindow = Duration(hours: 1);
|
||||
static const double refundRate = 0.8;
|
||||
|
||||
static const List<ThemeColor> predefined = <ThemeColor>[
|
||||
ThemeColor(name: '蓝色', hex: defaultHex, cost: 0),
|
||||
ThemeColor(name: '红色', hex: 'E74C3C', cost: presetCost),
|
||||
ThemeColor(name: '绿色', hex: '27AE60', cost: presetCost),
|
||||
ThemeColor(name: '紫色', hex: '9B59B6', cost: presetCost),
|
||||
ThemeColor(name: '橙色', hex: 'F39C12', cost: presetCost),
|
||||
ThemeColor(name: '青色', hex: '1ABC9C', cost: presetCost),
|
||||
ThemeColor(name: '粉色', hex: 'E91E63', cost: presetCost),
|
||||
ThemeColor(name: '深蓝', hex: '2C3E50', cost: presetCost),
|
||||
];
|
||||
|
||||
/// 某个十六进制颜色的价格;默认蓝 0,预置色 50,其它 150。
|
||||
static int costOf(String hex) {
|
||||
final h = hex.replaceAll('#', '').toUpperCase();
|
||||
if (h == defaultHex) return 0;
|
||||
for (final c in predefined) {
|
||||
if (c.hex.toUpperCase() == h) return presetCost;
|
||||
}
|
||||
return customCost;
|
||||
}
|
||||
}
|
||||
|
||||
/// 积分显示:整数不带小数位,小数保留到 0.01(去掉多余的 0)。
|
||||
String formatPoints(double v) {
|
||||
var s = v.toStringAsFixed(2);
|
||||
if (s.endsWith('.00')) return s.substring(0, s.length - 3);
|
||||
if (s.endsWith('0')) return s.substring(0, s.length - 1);
|
||||
return s;
|
||||
}
|
||||
|
||||
/// 人品值结果
|
||||
class FortuneResult {
|
||||
const FortuneResult(this.value, this.comment);
|
||||
|
||||
final int value;
|
||||
final String comment;
|
||||
|
||||
/// 0–100,越高越「人品爆发」
|
||||
static String commentFor(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 '非酋之王,明天再来';
|
||||
}
|
||||
}
|
||||
@@ -6,3 +6,4 @@ export 'pages/courseware.dart';
|
||||
export 'pages/download.dart';
|
||||
export 'pages/settings.dart';
|
||||
export 'pages/about.dart';
|
||||
export 'pages/user_page.dart';
|
||||
@@ -32,6 +32,11 @@ class _AboutPageViewState extends State<AboutPageView> {
|
||||
bool _loading = true;
|
||||
String? _error;
|
||||
|
||||
/// 重新下载启动器的进行状态与结果
|
||||
bool _redownloading = false;
|
||||
String? _redownloadMsg;
|
||||
bool? _redownloadOk;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
@@ -65,6 +70,34 @@ class _AboutPageViewState extends State<AboutPageView> {
|
||||
}
|
||||
}
|
||||
|
||||
/// 重新下载启动器包:后端下完会用清单里的 sha256 逐块校验,
|
||||
/// 校验不过会直接返回失败,不会留下半个坏包。
|
||||
Future<void> _redownloadLauncher() async {
|
||||
setState(() {
|
||||
_redownloading = true;
|
||||
_redownloadMsg = null;
|
||||
_redownloadOk = null;
|
||||
});
|
||||
try {
|
||||
final result = await widget.controller.api.redownloadLauncher();
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_redownloading = false;
|
||||
_redownloadOk = result.ok;
|
||||
_redownloadMsg = result.ok
|
||||
? T('about.redownloadOk', <Object?>[result.version])
|
||||
: (result.message.isEmpty ? T('about.redownloadFail') : result.message);
|
||||
});
|
||||
} catch (error) {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_redownloading = false;
|
||||
_redownloadOk = false;
|
||||
_redownloadMsg = error.toString();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ListView(
|
||||
@@ -175,18 +208,67 @@ class _AboutPageViewState extends State<AboutPageView> {
|
||||
],
|
||||
),
|
||||
const SizedBox(height: GcSpace.lg),
|
||||
OutlinedButton(
|
||||
onPressed: () async {
|
||||
final url = about?.repository;
|
||||
if (url == null || url.isEmpty) return;
|
||||
try {
|
||||
await widget.controller.api.openUrl(url);
|
||||
} catch (_) {
|
||||
// 忽略
|
||||
}
|
||||
},
|
||||
child: Text(T('about.openRepository')),
|
||||
Wrap(
|
||||
spacing: GcSpace.sm,
|
||||
runSpacing: GcSpace.sm,
|
||||
children: <Widget>[
|
||||
OutlinedButton(
|
||||
onPressed: () async {
|
||||
final url = about?.repository;
|
||||
if (url == null || url.isEmpty) return;
|
||||
try {
|
||||
await widget.controller.api.openUrl(url);
|
||||
} catch (_) {
|
||||
// 忽略
|
||||
}
|
||||
},
|
||||
child: Text(T('about.openRepository')),
|
||||
),
|
||||
OutlinedButton.icon(
|
||||
onPressed: _redownloading ? null : _redownloadLauncher,
|
||||
icon: _redownloading
|
||||
? const SizedBox(
|
||||
width: 14,
|
||||
height: 14,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
: const Icon(Icons.refresh_rounded, size: 16),
|
||||
label: Text(
|
||||
_redownloading
|
||||
? T('about.redownloading')
|
||||
: T('about.redownload'),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
if (_redownloadMsg != null) ...<Widget>[
|
||||
const SizedBox(height: GcSpace.md),
|
||||
Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
Icon(
|
||||
_redownloadOk == true
|
||||
? Icons.verified_rounded
|
||||
: Icons.error_outline_rounded,
|
||||
size: 16,
|
||||
color: _redownloadOk == true ? GcColors.ok : GcColors.danger,
|
||||
),
|
||||
const SizedBox(width: GcSpace.xs + 2),
|
||||
Expanded(
|
||||
child: Text(
|
||||
_redownloadMsg!,
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
height: 1.45,
|
||||
color: _redownloadOk == true
|
||||
? GcColors.muted
|
||||
: GcColors.danger,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
],
|
||||
);
|
||||
|
||||
|
||||
@@ -114,25 +114,41 @@ class _DownloadPageViewState extends State<DownloadPageView> {
|
||||
_error = null;
|
||||
});
|
||||
try {
|
||||
final sources = await widget.controller.api.sources();
|
||||
// 三个请求互不依赖,一起发出去:
|
||||
// 源列表(本地,几乎即时)、任务列表、模型索引(要打远端,最慢)
|
||||
// 以前是 sources → models → jobs 串行等三轮,进页面白等多一秒。
|
||||
final sourcesFuture = widget.controller.api.sources();
|
||||
final jobsFuture = widget.controller.api.jobs();
|
||||
final indexFuture = widget.controller.api.remoteModels(
|
||||
sourceId: _selectedSourceId,
|
||||
);
|
||||
|
||||
final sources = await sourcesFuture;
|
||||
final preferred = sources.where((s) => s.enabled).toList();
|
||||
final selected = _selectedSourceId ??
|
||||
(preferred.isNotEmpty
|
||||
? preferred.first.id
|
||||
: (sources.isNotEmpty ? sources.first.id : ''));
|
||||
|
||||
final index = selected.isEmpty
|
||||
? null
|
||||
: await widget.controller.api.remoteModels(sourceId: selected);
|
||||
// 源列表是本地的,先画出来:右侧模型列表还在等远端索引,左侧不必陪着转圈
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_sources = sources;
|
||||
_selectedSourceId = selected;
|
||||
});
|
||||
}
|
||||
|
||||
final index = await indexFuture;
|
||||
final jobs = await jobsFuture;
|
||||
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_sources = sources;
|
||||
_selectedSourceId = selected;
|
||||
_index = index;
|
||||
_jobs = jobs;
|
||||
_loading = false;
|
||||
});
|
||||
await _refreshJobs();
|
||||
} catch (error) {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
@@ -440,16 +456,97 @@ class _DownloadPageViewState extends State<DownloadPageView> {
|
||||
),
|
||||
),
|
||||
const SizedBox(width: GcSpace.lg),
|
||||
if (model.installed)
|
||||
OutlinedButton(
|
||||
onPressed: () => _download(model),
|
||||
child: Text(T('dl.reinstall')),
|
||||
)
|
||||
else
|
||||
FilledButton(
|
||||
onPressed: () => _download(model),
|
||||
child: Text(T('dl.download')),
|
||||
_downloadAction(model),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// 该模型是否有进行中的下载任务。
|
||||
JobInfo? _activeJobFor(String modelId) {
|
||||
for (final job in _jobs) {
|
||||
if (job.isActive && job.modelId == modelId) return job;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// 按钮位:空闲时是「下载 / 重新下载」,下载中就变成这一行的进度条。
|
||||
Widget _downloadAction(RemoteModelInfo model) {
|
||||
final job = _activeJobFor(model.id);
|
||||
if (job == null) {
|
||||
if (model.installed) {
|
||||
return OutlinedButton(
|
||||
onPressed: () => _download(model),
|
||||
child: Text(T('dl.reinstall')),
|
||||
);
|
||||
}
|
||||
return FilledButton(
|
||||
onPressed: () => _download(model),
|
||||
child: Text(T('dl.download')),
|
||||
);
|
||||
}
|
||||
|
||||
final value = job.progress.clamp(0.0, 1.0).toDouble();
|
||||
final percent = (value * 100).round();
|
||||
final detail = job.detailText.isNotEmpty ? job.detailText : job.statusText;
|
||||
|
||||
return SizedBox(
|
||||
width: 148,
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: <Widget>[
|
||||
Row(
|
||||
children: <Widget>[
|
||||
Text(
|
||||
'$percent%',
|
||||
style: TextStyle(
|
||||
fontSize: 12.5,
|
||||
height: 1.2,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: GcColors.accent,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: GcSpace.xs + 2),
|
||||
if (detail.isNotEmpty)
|
||||
Expanded(
|
||||
child: Text(
|
||||
detail,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
textAlign: TextAlign.right,
|
||||
style: TextStyle(
|
||||
fontSize: 11,
|
||||
height: 1.2,
|
||||
color: GcColors.faint,
|
||||
),
|
||||
),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () =>
|
||||
_jobAction(widget.controller.api.cancelJob, job.id),
|
||||
style: TextButton.styleFrom(
|
||||
minimumSize: const Size(0, 22),
|
||||
padding: const EdgeInsets.symmetric(horizontal: GcSpace.sm),
|
||||
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
|
||||
),
|
||||
child: Text(
|
||||
T('dl.cancel'),
|
||||
style: const TextStyle(fontSize: 11.5),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 3),
|
||||
ClipRRect(
|
||||
borderRadius: BorderRadius.circular(3),
|
||||
child: LinearProgressIndicator(
|
||||
// 还没拿到进度时走不确定态,避免显示 0% 让人以为卡住
|
||||
value: value > 0 ? value : null,
|
||||
minHeight: 6,
|
||||
backgroundColor: GcColors.surfaceAlt,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
@@ -89,6 +89,8 @@ class _HomePageViewState extends State<HomePageView> {
|
||||
Future<void> _launch(ModelInfo model) async {
|
||||
setState(() => _notice = null);
|
||||
try {
|
||||
// 模型窗口由后端用 Avalonia 打开(模型契约返回的是 Avalonia Control),
|
||||
// 前端只负责发这条指令并显示结果。
|
||||
final result = await widget.controller.api.launchModel(model.id);
|
||||
if (!mounted) return;
|
||||
setState(() => _notice = result.message);
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../api_client.dart';
|
||||
@@ -248,8 +246,6 @@ class _SettingsPageViewState extends State<SettingsPageView> {
|
||||
}
|
||||
|
||||
Widget _appearanceCard(SettingsInfo settings) {
|
||||
final current =
|
||||
GcPalette.parseHex(settings.accentColor) ?? GcPalette.defaultAccent;
|
||||
return GcCard(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
@@ -287,144 +283,11 @@ class _SettingsPageViewState extends State<SettingsPageView> {
|
||||
if (mounted) setState(() => _status = T('common.applied'));
|
||||
},
|
||||
),
|
||||
const SizedBox(height: GcSpace.xl),
|
||||
GcHint(T('set.accent.desc')),
|
||||
const SizedBox(height: GcSpace.md + 2),
|
||||
Wrap(
|
||||
spacing: GcSpace.sm + 2,
|
||||
runSpacing: GcSpace.sm + 2,
|
||||
children: <Widget>[
|
||||
for (final color in GcPalette.presets)
|
||||
_accentSwatch(color, current),
|
||||
_customAccentChip(),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: GcSpace.md),
|
||||
Text(
|
||||
'${T('set.accent')}: ${GcPalette.toHex(current)}',
|
||||
style: TextStyle(
|
||||
fontSize: 11.5,
|
||||
height: 1.4,
|
||||
color: GcColors.faint,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _accentSwatch(Color color, Color current) {
|
||||
final selected = color.value == current.value;
|
||||
return Tooltip(
|
||||
message: GcPalette.toHex(color),
|
||||
child: GestureDetector(
|
||||
onTap: () => _applyAccent(GcPalette.toHex(color)),
|
||||
child: Container(
|
||||
width: 34,
|
||||
height: 34,
|
||||
decoration: BoxDecoration(
|
||||
color: color,
|
||||
borderRadius: BorderRadius.circular(GcRadius.control),
|
||||
border: Border.all(
|
||||
color: selected ? GcColors.ink : Colors.transparent,
|
||||
width: 2,
|
||||
),
|
||||
),
|
||||
child: selected
|
||||
? Icon(
|
||||
Icons.check_rounded,
|
||||
size: 18,
|
||||
color: color.computeLuminance() > 0.42
|
||||
? const Color(0xFF0A1226)
|
||||
: Colors.white,
|
||||
)
|
||||
: null,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _customAccentChip() {
|
||||
return MouseRegion(
|
||||
cursor: SystemMouseCursors.click,
|
||||
child: GestureDetector(
|
||||
onTap: _pickCustomAccent,
|
||||
child: Container(
|
||||
height: 34,
|
||||
padding: const EdgeInsets.symmetric(horizontal: GcSpace.md),
|
||||
decoration: BoxDecoration(
|
||||
color: GcColors.surfaceAlt,
|
||||
borderRadius: BorderRadius.circular(GcRadius.control),
|
||||
border: Border.all(color: GcColors.line),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: <Widget>[
|
||||
Icon(Icons.colorize_rounded, size: 16, color: GcColors.faint),
|
||||
const SizedBox(width: GcSpace.xs + 2),
|
||||
Text(
|
||||
T('set.accent.custom'),
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
height: 1.3,
|
||||
color: GcColors.muted,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _pickCustomAccent() async {
|
||||
final controller = TextEditingController(
|
||||
text: GcPalette.toHex(GcPalette.accent.value),
|
||||
);
|
||||
final hex = await showDialog<String>(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog(
|
||||
backgroundColor: GcColors.surface,
|
||||
title: Text(T('set.accent.custom')),
|
||||
content: TextField(
|
||||
controller: controller,
|
||||
autofocus: true,
|
||||
style: Theme.of(context).textTheme.bodyLarge!.copyWith(fontSize: 13),
|
||||
decoration: InputDecoration(
|
||||
hintText: '#8FB6FF',
|
||||
helperText: T('set.accent.hexHint'),
|
||||
),
|
||||
onSubmitted: (value) => Navigator.of(context).pop(value),
|
||||
),
|
||||
actions: <Widget>[
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
child: Text(T('common.cancel')),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: () => Navigator.of(context).pop(controller.text),
|
||||
child: Text(T('common.confirm')),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
controller.dispose();
|
||||
if (hex != null) await _applyAccent(hex);
|
||||
}
|
||||
|
||||
Future<void> _applyAccent(String hex) async {
|
||||
final parsed = GcPalette.parseHex(hex);
|
||||
if (parsed == null) {
|
||||
if (mounted) setState(() => _status = T('set.accent.invalid'));
|
||||
return;
|
||||
}
|
||||
final normalized = GcPalette.toHex(parsed);
|
||||
GcPalette.apply(normalized); // 立即预览
|
||||
await widget.controller
|
||||
.saveSettings(SettingsPatch(accentColor: normalized));
|
||||
if (mounted) setState(() => _status = T('common.applied'));
|
||||
}
|
||||
|
||||
Widget _memoryCard(SettingsInfo settings) {
|
||||
return GcCard(
|
||||
child: Column(
|
||||
|
||||
@@ -0,0 +1,903 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../controller.dart';
|
||||
import '../api_client.dart';
|
||||
import '../i18n.dart';
|
||||
import '../theme.dart';
|
||||
import '../models/user.dart';
|
||||
|
||||
/// 用户页面:账号(注册/登录/人机验证)、签到、人品值、二选一、主题色
|
||||
class UserPage extends StatefulWidget {
|
||||
const UserPage({super.key, required this.controller});
|
||||
|
||||
final ShellController controller;
|
||||
|
||||
@override
|
||||
State<UserPage> createState() => _UserPageState();
|
||||
}
|
||||
|
||||
class _UserPageState extends State<UserPage> {
|
||||
UserRecord? _user;
|
||||
bool _loading = true;
|
||||
String? _error;
|
||||
|
||||
// 登录 / 注册
|
||||
final _usernameCtrl = TextEditingController();
|
||||
final _passwordCtrl = TextEditingController();
|
||||
final _captchaCtrl = TextEditingController();
|
||||
bool _isLogin = true;
|
||||
CaptchaInfo? _captcha;
|
||||
bool _captchaLoading = false;
|
||||
bool _submitting = false;
|
||||
|
||||
// 人品值
|
||||
FortuneResult? _fortune;
|
||||
bool _rolling = false;
|
||||
|
||||
// 二选一
|
||||
final _option1Ctrl = TextEditingController();
|
||||
final _option2Ctrl = TextEditingController();
|
||||
String? _randomResult;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_loadUser();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_usernameCtrl.dispose();
|
||||
_passwordCtrl.dispose();
|
||||
_captchaCtrl.dispose();
|
||||
_option1Ctrl.dispose();
|
||||
_option2Ctrl.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 账号
|
||||
|
||||
Future<void> _loadUser() async {
|
||||
setState(() {
|
||||
_loading = true;
|
||||
_error = null;
|
||||
});
|
||||
try {
|
||||
final resp = await widget.controller.api.me();
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_user = resp == null ? null : UserRecord.fromJson(resp);
|
||||
_loading = false;
|
||||
});
|
||||
_applyTheme();
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_loading = false;
|
||||
_error = e.toString();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// 用户买的主题色覆盖全局强调色
|
||||
void _applyTheme() {
|
||||
final hex = _user?.themeColor;
|
||||
if (hex == null || hex.isEmpty) return;
|
||||
GcPalette.apply('#$hex');
|
||||
}
|
||||
|
||||
Future<void> _refreshCaptcha() async {
|
||||
setState(() => _captchaLoading = true);
|
||||
try {
|
||||
final c = await widget.controller.api.captcha();
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_captcha = c;
|
||||
_captchaLoading = false;
|
||||
_captchaCtrl.clear();
|
||||
});
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
setState(() => _captchaLoading = false);
|
||||
_toast(e.toString());
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _submit() async {
|
||||
final username = _usernameCtrl.text.trim();
|
||||
final password = _passwordCtrl.text;
|
||||
|
||||
if (username.isEmpty || password.isEmpty) {
|
||||
_toast(T('user.fillAll'));
|
||||
return;
|
||||
}
|
||||
|
||||
if (!_isLogin) {
|
||||
if (_captcha == null) {
|
||||
_toast(T('user.captchaMissing'));
|
||||
return;
|
||||
}
|
||||
if (_captchaCtrl.text.trim().isEmpty) {
|
||||
_toast(T('user.fillCaptcha'));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
setState(() => _submitting = true);
|
||||
try {
|
||||
if (_isLogin) {
|
||||
await widget.controller.api.login(username, password);
|
||||
} else {
|
||||
await widget.controller.api.register(
|
||||
username,
|
||||
password,
|
||||
captchaId: _captcha!.id,
|
||||
captchaAnswer: _captchaCtrl.text.trim(),
|
||||
);
|
||||
await widget.controller.api.login(username, password);
|
||||
}
|
||||
|
||||
final resp = await widget.controller.api.me();
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_user = resp == null ? null : UserRecord.fromJson(resp);
|
||||
_usernameCtrl.clear();
|
||||
_passwordCtrl.clear();
|
||||
_captchaCtrl.clear();
|
||||
_captcha = null;
|
||||
_submitting = false;
|
||||
});
|
||||
_applyTheme();
|
||||
_toast(_isLogin ? T('user.loginSuccess') : T('user.registerSuccess'));
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
setState(() => _submitting = false);
|
||||
// 注册失败时换一题:验证码是一次性的
|
||||
if (!_isLogin) _refreshCaptcha();
|
||||
_toast(e.toString());
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _logout() async {
|
||||
await widget.controller.api.logout();
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_user = null;
|
||||
_fortune = null;
|
||||
});
|
||||
GcPalette.accent.value = GcPalette.defaultAccent;
|
||||
_toast(T('user.logoutDone'));
|
||||
}
|
||||
|
||||
Future<void> _signin() async {
|
||||
try {
|
||||
final resp = await widget.controller.api.signin();
|
||||
if (!mounted) return;
|
||||
|
||||
if (resp['message'] == '今日已签到') {
|
||||
_toast(T('user.alreadySigned'));
|
||||
return;
|
||||
}
|
||||
|
||||
final payload = resp['user'] as Map<String, dynamic>?;
|
||||
final reward = (resp['reward'] as num?)?.toInt() ?? 0;
|
||||
setState(() {
|
||||
if (payload != null) _user = UserRecord.fromJson(payload);
|
||||
});
|
||||
_toast('${T('user.signinSuccess')} +$reward ${T('user.points')}');
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
_toast(e.toString());
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 人品值
|
||||
|
||||
Future<void> _rollFortune() async {
|
||||
if (_user == null) {
|
||||
_toast(T('user.loginFirst'));
|
||||
return;
|
||||
}
|
||||
setState(() => _rolling = true);
|
||||
try {
|
||||
// 服务端算随机数和价格:当天第一次免费,之后按当日次数阶梯计费
|
||||
final resp = await widget.controller.api.rollFortune();
|
||||
if (!mounted) return;
|
||||
final value = (resp['value'] as num?)?.toInt() ?? 0;
|
||||
final cost = (resp['cost'] as num?)?.toDouble() ?? 0;
|
||||
setState(() {
|
||||
_fortune = FortuneResult(value, resp['comment'] as String? ?? FortuneResult.commentFor(value));
|
||||
final payload = resp['user'] as Map<String, dynamic>?;
|
||||
if (payload != null) _user = UserRecord.fromJson(payload);
|
||||
_rolling = false;
|
||||
});
|
||||
_toast(cost > 0 ? '本次消耗 ${formatPoints(cost)} 积分' : '今日首次免费');
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
setState(() => _rolling = false);
|
||||
_toast(e.toString());
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 二选一
|
||||
|
||||
Future<void> _pickRandom() async {
|
||||
final a = _option1Ctrl.text.trim();
|
||||
final b = _option2Ctrl.text.trim();
|
||||
if (a.isEmpty || b.isEmpty) {
|
||||
_toast(T('user.fillOptions'));
|
||||
return;
|
||||
}
|
||||
if (_user == null) {
|
||||
_toast(T('user.loginFirst'));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
// 服务端随机 + 计费:当天第一次免费,之后每次 0.5 积分
|
||||
final resp = await widget.controller.api.pickOne(a, b);
|
||||
if (!mounted) return;
|
||||
final cost = (resp['cost'] as num?)?.toDouble() ?? 0;
|
||||
setState(() {
|
||||
_randomResult = resp['choice'] as String?;
|
||||
final payload = resp['user'] as Map<String, dynamic>?;
|
||||
if (payload != null) _user = UserRecord.fromJson(payload);
|
||||
});
|
||||
_toast(cost > 0 ? '本次消耗 ${formatPoints(cost)} 积分' : '今日首次免费');
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
_toast(e.toString());
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 主题色
|
||||
|
||||
Future<void> _changeTheme(String hex) async {
|
||||
if (_user == null) {
|
||||
_toast(T('user.loginFirst'));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
final resp = await widget.controller.api.changeTheme(hex);
|
||||
if (!mounted) return;
|
||||
|
||||
final payload = resp['user'] as Map<String, dynamic>?;
|
||||
setState(() {
|
||||
if (payload != null) _user = UserRecord.fromJson(payload);
|
||||
});
|
||||
_applyTheme();
|
||||
|
||||
final refunded = (resp['refunded'] as num?)?.toInt() ?? 0;
|
||||
_toast(refunded > 0
|
||||
? '${T('user.themeUpdated')},${T('user.refunded')} +$refunded'
|
||||
: T('user.themeUpdated'));
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
_toast(e.toString());
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _pickCustomColor() async {
|
||||
if (_user == null) {
|
||||
_toast(T('user.loginFirst'));
|
||||
return;
|
||||
}
|
||||
|
||||
final controller = TextEditingController(text: '#7C6CFF');
|
||||
final hex = await showDialog<String>(
|
||||
context: context,
|
||||
builder: (ctx) => StatefulBuilder(
|
||||
builder: (ctx, setLocal) {
|
||||
final raw = controller.text.replaceAll('#', '').trim();
|
||||
final valid = raw.length == 6 && int.tryParse(raw, radix: 16) != null;
|
||||
final preview = valid
|
||||
? Color(0xFF000000 | int.parse(raw, radix: 16))
|
||||
: GcColors.surface;
|
||||
|
||||
return AlertDialog(
|
||||
title: Text(T('user.customColor')),
|
||||
content: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
Text(
|
||||
T('user.customColorCost', <Object?>['${ThemeColor.customCost}']),
|
||||
style: TextStyle(color: GcColors.muted, fontSize: 13),
|
||||
),
|
||||
const SizedBox(height: GcSpace.md),
|
||||
TextField(
|
||||
controller: controller,
|
||||
autofocus: true,
|
||||
decoration: InputDecoration(
|
||||
labelText: '#RRGGBB',
|
||||
border: const OutlineInputBorder(),
|
||||
errorText: valid || raw.isEmpty ? null : T('user.hexInvalid'),
|
||||
),
|
||||
onChanged: (_) => setLocal(() {}),
|
||||
),
|
||||
const SizedBox(height: GcSpace.md),
|
||||
Row(
|
||||
children: <Widget>[
|
||||
Container(
|
||||
width: 44,
|
||||
height: 44,
|
||||
decoration: BoxDecoration(
|
||||
color: preview,
|
||||
borderRadius: BorderRadius.circular(GcRadius.control),
|
||||
border: Border.all(color: GcColors.line),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: GcSpace.md),
|
||||
Expanded(
|
||||
child: Text(
|
||||
valid ? '#${raw.toUpperCase()}' : '—',
|
||||
style: TextStyle(color: GcColors.muted),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
actions: <Widget>[
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(ctx).pop(),
|
||||
child: Text(T('common.cancel')),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed:
|
||||
valid ? () => Navigator.of(ctx).pop(raw.toUpperCase()) : null,
|
||||
child: Text(T('user.confirmBuy')),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
controller.dispose();
|
||||
if (hex != null) await _changeTheme(hex);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 工具
|
||||
|
||||
void _toast(String message) {
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(context)
|
||||
..hideCurrentSnackBar()
|
||||
..showSnackBar(SnackBar(content: Text(message)));
|
||||
}
|
||||
|
||||
String _formatRefund(int seconds) {
|
||||
if (seconds >= 60) return '${seconds ~/ 60} ${T('user.minutes')}';
|
||||
return '$seconds ${T('user.seconds')}';
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- UI
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (_loading) {
|
||||
return Scaffold(
|
||||
backgroundColor: GcColors.appBg,
|
||||
body: const Center(child: CircularProgressIndicator()),
|
||||
);
|
||||
}
|
||||
|
||||
return Scaffold(
|
||||
backgroundColor: GcColors.appBg,
|
||||
body: SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(GcSpace.xxl),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: <Widget>[
|
||||
_header(),
|
||||
const SizedBox(height: GcSpace.lg),
|
||||
if (_user == null) ...[
|
||||
_authCard(),
|
||||
const SizedBox(height: GcSpace.lg),
|
||||
],
|
||||
_fortuneCard(),
|
||||
const SizedBox(height: GcSpace.lg),
|
||||
_pickCard(),
|
||||
const SizedBox(height: GcSpace.lg),
|
||||
_themeCard(),
|
||||
if (_error != null) ...[
|
||||
const SizedBox(height: GcSpace.md),
|
||||
Text(_error!, style: TextStyle(color: GcColors.danger)),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _header() {
|
||||
final user = _user;
|
||||
return GcCard(
|
||||
padding: const EdgeInsets.all(GcSpace.lg),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
Row(
|
||||
children: <Widget>[
|
||||
CircleAvatar(
|
||||
radius: 22,
|
||||
backgroundColor: GcColors.accentSoft,
|
||||
child: Icon(Icons.person_rounded, color: GcColors.accent),
|
||||
),
|
||||
const SizedBox(width: GcSpace.md),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
Text(
|
||||
user?.username ?? T('user.notLoggedIn'),
|
||||
style: const TextStyle(
|
||||
fontSize: 18, fontWeight: FontWeight.w700),
|
||||
),
|
||||
const SizedBox(height: 2),
|
||||
Text(
|
||||
user == null
|
||||
? T('user.loginHint')
|
||||
: '${T('user.points')} ${formatPoints(user.points)} · '
|
||||
'${T('user.days')} ${user.consecutiveDays}',
|
||||
style: TextStyle(color: GcColors.muted, fontSize: 13),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (user != null)
|
||||
OutlinedButton(
|
||||
onPressed: _logout,
|
||||
child: Text(T('user.logout')),
|
||||
),
|
||||
],
|
||||
),
|
||||
if (user != null) ...[
|
||||
const SizedBox(height: GcSpace.lg),
|
||||
Row(
|
||||
children: <Widget>[
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
Text(
|
||||
T('user.cycleDay',
|
||||
<Object?>['${user.cycleDay}', '${user.cycleDays}']),
|
||||
style: TextStyle(color: GcColors.muted, fontSize: 13),
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
ClipRRect(
|
||||
borderRadius: BorderRadius.circular(GcRadius.pill),
|
||||
child: LinearProgressIndicator(
|
||||
value: user.cycleDay / user.cycleDays,
|
||||
minHeight: 6,
|
||||
backgroundColor: GcColors.surfaceAlt,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
user.todaySigned
|
||||
? T('user.signedToday')
|
||||
: T('user.nextReward', <Object?>['${user.nextReward}']),
|
||||
style: TextStyle(color: GcColors.faint, fontSize: 12),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: GcSpace.lg),
|
||||
FilledButton(
|
||||
onPressed: user.todaySigned ? null : _signin,
|
||||
child: Text(user.todaySigned
|
||||
? T('user.signedTodayShort')
|
||||
: T('user.signin')),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _authCard() {
|
||||
return GcCard(
|
||||
padding: const EdgeInsets.all(GcSpace.lg),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
Row(
|
||||
children: <Widget>[
|
||||
Text(
|
||||
_isLogin ? T('user.login') : T('user.register'),
|
||||
style:
|
||||
const TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
|
||||
),
|
||||
const Spacer(),
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
setState(() {
|
||||
_isLogin = !_isLogin;
|
||||
_captcha = null;
|
||||
_captchaCtrl.clear();
|
||||
});
|
||||
if (!_isLogin) _refreshCaptcha();
|
||||
},
|
||||
child: Text(_isLogin
|
||||
? T('user.switchToRegister')
|
||||
: T('user.switchToLogin')),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: GcSpace.md),
|
||||
TextField(
|
||||
controller: _usernameCtrl,
|
||||
decoration: InputDecoration(
|
||||
labelText: T('user.username'),
|
||||
helperText: _isLogin ? null : T('user.usernameRule'),
|
||||
border: const OutlineInputBorder(),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: GcSpace.md),
|
||||
TextField(
|
||||
controller: _passwordCtrl,
|
||||
obscureText: true,
|
||||
decoration: InputDecoration(
|
||||
labelText: T('user.password'),
|
||||
border: const OutlineInputBorder(),
|
||||
),
|
||||
onSubmitted: (_) => _submit(),
|
||||
),
|
||||
|
||||
// 注册才需要人机验证
|
||||
if (!_isLogin) ...[
|
||||
const SizedBox(height: GcSpace.lg),
|
||||
Row(
|
||||
children: <Widget>[
|
||||
Expanded(
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: GcSpace.md, vertical: GcSpace.md),
|
||||
decoration: BoxDecoration(
|
||||
color: GcColors.surfaceAlt,
|
||||
borderRadius: BorderRadius.circular(GcRadius.control),
|
||||
border: Border.all(color: GcColors.line),
|
||||
),
|
||||
child: Row(
|
||||
children: <Widget>[
|
||||
Icon(Icons.shield_outlined,
|
||||
size: 18, color: GcColors.muted),
|
||||
const SizedBox(width: GcSpace.sm),
|
||||
Text(
|
||||
_captchaLoading
|
||||
? T('common.loading')
|
||||
: (_captcha?.question ?? T('user.captcha')),
|
||||
style: const TextStyle(
|
||||
fontSize: 15,
|
||||
fontWeight: FontWeight.w600,
|
||||
letterSpacing: 1),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
tooltip: T('user.refreshCaptcha'),
|
||||
onPressed: _captchaLoading ? null : _refreshCaptcha,
|
||||
icon: const Icon(Icons.refresh_rounded),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: GcSpace.md),
|
||||
TextField(
|
||||
controller: _captchaCtrl,
|
||||
keyboardType: TextInputType.number,
|
||||
decoration: InputDecoration(
|
||||
labelText: T('user.captchaAnswer'),
|
||||
border: const OutlineInputBorder(),
|
||||
),
|
||||
onSubmitted: (_) => _submit(),
|
||||
),
|
||||
],
|
||||
|
||||
const SizedBox(height: GcSpace.lg),
|
||||
SizedBox(
|
||||
height: GcSize.control,
|
||||
child: FilledButton(
|
||||
onPressed: _submitting ? null : _submit,
|
||||
child: _submitting
|
||||
? const SizedBox(
|
||||
width: 18,
|
||||
height: 18,
|
||||
child: CircularProgressIndicator(strokeWidth: 2))
|
||||
: Text(_isLogin ? T('user.login') : T('user.register')),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: GcSpace.sm),
|
||||
Text(
|
||||
T('user.noRecharge'),
|
||||
style: TextStyle(color: GcColors.faint, fontSize: 12),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _fortuneCard() {
|
||||
return GcCard(
|
||||
padding: const EdgeInsets.all(GcSpace.lg),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
Text(T('user.fortune'),
|
||||
style:
|
||||
const TextStyle(fontSize: 16, fontWeight: FontWeight.w600)),
|
||||
const SizedBox(height: 4),
|
||||
Text(T('user.fortuneDesc'),
|
||||
style: TextStyle(color: GcColors.muted, fontSize: 13)),
|
||||
const SizedBox(height: GcSpace.lg),
|
||||
Row(
|
||||
children: <Widget>[
|
||||
Container(
|
||||
width: 96,
|
||||
height: 96,
|
||||
alignment: Alignment.center,
|
||||
decoration: BoxDecoration(
|
||||
color: GcColors.accentSoft,
|
||||
shape: BoxShape.circle,
|
||||
border: Border.all(color: GcColors.accent, width: 2),
|
||||
),
|
||||
child: Text(
|
||||
_rolling ? '…' : (_fortune?.value.toString() ?? '?'),
|
||||
style: const TextStyle(
|
||||
fontSize: 34, fontWeight: FontWeight.w700, height: 1.0),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: GcSpace.lg),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
Text(
|
||||
_fortune?.comment ?? T('user.fortuneIdle'),
|
||||
style: const TextStyle(
|
||||
fontSize: 14, fontWeight: FontWeight.w600),
|
||||
),
|
||||
const SizedBox(height: GcSpace.md),
|
||||
FilledButton(
|
||||
onPressed: _rolling ? null : _rollFortune,
|
||||
child: Text(_fortune == null
|
||||
? T('user.fortuneRoll')
|
||||
: T('user.fortuneAgain')),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _pickCard() {
|
||||
return GcCard(
|
||||
padding: const EdgeInsets.all(GcSpace.lg),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
Text(T('user.pick'),
|
||||
style:
|
||||
const TextStyle(fontSize: 16, fontWeight: FontWeight.w600)),
|
||||
const SizedBox(height: 4),
|
||||
Text(T('user.pickDesc'),
|
||||
style: TextStyle(color: GcColors.muted, fontSize: 13)),
|
||||
const SizedBox(height: GcSpace.md),
|
||||
Row(
|
||||
children: <Widget>[
|
||||
Expanded(
|
||||
child: TextField(
|
||||
controller: _option1Ctrl,
|
||||
decoration: InputDecoration(
|
||||
labelText: T('user.option1'),
|
||||
border: const OutlineInputBorder(),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: GcSpace.md),
|
||||
Expanded(
|
||||
child: TextField(
|
||||
controller: _option2Ctrl,
|
||||
decoration: InputDecoration(
|
||||
labelText: T('user.option2'),
|
||||
border: const OutlineInputBorder(),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: GcSpace.md),
|
||||
Row(
|
||||
children: <Widget>[
|
||||
FilledButton(
|
||||
onPressed: _pickRandom,
|
||||
child: Text(T('user.pickRandom')),
|
||||
),
|
||||
if (_randomResult != null) ...[
|
||||
const SizedBox(width: GcSpace.lg),
|
||||
Expanded(
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: GcSpace.md, vertical: GcSpace.sm),
|
||||
decoration: BoxDecoration(
|
||||
color: GcColors.accentSoft,
|
||||
borderRadius: BorderRadius.circular(GcRadius.control),
|
||||
),
|
||||
child: Text(
|
||||
'${T('user.pickResult')} ${_randomResult!}',
|
||||
style: const TextStyle(
|
||||
fontSize: 15, fontWeight: FontWeight.w600),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _themeCard() {
|
||||
final user = _user;
|
||||
final current = user?.themeColor?.toUpperCase();
|
||||
final canRefund = (user?.refundSeconds ?? 0) > 0;
|
||||
|
||||
return GcCard(
|
||||
padding: const EdgeInsets.all(GcSpace.lg),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
Text(T('user.themeColor'),
|
||||
style:
|
||||
const TextStyle(fontSize: 16, fontWeight: FontWeight.w600)),
|
||||
const SizedBox(height: 4),
|
||||
Text(T('user.themeDesc'),
|
||||
style: TextStyle(color: GcColors.muted, fontSize: 13)),
|
||||
if (canRefund) ...[
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
T('user.refundHint', <Object?>[_formatRefund(user!.refundSeconds)]),
|
||||
style: TextStyle(color: GcColors.ok, fontSize: 12),
|
||||
),
|
||||
],
|
||||
const SizedBox(height: GcSpace.lg),
|
||||
Wrap(
|
||||
spacing: GcSpace.md,
|
||||
runSpacing: GcSpace.md,
|
||||
children: <Widget>[
|
||||
...ThemeColor.predefined.map((c) => _swatch(
|
||||
name: c.name,
|
||||
hex: c.hex,
|
||||
cost: c.cost,
|
||||
selected: current == c.hex.toUpperCase(),
|
||||
)),
|
||||
_customSwatch(
|
||||
selected: current != null &&
|
||||
ThemeColor.costOf(current) == ThemeColor.customCost,
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _swatch({
|
||||
required String name,
|
||||
required String hex,
|
||||
required int cost,
|
||||
required bool selected,
|
||||
}) {
|
||||
final points = _user?.points ?? 0;
|
||||
final affordable = cost == 0 || points >= cost;
|
||||
|
||||
return InkWell(
|
||||
onTap: () => _changeTheme(hex),
|
||||
borderRadius: BorderRadius.circular(GcRadius.control),
|
||||
child: Column(
|
||||
children: <Widget>[
|
||||
Stack(
|
||||
children: <Widget>[
|
||||
Container(
|
||||
width: 56,
|
||||
height: 56,
|
||||
decoration: BoxDecoration(
|
||||
color: Color(0xFF000000 | int.parse(hex, radix: 16)),
|
||||
borderRadius: BorderRadius.circular(GcRadius.control),
|
||||
border: Border.all(
|
||||
color: selected ? GcColors.accent : GcColors.line,
|
||||
width: selected ? 2.5 : 1,
|
||||
),
|
||||
),
|
||||
),
|
||||
if (selected)
|
||||
const Positioned(
|
||||
right: 3,
|
||||
bottom: 3,
|
||||
child: Icon(Icons.check_circle_rounded,
|
||||
size: 16, color: Colors.white),
|
||||
),
|
||||
if (!affordable)
|
||||
Positioned.fill(
|
||||
child: Container(
|
||||
decoration: BoxDecoration(
|
||||
// ignore: deprecated_member_use
|
||||
color: Colors.black.withOpacity(0.45),
|
||||
borderRadius: BorderRadius.circular(GcRadius.control),
|
||||
),
|
||||
child: const Icon(Icons.lock_outline,
|
||||
size: 18, color: Colors.white),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(name, style: TextStyle(fontSize: 11, color: GcColors.muted)),
|
||||
Text(
|
||||
cost == 0 ? T('user.free') : '$cost',
|
||||
style: TextStyle(
|
||||
fontSize: 11,
|
||||
color: affordable ? GcColors.faint : GcColors.danger,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _customSwatch({required bool selected}) {
|
||||
final canAfford = (_user?.points ?? 0) >= ThemeColor.customCost;
|
||||
return InkWell(
|
||||
onTap: _pickCustomColor,
|
||||
borderRadius: BorderRadius.circular(GcRadius.control),
|
||||
child: Column(
|
||||
children: <Widget>[
|
||||
Container(
|
||||
width: 56,
|
||||
height: 56,
|
||||
decoration: BoxDecoration(
|
||||
gradient: const SweepGradient(
|
||||
colors: <Color>[
|
||||
Color(0xFFFF7A7A),
|
||||
Color(0xFFFFC46B),
|
||||
Color(0xFF6BE3A2),
|
||||
Color(0xFF4FD1C5),
|
||||
Color(0xFF7C6CFF),
|
||||
Color(0xFFFF8FB1),
|
||||
Color(0xFFFF7A7A),
|
||||
],
|
||||
),
|
||||
borderRadius: BorderRadius.circular(GcRadius.control),
|
||||
border: Border.all(
|
||||
color: selected ? GcColors.accent : GcColors.line,
|
||||
width: selected ? 2.5 : 1,
|
||||
),
|
||||
),
|
||||
child: Icon(Icons.colorize_rounded,
|
||||
size: 20, color: canAfford ? Colors.white : Colors.white70),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(T('user.custom'),
|
||||
style: TextStyle(fontSize: 11, color: GcColors.muted)),
|
||||
Text(
|
||||
'${ThemeColor.customCost}',
|
||||
style: TextStyle(
|
||||
fontSize: 11,
|
||||
color: canAfford ? GcColors.faint : GcColors.danger,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import 'controller.dart';
|
||||
import 'i18n.dart';
|
||||
import 'pages.dart';
|
||||
import 'theme.dart';
|
||||
import 'window_chrome.dart';
|
||||
|
||||
/// 侧边栏导航项。
|
||||
class _NavItem {
|
||||
@@ -19,6 +20,7 @@ const List<_NavItem> _navItems = <_NavItem>[
|
||||
_NavItem(Icons.download_rounded, 'nav.download'),
|
||||
_NavItem(Icons.tune_rounded, 'nav.settings'),
|
||||
_NavItem(Icons.info_outline_rounded, 'nav.about'),
|
||||
_NavItem(Icons.person_rounded, 'nav.user'),
|
||||
];
|
||||
|
||||
/// 桌面端滚动行为:去掉移动端的拉伸回弹和边缘光晕,滚轮更跟手。
|
||||
@@ -69,16 +71,24 @@ class _ShellPageState extends State<ShellPage> {
|
||||
final controller = widget.controller;
|
||||
return Scaffold(
|
||||
backgroundColor: GcColors.appBg,
|
||||
body: Row(
|
||||
body: Column(
|
||||
children: <Widget>[
|
||||
_Sidebar(controller: controller),
|
||||
Container(width: 1, color: GcColors.line),
|
||||
// 自绘标题栏(macOS):系统标题栏已隐藏,最小化/最大化/关闭在这里画
|
||||
const GcTitleBar(),
|
||||
Expanded(
|
||||
child: Column(
|
||||
child: Row(
|
||||
children: <Widget>[
|
||||
Expanded(child: _content(controller)),
|
||||
if (controller.updateBarVisible)
|
||||
_UpdateBar(controller: controller),
|
||||
_Sidebar(controller: controller),
|
||||
Container(width: 1, color: GcColors.line),
|
||||
Expanded(
|
||||
child: Column(
|
||||
children: <Widget>[
|
||||
Expanded(child: _content(controller)),
|
||||
if (controller.updateBarVisible)
|
||||
_UpdateBar(controller: controller),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
@@ -136,6 +146,8 @@ class _ShellPageState extends State<ShellPage> {
|
||||
return SettingsPageView(controller: controller);
|
||||
case 4:
|
||||
return AboutPageView(controller: controller);
|
||||
case 5:
|
||||
return UserPage(controller: controller);
|
||||
default:
|
||||
return HomePageView(controller: controller);
|
||||
}
|
||||
@@ -445,7 +457,8 @@ class _BackendDown extends StatelessWidget {
|
||||
const SizedBox(height: GcSpace.md),
|
||||
GcHint(controller.loadError ?? ''),
|
||||
const SizedBox(height: GcSpace.xs),
|
||||
GcHint('${T('set.backend')}: ${controller.api.baseUrl}'),
|
||||
GcHint('${T('set.backend')}: ${controller.api.baseUrl}'
|
||||
' · ${controller.api.hasSessionToken ? '令牌已就绪' : '缺少会话令牌'}'),
|
||||
const SizedBox(height: GcSpace.lg),
|
||||
FilledButton(
|
||||
onPressed: controller.bootstrap,
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import 'theme.dart';
|
||||
|
||||
/// 自绘窗口按钮的通道(macOS 侧在 macos/Runner/MainFlutterWindow.swift 实现)。
|
||||
///
|
||||
/// 系统标题栏已去掉(titleVisibility = .hidden + fullSizeContentView),
|
||||
/// 最小化 / 最大化 / 关闭 全部由 Flutter 画,外观跟界面统一。
|
||||
class GcWindow {
|
||||
GcWindow._();
|
||||
|
||||
static const MethodChannel _channel = MethodChannel('gc/window');
|
||||
|
||||
/// 只有 macOS 走了自绘标题栏;其它平台保留系统标题栏,不显示自绘按钮。
|
||||
static bool get supported => !kIsWeb && Platform.isMacOS;
|
||||
|
||||
static Future<void> minimize() => _invoke('minimize');
|
||||
static Future<void> close() => _invoke('close');
|
||||
static Future<void> toggleMaximize() => _invoke('toggleMaximize');
|
||||
|
||||
/// 开始拖拽窗口。用原生 performDrag,比在 Flutter 里模拟位置更跟手。
|
||||
static Future<void> beginDrag() => _invoke('beginDrag');
|
||||
|
||||
static Future<bool> isMaximized() async {
|
||||
if (!supported) return false;
|
||||
try {
|
||||
return await _channel.invokeMethod<bool>('isMaximized') ?? false;
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
static Future<void> _invoke(String method) async {
|
||||
if (!supported) return;
|
||||
try {
|
||||
await _channel.invokeMethod<void>(method);
|
||||
} catch (_) {
|
||||
// 通道不可用(例如截图测试环境)时静默忽略
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 顶部标题栏:左侧应用名 + 右侧自绘的最小化 / 最大化 / 关闭。
|
||||
///
|
||||
/// 只在 macOS 显示;其它平台系统标题栏还在,这里返回零高度占位。
|
||||
class GcTitleBar extends StatelessWidget {
|
||||
const GcTitleBar({super.key, this.title = 'Morris GC'});
|
||||
|
||||
final String title;
|
||||
|
||||
static const double height = 38;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (!GcWindow.supported) return const SizedBox.shrink();
|
||||
|
||||
return GestureDetector(
|
||||
behavior: HitTestBehavior.opaque,
|
||||
onPanStart: (_) => GcWindow.beginDrag(),
|
||||
child: Container(
|
||||
height: height,
|
||||
// 与主题底色保持一致:浅色主题是纯白,深色主题是深色面板色。
|
||||
// 不叠强调色 —— 标题栏属于窗口底色,染色会显得和内容区不是一套。
|
||||
decoration: BoxDecoration(
|
||||
color: GcColors.sideBg,
|
||||
border: Border(bottom: BorderSide(color: GcColors.line)),
|
||||
),
|
||||
padding: const EdgeInsets.only(left: GcSpace.xl, right: GcSpace.sm),
|
||||
child: Row(
|
||||
children: <Widget>[
|
||||
Text(
|
||||
title,
|
||||
style: TextStyle(
|
||||
fontSize: 12.5,
|
||||
height: 1.2,
|
||||
fontWeight: FontWeight.w600,
|
||||
letterSpacing: 0.2,
|
||||
color: GcColors.faint,
|
||||
),
|
||||
),
|
||||
const Spacer(),
|
||||
_WindowButton(
|
||||
icon: Icons.remove_rounded,
|
||||
tooltip: '最小化',
|
||||
onTap: GcWindow.minimize,
|
||||
),
|
||||
_WindowButton(
|
||||
icon: Icons.crop_square_rounded,
|
||||
tooltip: '最大化',
|
||||
onTap: GcWindow.toggleMaximize,
|
||||
),
|
||||
_WindowButton(
|
||||
icon: Icons.close_rounded,
|
||||
tooltip: '关闭',
|
||||
danger: true,
|
||||
onTap: GcWindow.close,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _WindowButton extends StatefulWidget {
|
||||
const _WindowButton({
|
||||
required this.icon,
|
||||
required this.tooltip,
|
||||
required this.onTap,
|
||||
this.danger = false,
|
||||
});
|
||||
|
||||
final IconData icon;
|
||||
final String tooltip;
|
||||
final Future<void> Function() onTap;
|
||||
final bool danger;
|
||||
|
||||
@override
|
||||
State<_WindowButton> createState() => _WindowButtonState();
|
||||
}
|
||||
|
||||
class _WindowButtonState extends State<_WindowButton> {
|
||||
bool _hover = false;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final Color bg = _hover
|
||||
? (widget.danger
|
||||
? GcColors.danger.withOpacity(0.16)
|
||||
: GcColors.surfaceHover)
|
||||
: Colors.transparent;
|
||||
|
||||
return Tooltip(
|
||||
message: widget.tooltip,
|
||||
waitDuration: const Duration(milliseconds: 500),
|
||||
child: MouseRegion(
|
||||
cursor: SystemMouseCursors.basic,
|
||||
onEnter: (_) => setState(() => _hover = true),
|
||||
onExit: (_) => setState(() => _hover = false),
|
||||
child: GestureDetector(
|
||||
onTap: () => widget.onTap(),
|
||||
child: AnimatedContainer(
|
||||
duration: const Duration(milliseconds: 110),
|
||||
width: 40,
|
||||
height: GcTitleBar.height,
|
||||
alignment: Alignment.center,
|
||||
color: bg,
|
||||
child: Icon(
|
||||
widget.icon,
|
||||
size: 15,
|
||||
color: _hover
|
||||
? (widget.danger ? GcColors.danger : GcColors.ink)
|
||||
: GcColors.faint,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,52 @@ class MainFlutterWindow: NSWindow {
|
||||
self.contentViewController = flutterViewController
|
||||
self.setFrame(windowFrame, display: true)
|
||||
|
||||
// 去掉系统标题栏(应用名 + 红绿灯按钮),改由 Flutter 自绘:
|
||||
// fullSizeContentView 让内容铺满整窗,titlebarAppearsTransparent + titleVisibility
|
||||
// 隐藏标题栏文字与背景,三个系统按钮一并隐藏。
|
||||
// 注意:不要动 styleMask 里的 .resizable,否则窗口无法缩放。
|
||||
self.titleVisibility = .hidden
|
||||
self.titlebarAppearsTransparent = true
|
||||
self.styleMask.insert(.fullSizeContentView)
|
||||
self.standardWindowButton(.closeButton)?.isHidden = true
|
||||
self.standardWindowButton(.miniaturizeButton)?.isHidden = true
|
||||
self.standardWindowButton(.zoomButton)?.isHidden = true
|
||||
self.isMovableByWindowBackground = true
|
||||
|
||||
// 自绘按钮 -> 原生窗口操作
|
||||
let channel = FlutterMethodChannel(
|
||||
name: "gc/window",
|
||||
binaryMessenger: flutterViewController.engine.binaryMessenger
|
||||
)
|
||||
channel.setMethodCallHandler { [weak self] call, result in
|
||||
guard let self = self else {
|
||||
result(FlutterMethodNotImplemented)
|
||||
return
|
||||
}
|
||||
switch call.method {
|
||||
case "minimize":
|
||||
self.miniaturize(nil)
|
||||
result(nil)
|
||||
case "toggleMaximize":
|
||||
// NSWindow.zoom(_:) 自带切换语义:放大状态下再调即还原
|
||||
self.zoom(nil)
|
||||
result(nil)
|
||||
case "close":
|
||||
self.close()
|
||||
result(nil)
|
||||
case "isMaximized":
|
||||
result(self.isZoomed)
|
||||
case "beginDrag":
|
||||
// 拖拽整窗:用系统拖拽,比在 Dart 里逐帧挪窗口平滑
|
||||
if let event = NSApp.currentEvent {
|
||||
self.performDrag(with: event)
|
||||
}
|
||||
result(nil)
|
||||
default:
|
||||
result(FlutterMethodNotImplemented)
|
||||
}
|
||||
}
|
||||
|
||||
RegisterGeneratedPlugins(registry: flutterViewController)
|
||||
|
||||
super.awakeFromNib()
|
||||
|
||||
+37
-37
@@ -6,7 +6,7 @@ packages:
|
||||
description:
|
||||
name: async
|
||||
sha256: "947bfcf187f74dbc5e146c9eb9c0f10c9f8b30743e341481c1e2ed3ecc18c20c"
|
||||
url: "https://pub.dev"
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "2.11.0"
|
||||
boolean_selector:
|
||||
@@ -14,7 +14,7 @@ packages:
|
||||
description:
|
||||
name: boolean_selector
|
||||
sha256: "6cfb5af12253eaf2b368f07bacc5a80d1301a071c73360d746b7f2e32d762c66"
|
||||
url: "https://pub.dev"
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "2.1.1"
|
||||
characters:
|
||||
@@ -22,7 +22,7 @@ packages:
|
||||
description:
|
||||
name: characters
|
||||
sha256: "04a925763edad70e8443c99234dc3328f442e811f1d8fd1a72f1c8ad0f69a605"
|
||||
url: "https://pub.dev"
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "1.3.0"
|
||||
clock:
|
||||
@@ -30,7 +30,7 @@ packages:
|
||||
description:
|
||||
name: clock
|
||||
sha256: cb6d7f03e1de671e34607e909a7213e31d7752be4fb66a86d29fe1eb14bfb5cf
|
||||
url: "https://pub.dev"
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "1.1.1"
|
||||
collection:
|
||||
@@ -38,7 +38,7 @@ packages:
|
||||
description:
|
||||
name: collection
|
||||
sha256: ee67cb0715911d28db6bf4af1026078bd6f0128b07a5f66fb2ed94ec6783c09a
|
||||
url: "https://pub.dev"
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "1.18.0"
|
||||
cupertino_icons:
|
||||
@@ -46,7 +46,7 @@ packages:
|
||||
description:
|
||||
name: cupertino_icons
|
||||
sha256: ba631d1c7f7bef6b729a622b7b752645a2d076dba9976925b8f25725a30e1ee6
|
||||
url: "https://pub.dev"
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "1.0.8"
|
||||
fake_async:
|
||||
@@ -54,7 +54,7 @@ packages:
|
||||
description:
|
||||
name: fake_async
|
||||
sha256: "511392330127add0b769b75a987850d136345d9227c6b94c96a04cf4a391bf78"
|
||||
url: "https://pub.dev"
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "1.3.1"
|
||||
flutter:
|
||||
@@ -67,7 +67,7 @@ packages:
|
||||
description:
|
||||
name: flutter_inappwebview
|
||||
sha256: "80092d13d3e29b6227e25b67973c67c7210bd5e35c4b747ca908e31eb71a46d5"
|
||||
url: "https://pub.dev"
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "6.1.5"
|
||||
flutter_inappwebview_android:
|
||||
@@ -75,7 +75,7 @@ packages:
|
||||
description:
|
||||
name: flutter_inappwebview_android
|
||||
sha256: "62557c15a5c2db5d195cb3892aab74fcaec266d7b86d59a6f0027abd672cddba"
|
||||
url: "https://pub.dev"
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "1.1.3"
|
||||
flutter_inappwebview_internal_annotations:
|
||||
@@ -83,7 +83,7 @@ packages:
|
||||
description:
|
||||
name: flutter_inappwebview_internal_annotations
|
||||
sha256: "787171d43f8af67864740b6f04166c13190aa74a1468a1f1f1e9ee5b90c359cd"
|
||||
url: "https://pub.dev"
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "1.2.0"
|
||||
flutter_inappwebview_ios:
|
||||
@@ -91,7 +91,7 @@ packages:
|
||||
description:
|
||||
name: flutter_inappwebview_ios
|
||||
sha256: "5818cf9b26cf0cbb0f62ff50772217d41ea8d3d9cc00279c45f8aabaa1b4025d"
|
||||
url: "https://pub.dev"
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "1.1.2"
|
||||
flutter_inappwebview_macos:
|
||||
@@ -99,7 +99,7 @@ packages:
|
||||
description:
|
||||
name: flutter_inappwebview_macos
|
||||
sha256: c1fbb86af1a3738e3541364d7d1866315ffb0468a1a77e34198c9be571287da1
|
||||
url: "https://pub.dev"
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "1.1.2"
|
||||
flutter_inappwebview_platform_interface:
|
||||
@@ -107,7 +107,7 @@ packages:
|
||||
description:
|
||||
name: flutter_inappwebview_platform_interface
|
||||
sha256: cf5323e194096b6ede7a1ca808c3e0a078e4b33cc3f6338977d75b4024ba2500
|
||||
url: "https://pub.dev"
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "1.3.0+1"
|
||||
flutter_inappwebview_web:
|
||||
@@ -115,7 +115,7 @@ packages:
|
||||
description:
|
||||
name: flutter_inappwebview_web
|
||||
sha256: "55f89c83b0a0d3b7893306b3bb545ba4770a4df018204917148ebb42dc14a598"
|
||||
url: "https://pub.dev"
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "1.1.2"
|
||||
flutter_inappwebview_windows:
|
||||
@@ -123,7 +123,7 @@ packages:
|
||||
description:
|
||||
name: flutter_inappwebview_windows
|
||||
sha256: "8b4d3a46078a2cdc636c4a3d10d10f2a16882f6be607962dbfff8874d1642055"
|
||||
url: "https://pub.dev"
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "0.6.0"
|
||||
flutter_lints:
|
||||
@@ -131,7 +131,7 @@ packages:
|
||||
description:
|
||||
name: flutter_lints
|
||||
sha256: "3f41d009ba7172d5ff9be5f6e6e6abb4300e263aab8866d2a0842ed2a70f8f0c"
|
||||
url: "https://pub.dev"
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "4.0.0"
|
||||
flutter_test:
|
||||
@@ -149,7 +149,7 @@ packages:
|
||||
description:
|
||||
name: http
|
||||
sha256: "87721a4a50b19c7f1d49001e51409bddc46303966ce89a65af4f4e6004896412"
|
||||
url: "https://pub.dev"
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "1.6.0"
|
||||
http_parser:
|
||||
@@ -157,7 +157,7 @@ packages:
|
||||
description:
|
||||
name: http_parser
|
||||
sha256: "2aa08ce0341cc9b354a498388e30986515406668dbcc4f7c950c3e715496693b"
|
||||
url: "https://pub.dev"
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "4.0.2"
|
||||
leak_tracker:
|
||||
@@ -165,7 +165,7 @@ packages:
|
||||
description:
|
||||
name: leak_tracker
|
||||
sha256: "3f87a60e8c63aecc975dda1ceedbc8f24de75f09e4856ea27daf8958f2f0ce05"
|
||||
url: "https://pub.dev"
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "10.0.5"
|
||||
leak_tracker_flutter_testing:
|
||||
@@ -173,7 +173,7 @@ packages:
|
||||
description:
|
||||
name: leak_tracker_flutter_testing
|
||||
sha256: "932549fb305594d82d7183ecd9fa93463e9914e1b67cacc34bc40906594a1806"
|
||||
url: "https://pub.dev"
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "3.0.5"
|
||||
leak_tracker_testing:
|
||||
@@ -181,7 +181,7 @@ packages:
|
||||
description:
|
||||
name: leak_tracker_testing
|
||||
sha256: "6ba465d5d76e67ddf503e1161d1f4a6bc42306f9d66ca1e8f079a47290fb06d3"
|
||||
url: "https://pub.dev"
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "3.0.1"
|
||||
lints:
|
||||
@@ -189,7 +189,7 @@ packages:
|
||||
description:
|
||||
name: lints
|
||||
sha256: "976c774dd944a42e83e2467f4cc670daef7eed6295b10b36ae8c85bcbf828235"
|
||||
url: "https://pub.dev"
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "4.0.0"
|
||||
matcher:
|
||||
@@ -197,7 +197,7 @@ packages:
|
||||
description:
|
||||
name: matcher
|
||||
sha256: d2323aa2060500f906aa31a895b4030b6da3ebdcc5619d14ce1aada65cd161cb
|
||||
url: "https://pub.dev"
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "0.12.16+1"
|
||||
material_color_utilities:
|
||||
@@ -205,7 +205,7 @@ packages:
|
||||
description:
|
||||
name: material_color_utilities
|
||||
sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec
|
||||
url: "https://pub.dev"
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "0.11.1"
|
||||
meta:
|
||||
@@ -213,7 +213,7 @@ packages:
|
||||
description:
|
||||
name: meta
|
||||
sha256: bdb68674043280c3428e9ec998512fb681678676b3c54e773629ffe74419f8c7
|
||||
url: "https://pub.dev"
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "1.15.0"
|
||||
path:
|
||||
@@ -221,7 +221,7 @@ packages:
|
||||
description:
|
||||
name: path
|
||||
sha256: "087ce49c3f0dc39180befefc60fdb4acd8f8620e5682fe2476afd0b3688bb4af"
|
||||
url: "https://pub.dev"
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "1.9.0"
|
||||
plugin_platform_interface:
|
||||
@@ -229,7 +229,7 @@ packages:
|
||||
description:
|
||||
name: plugin_platform_interface
|
||||
sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02"
|
||||
url: "https://pub.dev"
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "2.1.8"
|
||||
sky_engine:
|
||||
@@ -242,7 +242,7 @@ packages:
|
||||
description:
|
||||
name: source_span
|
||||
sha256: "53e943d4206a5e30df338fd4c6e7a077e02254531b138a15aec3bd143c1a8b3c"
|
||||
url: "https://pub.dev"
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "1.10.0"
|
||||
stack_trace:
|
||||
@@ -250,7 +250,7 @@ packages:
|
||||
description:
|
||||
name: stack_trace
|
||||
sha256: "73713990125a6d93122541237550ee3352a2d84baad52d375a4cad2eb9b7ce0b"
|
||||
url: "https://pub.dev"
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "1.11.1"
|
||||
stream_channel:
|
||||
@@ -258,7 +258,7 @@ packages:
|
||||
description:
|
||||
name: stream_channel
|
||||
sha256: ba2aa5d8cc609d96bbb2899c28934f9e1af5cddbd60a827822ea467161eb54e7
|
||||
url: "https://pub.dev"
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "2.1.2"
|
||||
string_scanner:
|
||||
@@ -266,7 +266,7 @@ packages:
|
||||
description:
|
||||
name: string_scanner
|
||||
sha256: "556692adab6cfa87322a115640c11f13cb77b3f076ddcc5d6ae3c20242bedcde"
|
||||
url: "https://pub.dev"
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "1.2.0"
|
||||
term_glyph:
|
||||
@@ -274,7 +274,7 @@ packages:
|
||||
description:
|
||||
name: term_glyph
|
||||
sha256: a29248a84fbb7c79282b40b8c72a1209db169a2e0542bce341da992fe1bc7e84
|
||||
url: "https://pub.dev"
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "1.2.1"
|
||||
test_api:
|
||||
@@ -282,7 +282,7 @@ packages:
|
||||
description:
|
||||
name: test_api
|
||||
sha256: "5b8a98dafc4d5c4c9c72d8b31ab2b23fc13422348d2997120294d3bac86b4ddb"
|
||||
url: "https://pub.dev"
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "0.7.2"
|
||||
typed_data:
|
||||
@@ -290,7 +290,7 @@ packages:
|
||||
description:
|
||||
name: typed_data
|
||||
sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006
|
||||
url: "https://pub.dev"
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "1.4.0"
|
||||
vector_math:
|
||||
@@ -298,7 +298,7 @@ packages:
|
||||
description:
|
||||
name: vector_math
|
||||
sha256: "80b3257d1492ce4d091729e3a67a60407d227c27241d6927be0130c98e741803"
|
||||
url: "https://pub.dev"
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "2.1.4"
|
||||
vm_service:
|
||||
@@ -306,7 +306,7 @@ packages:
|
||||
description:
|
||||
name: vm_service
|
||||
sha256: "5c5f338a667b4c644744b661f309fb8080bb94b18a7e91ef1dbd343bed00ed6d"
|
||||
url: "https://pub.dev"
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "14.2.5"
|
||||
web:
|
||||
@@ -314,7 +314,7 @@ packages:
|
||||
description:
|
||||
name: web
|
||||
sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a"
|
||||
url: "https://pub.dev"
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "1.1.1"
|
||||
sdks:
|
||||
|
||||
@@ -13,30 +13,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "GC", "GC", "{3E72BF5C-0B5E-
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{09578AA7-0862-3E52-D2AA-D8F7E863B74B}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GC.Tests", "GC\src\test\dotnet\GC.Tests\GC.Tests.csproj", "{D15CB92F-5E5C-4516-8D07-C244FC0CD113}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "_sdk", "_sdk", "{26AABC0C-8B8D-F9B8-86B4-01B1A96D59F4}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GC.ModelSdk", "model\_sdk\GC.ModelSdk\GC.ModelSdk.csproj", "{C8FAB8D5-CAB7-42D7-8A1F-4B79771A2CE0}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "model", "model", "{62B8A37E-7066-D91A-6443-87D4E6CE63FE}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "earth-rotation", "earth-rotation", "{EBCD2737-5E64-9C5F-5D8B-D0375EC50F43}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{13F93445-B061-AC9E-97CA-8C4FA55DC418}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EarthRotationModel", "model\earth-rotation\src\EarthRotationModel.csproj", "{64556F71-7456-43B2-890C-CF01AD29D386}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "earth-revolution", "earth-revolution", "{0B92F86C-37C2-3C12-904C-85123CE34F4C}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{EADF0841-BEC2-9A74-4322-069D7B5A6EBB}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EarthRevolutionModel", "model\earth-revolution\src\EarthRevolutionModel.csproj", "{6BD9C21B-8F06-4F60-A087-696B6F03CC25}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GC.Core", "GC\src\GC.Core.csproj", "{AB63C416-5783-4FB9-A162-5BBA32E8BFCC}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "_sdk", "_sdk", "{6C38EF76-7D14-0C76-0B88-84F29EAA96CD}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GC-DOWNLOAD", "GC-DOWNLOAD\GC-DOWNLOAD.csproj", "{98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GC-SAVEDOG", "GC-SAVEDOG\GC-SAVEDOG.csproj", "{B169F2BF-9E60-40BF-824E-0486573DA65E}"
|
||||
@@ -69,54 +47,6 @@ Global
|
||||
{2E3BE2DB-1C4B-4EA0-9523-43EE910BD54C}.Release|x64.Build.0 = Release|Any CPU
|
||||
{2E3BE2DB-1C4B-4EA0-9523-43EE910BD54C}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{2E3BE2DB-1C4B-4EA0-9523-43EE910BD54C}.Release|x86.Build.0 = Release|Any CPU
|
||||
{D15CB92F-5E5C-4516-8D07-C244FC0CD113}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{D15CB92F-5E5C-4516-8D07-C244FC0CD113}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{D15CB92F-5E5C-4516-8D07-C244FC0CD113}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{D15CB92F-5E5C-4516-8D07-C244FC0CD113}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{D15CB92F-5E5C-4516-8D07-C244FC0CD113}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{D15CB92F-5E5C-4516-8D07-C244FC0CD113}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{D15CB92F-5E5C-4516-8D07-C244FC0CD113}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{D15CB92F-5E5C-4516-8D07-C244FC0CD113}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{D15CB92F-5E5C-4516-8D07-C244FC0CD113}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{D15CB92F-5E5C-4516-8D07-C244FC0CD113}.Release|x64.Build.0 = Release|Any CPU
|
||||
{D15CB92F-5E5C-4516-8D07-C244FC0CD113}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{D15CB92F-5E5C-4516-8D07-C244FC0CD113}.Release|x86.Build.0 = Release|Any CPU
|
||||
{C8FAB8D5-CAB7-42D7-8A1F-4B79771A2CE0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{C8FAB8D5-CAB7-42D7-8A1F-4B79771A2CE0}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{C8FAB8D5-CAB7-42D7-8A1F-4B79771A2CE0}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{C8FAB8D5-CAB7-42D7-8A1F-4B79771A2CE0}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{C8FAB8D5-CAB7-42D7-8A1F-4B79771A2CE0}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{C8FAB8D5-CAB7-42D7-8A1F-4B79771A2CE0}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{C8FAB8D5-CAB7-42D7-8A1F-4B79771A2CE0}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{C8FAB8D5-CAB7-42D7-8A1F-4B79771A2CE0}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{C8FAB8D5-CAB7-42D7-8A1F-4B79771A2CE0}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{C8FAB8D5-CAB7-42D7-8A1F-4B79771A2CE0}.Release|x64.Build.0 = Release|Any CPU
|
||||
{C8FAB8D5-CAB7-42D7-8A1F-4B79771A2CE0}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{C8FAB8D5-CAB7-42D7-8A1F-4B79771A2CE0}.Release|x86.Build.0 = Release|Any CPU
|
||||
{64556F71-7456-43B2-890C-CF01AD29D386}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{64556F71-7456-43B2-890C-CF01AD29D386}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{64556F71-7456-43B2-890C-CF01AD29D386}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{64556F71-7456-43B2-890C-CF01AD29D386}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{64556F71-7456-43B2-890C-CF01AD29D386}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{64556F71-7456-43B2-890C-CF01AD29D386}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{64556F71-7456-43B2-890C-CF01AD29D386}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{64556F71-7456-43B2-890C-CF01AD29D386}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{64556F71-7456-43B2-890C-CF01AD29D386}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{64556F71-7456-43B2-890C-CF01AD29D386}.Release|x64.Build.0 = Release|Any CPU
|
||||
{64556F71-7456-43B2-890C-CF01AD29D386}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{64556F71-7456-43B2-890C-CF01AD29D386}.Release|x86.Build.0 = Release|Any CPU
|
||||
{6BD9C21B-8F06-4F60-A087-696B6F03CC25}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{6BD9C21B-8F06-4F60-A087-696B6F03CC25}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{6BD9C21B-8F06-4F60-A087-696B6F03CC25}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{6BD9C21B-8F06-4F60-A087-696B6F03CC25}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{6BD9C21B-8F06-4F60-A087-696B6F03CC25}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{6BD9C21B-8F06-4F60-A087-696B6F03CC25}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{6BD9C21B-8F06-4F60-A087-696B6F03CC25}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{6BD9C21B-8F06-4F60-A087-696B6F03CC25}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{6BD9C21B-8F06-4F60-A087-696B6F03CC25}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{6BD9C21B-8F06-4F60-A087-696B6F03CC25}.Release|x64.Build.0 = Release|Any CPU
|
||||
{6BD9C21B-8F06-4F60-A087-696B6F03CC25}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{6BD9C21B-8F06-4F60-A087-696B6F03CC25}.Release|x86.Build.0 = Release|Any CPU
|
||||
{AB63C416-5783-4FB9-A162-5BBA32E8BFCC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{AB63C416-5783-4FB9-A162-5BBA32E8BFCC}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{AB63C416-5783-4FB9-A162-5BBA32E8BFCC}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
@@ -172,16 +102,7 @@ Global
|
||||
GlobalSection(NestedProjects) = preSolution
|
||||
{2E3BE2DB-1C4B-4EA0-9523-43EE910BD54C} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
|
||||
{09578AA7-0862-3E52-D2AA-D8F7E863B74B} = {3E72BF5C-0B5E-D5BD-DCAE-6B991004B4A5}
|
||||
{D15CB92F-5E5C-4516-8D07-C244FC0CD113} = {09578AA7-0862-3E52-D2AA-D8F7E863B74B}
|
||||
{C8FAB8D5-CAB7-42D7-8A1F-4B79771A2CE0} = {26AABC0C-8B8D-F9B8-86B4-01B1A96D59F4}
|
||||
{EBCD2737-5E64-9C5F-5D8B-D0375EC50F43} = {62B8A37E-7066-D91A-6443-87D4E6CE63FE}
|
||||
{13F93445-B061-AC9E-97CA-8C4FA55DC418} = {EBCD2737-5E64-9C5F-5D8B-D0375EC50F43}
|
||||
{64556F71-7456-43B2-890C-CF01AD29D386} = {13F93445-B061-AC9E-97CA-8C4FA55DC418}
|
||||
{0B92F86C-37C2-3C12-904C-85123CE34F4C} = {62B8A37E-7066-D91A-6443-87D4E6CE63FE}
|
||||
{EADF0841-BEC2-9A74-4322-069D7B5A6EBB} = {0B92F86C-37C2-3C12-904C-85123CE34F4C}
|
||||
{6BD9C21B-8F06-4F60-A087-696B6F03CC25} = {EADF0841-BEC2-9A74-4322-069D7B5A6EBB}
|
||||
{AB63C416-5783-4FB9-A162-5BBA32E8BFCC} = {09578AA7-0862-3E52-D2AA-D8F7E863B74B}
|
||||
{6C38EF76-7D14-0C76-0B88-84F29EAA96CD} = {62B8A37E-7066-D91A-6443-87D4E6CE63FE}
|
||||
{98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3} = {BCA2AA3E-F98F-43A1-9D31-239103C303F7}
|
||||
{59BED32E-68DD-4FA2-9A8E-89C71966F30E} = {560E034A-28FD-4D82-ABD0-FBD0C1B0F553}
|
||||
{33EA353C-FD81-4288-872E-D9404D9E50AF} = {59BED32E-68DD-4FA2-9A8E-89C71966F30E}
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
<Application xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:vm="using:GC.ViewModels"
|
||||
xmlns:views="using:GC.Views"
|
||||
x:Class="GC.App"
|
||||
RequestedThemeVariant="Light">
|
||||
|
||||
<Application.DataTemplates>
|
||||
<DataTemplate DataType="{x:Type vm:HomeViewModel}">
|
||||
<views:HomeView />
|
||||
</DataTemplate>
|
||||
<DataTemplate DataType="{x:Type vm:DownloadViewModel}">
|
||||
<views:DownloadView />
|
||||
</DataTemplate>
|
||||
<DataTemplate DataType="{x:Type vm:SettingsViewModel}">
|
||||
<views:SettingsView />
|
||||
</DataTemplate>
|
||||
<DataTemplate DataType="{x:Type vm:AboutViewModel}">
|
||||
<views:AboutView />
|
||||
</DataTemplate>
|
||||
</Application.DataTemplates>
|
||||
|
||||
<Application.Resources>
|
||||
<Color x:Key="SystemAccentColor">#2F6BFF</Color>
|
||||
|
||||
<!--
|
||||
FluentTheme 的按钮模板在 :pointerover / :pressed 时会用这些主题资源
|
||||
覆盖 ContentPresenter 的画刷。若与 AppTheme.axaml 里通过 Button 属性
|
||||
设置的 hover 颜色不一致,两套机制会互相覆盖,导致光标移动时渲染错乱。
|
||||
这里把它们统一指向与按钮样式相同的颜色。
|
||||
-->
|
||||
<SolidColorBrush x:Key="ButtonBackgroundPointerOver">#EDF2FC</SolidColorBrush>
|
||||
<SolidColorBrush x:Key="ButtonBackgroundPressed">#DDE7F8</SolidColorBrush>
|
||||
<SolidColorBrush x:Key="ButtonBorderBrushPointerOver">#BAC9E6</SolidColorBrush>
|
||||
<SolidColorBrush x:Key="ButtonBorderBrushPressed">#9FB4DD</SolidColorBrush>
|
||||
<SolidColorBrush x:Key="ButtonForegroundPointerOver">#111A2E</SolidColorBrush>
|
||||
<SolidColorBrush x:Key="ButtonForegroundPressed">#111A2E</SolidColorBrush>
|
||||
|
||||
<SolidColorBrush x:Key="AccentButtonBackground">#2F6BFF</SolidColorBrush>
|
||||
<SolidColorBrush x:Key="AccentButtonBackgroundPointerOver">#1F4FD0</SolidColorBrush>
|
||||
<SolidColorBrush x:Key="AccentButtonBackgroundPressed">#183FA8</SolidColorBrush>
|
||||
</Application.Resources>
|
||||
|
||||
<Application.Styles>
|
||||
<FluentTheme />
|
||||
<StyleInclude Source="avares://GC.Core/Styles/AppTheme.axaml" />
|
||||
</Application.Styles>
|
||||
</Application>
|
||||
@@ -1,134 +0,0 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Controls.ApplicationLifetimes;
|
||||
using Avalonia.Markup.Xaml;
|
||||
using GC.Services;
|
||||
using GC.ViewModels;
|
||||
using GC.Views;
|
||||
|
||||
namespace GC;
|
||||
|
||||
public partial class App : Application
|
||||
{
|
||||
public override void Initialize() => AvaloniaXamlLoader.Load(this);
|
||||
|
||||
public override void OnFrameworkInitializationCompleted()
|
||||
{
|
||||
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
|
||||
{
|
||||
var services = AppServices.Create();
|
||||
|
||||
// 诊断模式:只验证模型程序集能否加载(发布包里也用它做冒烟测试)
|
||||
if (Environment.GetEnvironmentVariable("EMS_SELFTEST") == "1")
|
||||
{
|
||||
var code = SelfTest(services);
|
||||
Avalonia.Threading.Dispatcher.UIThread.Post(
|
||||
() => desktop.Shutdown(code), Avalonia.Threading.DispatcherPriority.Background);
|
||||
return;
|
||||
}
|
||||
|
||||
// 启动加速:先建空窗口并显示,再在首帧之后构造 ViewModel。
|
||||
// MainViewModel 会扫描模型、加载封面、读设置,同步做会让
|
||||
// 「双击到看见窗口」明显变慢;先出窗口,内容随后填充。
|
||||
var window = new MainWindow();
|
||||
window.Show();
|
||||
|
||||
// 健康标记:GC-SAVEDOG 正在等这个文件。主窗口能显示出来,
|
||||
// 就说明「新版本确实能启动」,它据此决定保留新版还是回滚。
|
||||
StartupHealth.MarkHealthy(services.Paths.UpdateRoot,
|
||||
LauncherRuntimeInfo.CurrentLauncherVersion);
|
||||
|
||||
// 首帧之后再构造 ViewModel:Post 而非依赖 Opened,
|
||||
// 因为 Opened 在某些情况下不触发(headless / 部分平台),
|
||||
// 会导致 DataContext 一直是 null、主页面白屏。
|
||||
// 扫描模型 / 加载封面在后台线程做,UI 线程只负责赋值,
|
||||
// 这样窗口能立刻响应,不会卡在白屏。
|
||||
MainViewModel vm = null!;
|
||||
Task.Run(() => new MainViewModel(services))
|
||||
.ContinueWith(t =>
|
||||
{
|
||||
vm = t.Result;
|
||||
Avalonia.Threading.Dispatcher.UIThread.Post(() =>
|
||||
{
|
||||
window.DataContext = vm;
|
||||
WireMainViewModel(vm, window, services, desktop);
|
||||
}, Avalonia.Threading.DispatcherPriority.Background);
|
||||
}, System.Threading.Tasks.TaskScheduler.Default);
|
||||
|
||||
// 应用图标不依赖 ViewModel,先设好让窗口一出现就有图标
|
||||
try
|
||||
{
|
||||
using var iconStream = Avalonia.Platform.AssetLoader.Open(
|
||||
new Uri("avares://GC.Core/Assets/icon.png"));
|
||||
window.Icon = new Avalonia.Controls.WindowIcon(iconStream);
|
||||
}
|
||||
catch { /* 图标缺失不影响启动 */ }
|
||||
|
||||
desktop.MainWindow = window;
|
||||
desktop.ShutdownMode = ShutdownMode.OnMainWindowClose;
|
||||
}
|
||||
|
||||
base.OnFrameworkInitializationCompleted();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 主窗口显示后再接上 ViewModel:绑定对话框、启动后台更新检查。
|
||||
/// 拆出来是为了让窗口先出现,模型扫描不影响「双击到出窗口」。
|
||||
/// </summary>
|
||||
private static void WireMainViewModel(MainViewModel vm, MainWindow window,
|
||||
AppServices services, IClassicDesktopStyleApplicationLifetime desktop)
|
||||
{
|
||||
_ = desktop;
|
||||
vm.ConfirmHandler = async message =>
|
||||
{
|
||||
var dialog = new ConfirmWindow(message);
|
||||
return await dialog.ShowDialog<bool>(window);
|
||||
};
|
||||
|
||||
// 发现启动器新版本:弹窗询问,用户选「更新」才下载并安排替换
|
||||
vm.LauncherUpdateHandler = async newVersion =>
|
||||
{
|
||||
var dialog = new ConfirmWindow(
|
||||
title: "发现新版本",
|
||||
message: $"启动器有新版本 v{newVersion},是否立即更新?\n\n" +
|
||||
"更新会下载新版程序,下次启动时自动替换当前版本;" +
|
||||
"选择取消则继续使用当前版本,但模型仍会更新到最新。",
|
||||
confirmText: "更新",
|
||||
cancelText: "取消");
|
||||
return await dialog.ShowDialog<bool>(window);
|
||||
};
|
||||
|
||||
// 主窗口已显示,后台检查模型 / 启动器更新,不阻塞界面
|
||||
if (Environment.GetEnvironmentVariable("EMS_NO_UPDATE") != "1")
|
||||
{
|
||||
Avalonia.Threading.Dispatcher.UIThread.Post(
|
||||
() => _ = vm.RunStartupUpdateAsync(),
|
||||
Avalonia.Threading.DispatcherPriority.Background);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>逐个加载模型,打印结果;返回退出码(0 = 全部成功)。</summary>
|
||||
private static int SelfTest(AppServices services)
|
||||
{
|
||||
var packages = services.Models.Scan();
|
||||
Console.WriteLine($"模型库: {services.Paths.ModelRoot}");
|
||||
Console.WriteLine($"模型数: {packages.Count}");
|
||||
var failed = 0;
|
||||
foreach (var package in packages)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var loaded = services.ModelHost.Load(package, () => { });
|
||||
Console.WriteLine($"OK {package.Id} -> {loaded.View.GetType().FullName}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
failed++;
|
||||
Console.WriteLine($"FAIL {package.Id}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
return failed == 0 ? 0 : 1;
|
||||
}
|
||||
}
|
||||
@@ -5,14 +5,18 @@
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<RootNamespace>GC</RootNamespace>
|
||||
<AssemblyName>GC.Core</AssemblyName>
|
||||
<AvaloniaUseCompiledBindingsByDefault>false</AvaloniaUseCompiledBindingsByDefault>
|
||||
<InvariantGlobalization>false</InvariantGlobalization>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<AvaloniaResource Include="Assets\**" />
|
||||
<!-- 界面仍是 Flutter,但模型由 Avalonia 承载(模型契约返回 Avalonia Control),
|
||||
所以核心库需要 Avalonia + 模型 SDK,并把 GC-DRAW 的窗口一起编译进来。 -->
|
||||
<Compile Include="..\..\GC-DRAW\PlayerWindow.cs" />
|
||||
<Compile Remove="test\**\*.cs" />
|
||||
<AvaloniaResource Include="Assets\**" />
|
||||
<!-- 多语言表原先通过 Avalonia 的 avares:// 读取,改为嵌入资源 -->
|
||||
<EmbeddedResource Include="Assets\i18n\*.json"
|
||||
LogicalName="GC.Core.Assets.i18n.%(Filename)%(Extension)" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -13,7 +13,7 @@ public sealed class AppServices
|
||||
public IDownloadCenter Downloads { get; }
|
||||
public MemoryBudget Memory { get; }
|
||||
public IModelSourceClient Sources { get; }
|
||||
/// <summary>模型加载器:只负责把模型程序集跑起来,不渲染。</summary>
|
||||
/// <summary>模型加载器:只负责把模型程序集跑起来,不渲染(渲染在 Avalonia PlayerWindow)。</summary>
|
||||
public ModelHost ModelHost { get; }
|
||||
/// <summary>启动时检查模型 / 启动器更新。</summary>
|
||||
public IUpdateService Updates { get; }
|
||||
|
||||
@@ -51,7 +51,8 @@ public static class ContributorsService
|
||||
private const int MaxShown = 8;
|
||||
private static readonly TimeSpan CacheTtl = TimeSpan.FromMinutes(10);
|
||||
|
||||
private static readonly HttpClient Http = CreateHttp();
|
||||
// 使用共享 HttpClient
|
||||
private static readonly HttpClient Http = SharedHttpClientFactory.GetDefault();
|
||||
|
||||
/// <summary>同一作者的多个 git 身份 -> 统一展示名。</summary>
|
||||
private static readonly Dictionary<string, string> Aliases = new(StringComparer.OrdinalIgnoreCase)
|
||||
@@ -61,6 +62,9 @@ public static class ContributorsService
|
||||
["2509_92447106"] = "Morris",
|
||||
["chenmoyuan1214@qq.com"] = "Morris",
|
||||
["morris@xhmcl.com"] = "Morris",
|
||||
// 远影科技是 Morris 的另一个 git 身份(同一邮箱),归并到 Morris
|
||||
["远影科技"] = "Morris",
|
||||
["yuanying@yuanying.tech"] = "Morris",
|
||||
// 早期提交用的是 xhgit 这个账号,展示名统一成 itxiaohui
|
||||
["xhgit"] = "itxiaohui",
|
||||
["itxiaohui"] = "itxiaohui",
|
||||
@@ -75,14 +79,6 @@ public static class ContributorsService
|
||||
private static readonly object Gate = new();
|
||||
private static (DateTimeOffset At, string Key, List<Contributor> Items)? _cache;
|
||||
|
||||
private static HttpClient CreateHttp()
|
||||
{
|
||||
var c = new HttpClient { Timeout = TimeSpan.FromSeconds(10) };
|
||||
c.DefaultRequestHeaders.UserAgent.ParseAdd("GC/1.0");
|
||||
c.DefaultRequestHeaders.Accept.ParseAdd("application/json");
|
||||
return c;
|
||||
}
|
||||
|
||||
/// <summary>按仓库地址推导接口:Xhmcl(Gitea) 与 GitCode 结构不同。</summary>
|
||||
public static string BuildUrl(string repository)
|
||||
{
|
||||
|
||||
@@ -1,124 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Controls.ApplicationLifetimes;
|
||||
using Avalonia.Threading;
|
||||
using GC.Views;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 启动器更新的完整交互流程(「检查更新」与「重新下载启动器」共用):
|
||||
/// 1. 关闭主窗口与所有模型窗口;
|
||||
/// 2. 弹出圆角进度窗;
|
||||
/// 3. 下载最新版到当前目录(与旧版并列);
|
||||
/// 4. 安排替换脚本、关进度窗、退出进程。
|
||||
/// 失败时恢复主窗口,继续使用当前版本。
|
||||
/// </summary>
|
||||
public static class LauncherUpdateFlow
|
||||
{
|
||||
private static bool _running;
|
||||
public static bool IsRunning => _running;
|
||||
|
||||
public static async Task RunAsync(AppServices services, string title)
|
||||
{
|
||||
if (_running) return;
|
||||
_running = true;
|
||||
|
||||
var desktop = Application.Current?.ApplicationLifetime
|
||||
as IClassicDesktopStyleApplicationLifetime;
|
||||
var mainWindow = desktop?.MainWindow;
|
||||
var progressWindow = new UpdaterWindow(title);
|
||||
|
||||
try
|
||||
{
|
||||
// 1. 关闭所有窗口
|
||||
if (desktop != null) desktop.MainWindow = null;
|
||||
try { mainWindow?.Close(); } catch { }
|
||||
foreach (var w in OpenWindows().ToList())
|
||||
{
|
||||
try { w.Close(); } catch { }
|
||||
}
|
||||
|
||||
// 2. 进度窗
|
||||
progressWindow.Show();
|
||||
progressWindow.Report(0, "准备更新…");
|
||||
await Dispatcher.UIThread.InvokeAsync(() => { }, DispatcherPriority.Render);
|
||||
|
||||
// 3. 下载
|
||||
var progress = new Progress<UpdateProgressInfo>(p =>
|
||||
progressWindow.Report(p.Value, p.Stage));
|
||||
|
||||
var result = await services.LauncherUpdates.DownloadAsync(
|
||||
services.Paths, services.Updates.Remote, progress);
|
||||
|
||||
if (result.State == UpdateRunState.Failed)
|
||||
{
|
||||
progressWindow.Report(0, "更新失败", result.Message);
|
||||
await Task.Delay(2200);
|
||||
_running = false;
|
||||
progressWindow.Close();
|
||||
RestoreMainWindow(desktop, mainWindow);
|
||||
return;
|
||||
}
|
||||
|
||||
progressWindow.Report(1, $"v{result.Version} 下载完成,正在重启…");
|
||||
|
||||
// 4. 安排替换(下次启动生效 / 脚本接管重启)
|
||||
var scheduled = services.LauncherUpdates.ScheduleApply(
|
||||
services.Paths, result.PackageName ?? "");
|
||||
|
||||
if (!scheduled)
|
||||
{
|
||||
progressWindow.Report(0, "无法安排更新", "请检查安装目录是否可写");
|
||||
await Task.Delay(2200);
|
||||
_running = false;
|
||||
progressWindow.Close();
|
||||
RestoreMainWindow(desktop, mainWindow);
|
||||
return;
|
||||
}
|
||||
|
||||
await Task.Delay(400);
|
||||
progressWindow.Close();
|
||||
desktop?.Shutdown();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"更新流程异常: {ex}");
|
||||
_running = false;
|
||||
try { progressWindow.Close(); } catch { }
|
||||
RestoreMainWindow(desktop, mainWindow);
|
||||
}
|
||||
}
|
||||
|
||||
private static void RestoreMainWindow(
|
||||
IClassicDesktopStyleApplicationLifetime? desktop, Window? mainWindow)
|
||||
{
|
||||
if (desktop == null || mainWindow == null) return;
|
||||
try
|
||||
{
|
||||
desktop.MainWindow = mainWindow;
|
||||
mainWindow.Show();
|
||||
mainWindow.Activate();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"恢复主窗口失败: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private static IEnumerable<Window> OpenWindows()
|
||||
{
|
||||
if (Application.Current?.ApplicationLifetime
|
||||
is not IClassicDesktopStyleApplicationLifetime d)
|
||||
yield break;
|
||||
foreach (var w in d.Windows)
|
||||
{
|
||||
if (w is UpdaterWindow) continue;
|
||||
yield return w;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,9 +4,6 @@ using System.ComponentModel;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
using Avalonia.Markup.Xaml;
|
||||
using Avalonia.Data;
|
||||
using Avalonia.Platform;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
@@ -75,8 +72,10 @@ public sealed class L : INotifyPropertyChanged
|
||||
{
|
||||
try
|
||||
{
|
||||
var uri = new Uri($"avares://GC.Core/Assets/i18n/{code}.json");
|
||||
using var stream = AssetLoader.Open(uri);
|
||||
// 界面已迁到 Flutter,这里不能再依赖 Avalonia 的 avares:// 资源加载
|
||||
var asm = typeof(L).Assembly;
|
||||
using var stream = asm.GetManifestResourceStream($"GC.Core.Assets.i18n.{code}.json");
|
||||
if (stream == null) return null;
|
||||
using var reader = new StreamReader(stream);
|
||||
return JsonSerializer.Deserialize<Dictionary<string, string>>(reader.ReadToEnd(),
|
||||
new JsonSerializerOptions { ReadCommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true });
|
||||
@@ -131,13 +130,3 @@ public sealed class LocalizedString : INotifyPropertyChanged
|
||||
internal void Refresh() => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Value)));
|
||||
}
|
||||
|
||||
/// <summary>XAML 用法:Text="{loc:Loc nav.home}"</summary>
|
||||
public sealed class LocExtension : MarkupExtension
|
||||
{
|
||||
public LocExtension() { }
|
||||
public LocExtension(string key) => Key = key;
|
||||
public string Key { get; set; } = "";
|
||||
|
||||
public override object ProvideValue(IServiceProvider serviceProvider)
|
||||
=> new Binding(nameof(LocalizedString.Value)) { Source = L.I.For(Key) };
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
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;
|
||||
}
|
||||
@@ -7,9 +7,9 @@ namespace GC.Services;
|
||||
/// <summary>
|
||||
/// 内置下载源。
|
||||
///
|
||||
/// 目前只启用 Xhmcl;GitCode 的 preset 与下载实现仍保留在代码中,
|
||||
/// 但不参与测速 / 下载 / 更新。两个源本来指向同一份仓库内容,
|
||||
/// 区别只是托管服务器;恢复双源时把 GitCode 加回 <see cref="All"/>。
|
||||
/// 当前启用 Xhmcl(Gitea)与 GitHub 两个镜像,指向同一份仓库内容;
|
||||
/// 启动 / 下载 / 更新前并发测速(2 秒超时),取最快且可用的那个。
|
||||
/// GitCode 的 preset 与下载实现仍保留在代码中,但不参与测速 / 下载 / 更新。
|
||||
/// </summary>
|
||||
public sealed class SourcePreset
|
||||
{
|
||||
@@ -31,10 +31,16 @@ public sealed class SourcePreset
|
||||
|
||||
public string Repository => HomeUrl;
|
||||
|
||||
/// <summary>拼 raw 文件下载地址(两个平台的 URL 结构不同)。</summary>
|
||||
public string RawUrl(string path) => RawStyle == "plain"
|
||||
? $"{RawBase}/{Owner}/{Repo}/raw/{Branch}/{path.TrimStart('/')}"
|
||||
: $"{RawBase}/{Owner}/{Repo}/raw/branch/{Branch}/{path.TrimStart('/')}";
|
||||
/// <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()
|
||||
{
|
||||
@@ -50,6 +56,25 @@ public sealed class SourcePreset
|
||||
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",
|
||||
@@ -65,20 +90,29 @@ public sealed class SourcePreset
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// 当前启用的源:暂时只保留 Xhmcl。GitCode 的定义与实现仍保留在代码里,
|
||||
/// 但不参与测速、下载与更新(需要恢复时把 GitCode 加回这个数组即可)。
|
||||
/// 当前启用的源:Xhmcl 与 GitHub 是同一份仓库的两个镜像,启动时并发测速取最快。
|
||||
/// GitCode 的定义与实现仍保留在代码里,但不参与测速、下载与更新
|
||||
/// (需要恢复时把 GitCode 加回这个数组即可)。
|
||||
/// </summary>
|
||||
public static readonly SourcePreset[] All = { Xhmcl };
|
||||
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>
|
||||
/// <summary>把任意仓库地址 / 源名映射到启用的内置源(用于兼容旧配置与调用方取值)。</summary>
|
||||
public static SourcePreset Detect(string? url)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(url) &&
|
||||
url!.Contains("xhmcl.com", StringComparison.OrdinalIgnoreCase))
|
||||
return Xhmcl;
|
||||
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;
|
||||
|
||||
File renamed without changes.
@@ -1,325 +0,0 @@
|
||||
<Styles xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
|
||||
|
||||
<Styles.Resources>
|
||||
<SolidColorBrush x:Key="AppBg" Color="#F4F6FB" />
|
||||
<SolidColorBrush x:Key="Surface" Color="#FFFFFF" />
|
||||
<SolidColorBrush x:Key="SurfaceAlt" Color="#F7F9FE" />
|
||||
<SolidColorBrush x:Key="Line" Color="#E3E8F3" />
|
||||
<SolidColorBrush x:Key="LineStrong" Color="#D2DAEA" />
|
||||
<SolidColorBrush x:Key="Ink" Color="#111A2E" />
|
||||
<SolidColorBrush x:Key="InkDim" Color="#5B6A86" />
|
||||
<SolidColorBrush x:Key="InkFaint" Color="#8A97B1" />
|
||||
<SolidColorBrush x:Key="Accent" Color="#2F6BFF" />
|
||||
<SolidColorBrush x:Key="AccentDark" Color="#1F4FD0" />
|
||||
<SolidColorBrush x:Key="AccentSoft" Color="#EAF1FF" />
|
||||
<SolidColorBrush x:Key="SideBg" Color="#0D1526" />
|
||||
<SolidColorBrush x:Key="SideLine" Color="#1B2740" />
|
||||
<SolidColorBrush x:Key="SideInk" Color="#A9B8D4" />
|
||||
<SolidColorBrush x:Key="Success" Color="#1F9D6B" />
|
||||
<SolidColorBrush x:Key="Danger" Color="#D64545" />
|
||||
<SolidColorBrush x:Key="Warn" Color="#D98613" />
|
||||
|
||||
<LinearGradientBrush x:Key="HeroBg" StartPoint="0%,0%" EndPoint="100%,100%">
|
||||
<GradientStop Color="#12203C" Offset="0" />
|
||||
<GradientStop Color="#1A3057" Offset="0.55" />
|
||||
<GradientStop Color="#0E1A31" Offset="1" />
|
||||
</LinearGradientBrush>
|
||||
|
||||
<LinearGradientBrush x:Key="TitleBarBg" StartPoint="0%,0%" EndPoint="100%,100%">
|
||||
<GradientStop Color="#101C33" Offset="0" />
|
||||
<GradientStop Color="#0B1322" Offset="1" />
|
||||
</LinearGradientBrush>
|
||||
|
||||
<LinearGradientBrush x:Key="SideBgBrush" StartPoint="0%,0%" EndPoint="0%,100%">
|
||||
<GradientStop Color="#0E1729" Offset="0" />
|
||||
<GradientStop Color="#0A1120" Offset="1" />
|
||||
</LinearGradientBrush>
|
||||
</Styles.Resources>
|
||||
|
||||
<Style Selector="Window">
|
||||
<Setter Property="FontSize" Value="13" />
|
||||
<Setter Property="Foreground" Value="{DynamicResource Ink}" />
|
||||
</Style>
|
||||
|
||||
<!-- 文本 -->
|
||||
<Style Selector="TextBlock.h1">
|
||||
<Setter Property="FontSize" Value="26" />
|
||||
<Setter Property="FontWeight" Value="SemiBold" />
|
||||
<Setter Property="Foreground" Value="{DynamicResource Ink}" />
|
||||
</Style>
|
||||
<Style Selector="TextBlock.h2">
|
||||
<Setter Property="FontSize" Value="16" />
|
||||
<Setter Property="FontWeight" Value="SemiBold" />
|
||||
<Setter Property="Foreground" Value="{DynamicResource Ink}" />
|
||||
</Style>
|
||||
<Style Selector="TextBlock.h3">
|
||||
<Setter Property="FontSize" Value="13.5" />
|
||||
<Setter Property="FontWeight" Value="SemiBold" />
|
||||
<Setter Property="Foreground" Value="{DynamicResource Ink}" />
|
||||
</Style>
|
||||
<Style Selector="TextBlock.muted">
|
||||
<Setter Property="FontSize" Value="12" />
|
||||
<Setter Property="Foreground" Value="{DynamicResource InkDim}" />
|
||||
</Style>
|
||||
<Style Selector="TextBlock.faint">
|
||||
<Setter Property="FontSize" Value="11.5" />
|
||||
<Setter Property="Foreground" Value="{DynamicResource InkFaint}" />
|
||||
</Style>
|
||||
<Style Selector="TextBlock.eyebrow">
|
||||
<Setter Property="FontSize" Value="11" />
|
||||
<Setter Property="FontWeight" Value="SemiBold" />
|
||||
<Setter Property="Foreground" Value="{DynamicResource InkFaint}" />
|
||||
</Style>
|
||||
<Style Selector="TextBlock.onDark">
|
||||
<Setter Property="Foreground" Value="#EAF1FF" />
|
||||
</Style>
|
||||
<Style Selector="TextBlock.onDarkDim">
|
||||
<Setter Property="Foreground" Value="#9DB0D0" />
|
||||
</Style>
|
||||
|
||||
<!-- 容器 -->
|
||||
<!-- 容器:卡片悬停浮起,阴影与位移都有过渡 -->
|
||||
<Style Selector="Border.card">
|
||||
<Setter Property="Background" Value="{DynamicResource Surface}" />
|
||||
<Setter Property="BorderBrush" Value="{DynamicResource Line}" />
|
||||
<Setter Property="BorderThickness" Value="1" />
|
||||
<Setter Property="CornerRadius" Value="16" />
|
||||
<Setter Property="Transitions">
|
||||
<Transitions>
|
||||
<BoxShadowsTransition Property="BoxShadow" Duration="0:0:0.2" />
|
||||
<BrushTransition Property="BorderBrush" Duration="0:0:0.2" />
|
||||
<TransformOperationsTransition Property="RenderTransform" Duration="0:0:0.2" />
|
||||
</Transitions>
|
||||
</Setter>
|
||||
</Style>
|
||||
<Style Selector="Border.card:pointerover">
|
||||
<Setter Property="BoxShadow" Value="0 10 26 0 #1A213C70" />
|
||||
<Setter Property="BorderBrush" Value="{DynamicResource LineStrong}" />
|
||||
<Setter Property="RenderTransform" Value="translateY(-2px)" />
|
||||
</Style>
|
||||
<Style Selector="Border.panel">
|
||||
<Setter Property="Background" Value="{DynamicResource SurfaceAlt}" />
|
||||
<Setter Property="BorderBrush" Value="{DynamicResource Line}" />
|
||||
<Setter Property="BorderThickness" Value="1" />
|
||||
<Setter Property="CornerRadius" Value="12" />
|
||||
</Style>
|
||||
<Style Selector="Border.hero">
|
||||
<Setter Property="Background" Value="{DynamicResource HeroBg}" />
|
||||
<Setter Property="CornerRadius" Value="20" />
|
||||
<Setter Property="BoxShadow" Value="0 12 32 0 #1A0B1A3A" />
|
||||
</Style>
|
||||
<Style Selector="Border.chip">
|
||||
<Setter Property="Background" Value="{DynamicResource AccentSoft}" />
|
||||
<Setter Property="CornerRadius" Value="999" />
|
||||
<Setter Property="Padding" Value="8,2" />
|
||||
</Style>
|
||||
<Style Selector="Border.tag">
|
||||
<Setter Property="Background" Value="#F0F3FA" />
|
||||
<Setter Property="CornerRadius" Value="6" />
|
||||
<Setter Property="Padding" Value="7,2" />
|
||||
</Style>
|
||||
|
||||
<!-- ===================================================================
|
||||
按钮(重写版)
|
||||
原则:只通过 Button 自身的 Background/Foreground/BorderBrush + 伪类
|
||||
设置来换色,一律不覆盖 /template/ ContentPresenter 的属性,也不使用
|
||||
RenderTransform 动画。FluentTheme 的按钮模板通过 TemplateBinding 读取
|
||||
这些属性,混用「Button 属性」与「模板内部元素属性」会在 hover 状态
|
||||
切换时互相覆盖,造成光标移动时的渲染错乱。
|
||||
所有过渡都是纯画刷过渡(BrushTransition),类型固定,不会转换失败。
|
||||
=================================================================== -->
|
||||
<Style Selector="Button">
|
||||
<Setter Property="FontSize" Value="13" />
|
||||
<Setter Property="Padding" Value="14,7" />
|
||||
<Setter Property="MinHeight" Value="34" />
|
||||
<Setter Property="CornerRadius" Value="9" />
|
||||
<Setter Property="Background" Value="{DynamicResource Surface}" />
|
||||
<Setter Property="BorderBrush" Value="{DynamicResource LineStrong}" />
|
||||
<Setter Property="BorderThickness" Value="1" />
|
||||
<Setter Property="Foreground" Value="{DynamicResource Ink}" />
|
||||
<Setter Property="HorizontalContentAlignment" Value="Center" />
|
||||
<Setter Property="VerticalContentAlignment" Value="Center" />
|
||||
<Setter Property="Cursor" Value="Hand" />
|
||||
<Setter Property="Transitions">
|
||||
<Transitions>
|
||||
<BrushTransition Property="Background" Duration="0:0:0.13" />
|
||||
<BrushTransition Property="BorderBrush" Duration="0:0:0.13" />
|
||||
<BrushTransition Property="Foreground" Duration="0:0:0.13" />
|
||||
</Transitions>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<!-- 通用 hover / pressed(纯色,无变换) -->
|
||||
<Style Selector="Button:pointerover">
|
||||
<Setter Property="Background" Value="#EDF2FC" />
|
||||
<Setter Property="BorderBrush" Value="#BAC9E6" />
|
||||
</Style>
|
||||
<Style Selector="Button:pressed">
|
||||
<Setter Property="Background" Value="#DDE7F8" />
|
||||
<Setter Property="BorderBrush" Value="#9FB4DD" />
|
||||
</Style>
|
||||
|
||||
<!-- 主要按钮 -->
|
||||
<Style Selector="Button.primary">
|
||||
<Setter Property="Background" Value="{DynamicResource Accent}" />
|
||||
<Setter Property="BorderBrush" Value="{DynamicResource Accent}" />
|
||||
<Setter Property="Foreground" Value="White" />
|
||||
</Style>
|
||||
<Style Selector="Button.primary:pointerover">
|
||||
<Setter Property="Background" Value="{DynamicResource AccentDark}" />
|
||||
<Setter Property="BorderBrush" Value="{DynamicResource AccentDark}" />
|
||||
<Setter Property="Foreground" Value="White" />
|
||||
</Style>
|
||||
<Style Selector="Button.primary:pressed">
|
||||
<Setter Property="Background" Value="#183FA8" />
|
||||
<Setter Property="BorderBrush" Value="#183FA8" />
|
||||
<Setter Property="Foreground" Value="White" />
|
||||
</Style>
|
||||
|
||||
<!-- 幽灵按钮 -->
|
||||
<Style Selector="Button.ghost">
|
||||
<Setter Property="Background" Value="Transparent" />
|
||||
<Setter Property="BorderThickness" Value="0" />
|
||||
<Setter Property="BorderBrush" Value="Transparent" />
|
||||
<Setter Property="Foreground" Value="{DynamicResource InkDim}" />
|
||||
</Style>
|
||||
<Style Selector="Button.ghost:pointerover">
|
||||
<Setter Property="Background" Value="#EEF2FA" />
|
||||
<Setter Property="Foreground" Value="{DynamicResource Ink}" />
|
||||
</Style>
|
||||
<Style Selector="Button.ghost:pressed">
|
||||
<Setter Property="Background" Value="#E2E9F6" />
|
||||
</Style>
|
||||
|
||||
<!-- 危险按钮 -->
|
||||
<Style Selector="Button.danger">
|
||||
<Setter Property="Foreground" Value="{DynamicResource Danger}" />
|
||||
</Style>
|
||||
<Style Selector="Button.danger:pointerover">
|
||||
<Setter Property="Background" Value="#FDECEC" />
|
||||
<Setter Property="Foreground" Value="{DynamicResource Danger}" />
|
||||
</Style>
|
||||
<Style Selector="Button.danger:pressed">
|
||||
<Setter Property="Background" Value="#F8DADA" />
|
||||
</Style>
|
||||
|
||||
<!-- 深色背景上的按钮 -->
|
||||
<Style Selector="Button.onDark">
|
||||
<Setter Property="Background" Value="#1B2740" />
|
||||
<Setter Property="BorderBrush" Value="#2A3A57" />
|
||||
<Setter Property="Foreground" Value="#DCE7FA" />
|
||||
</Style>
|
||||
<Style Selector="Button.onDark:pointerover">
|
||||
<Setter Property="Background" Value="#233351" />
|
||||
<Setter Property="BorderBrush" Value="#3A4E75" />
|
||||
</Style>
|
||||
<Style Selector="Button.onDark:pressed">
|
||||
<Setter Property="Background" Value="#2B3D60" />
|
||||
</Style>
|
||||
<Style Selector="Button.onDark.active">
|
||||
<Setter Property="Background" Value="{DynamicResource Accent}" />
|
||||
<Setter Property="BorderBrush" Value="{DynamicResource Accent}" />
|
||||
<Setter Property="Foreground" Value="White" />
|
||||
</Style>
|
||||
|
||||
<Style Selector="Button.small">
|
||||
<Setter Property="FontSize" Value="12" />
|
||||
<Setter Property="Padding" Value="10,4" />
|
||||
<Setter Property="MinHeight" Value="28" />
|
||||
<Setter Property="CornerRadius" Value="8" />
|
||||
</Style>
|
||||
|
||||
<!-- 侧栏导航(主页 / 下载 / 设置) -->
|
||||
<Style Selector="Button.nav">
|
||||
<Setter Property="HorizontalAlignment" Value="Stretch" />
|
||||
<Setter Property="HorizontalContentAlignment" Value="Left" />
|
||||
<Setter Property="Background" Value="Transparent" />
|
||||
<Setter Property="BorderBrush" Value="Transparent" />
|
||||
<Setter Property="BorderThickness" Value="0" />
|
||||
<Setter Property="Foreground" Value="{DynamicResource SideInk}" />
|
||||
<Setter Property="Padding" Value="14,10" />
|
||||
<Setter Property="CornerRadius" Value="10" />
|
||||
<Setter Property="FontSize" Value="13.5" />
|
||||
<Setter Property="MinHeight" Value="40" />
|
||||
</Style>
|
||||
<Style Selector="Button.nav:pointerover">
|
||||
<Setter Property="Background" Value="#16213A" />
|
||||
<Setter Property="Foreground" Value="#E8EFFF" />
|
||||
</Style>
|
||||
<Style Selector="Button.nav:pressed">
|
||||
<Setter Property="Background" Value="#1E2C49" />
|
||||
</Style>
|
||||
<Style Selector="Button.nav.active">
|
||||
<Setter Property="Background" Value="#1C2C4C" />
|
||||
<Setter Property="Foreground" Value="#FFFFFF" />
|
||||
<Setter Property="BorderBrush" Value="{DynamicResource Accent}" />
|
||||
<Setter Property="BorderThickness" Value="3,0,0,0" />
|
||||
</Style>
|
||||
<Style Selector="Button.nav.active:pointerover">
|
||||
<Setter Property="Background" Value="#22355A" />
|
||||
<Setter Property="Foreground" Value="#FFFFFF" />
|
||||
</Style>
|
||||
|
||||
<!-- 输入 -->
|
||||
<Style Selector="TextBox">
|
||||
<Setter Property="CornerRadius" Value="9" />
|
||||
<Setter Property="Padding" Value="11,8" />
|
||||
<Setter Property="MinHeight" Value="36" />
|
||||
<Setter Property="FontSize" Value="12.5" />
|
||||
<Setter Property="Background" Value="{DynamicResource Surface}" />
|
||||
<Setter Property="BorderBrush" Value="{DynamicResource LineStrong}" />
|
||||
</Style>
|
||||
<Style Selector="ComboBox">
|
||||
<Setter Property="CornerRadius" Value="9" />
|
||||
<Setter Property="MinHeight" Value="34" />
|
||||
<Setter Property="FontSize" Value="12.5" />
|
||||
<Setter Property="Padding" Value="10,4" />
|
||||
</Style>
|
||||
<Style Selector="ProgressBar">
|
||||
<Setter Property="Height" Value="5" />
|
||||
<Setter Property="CornerRadius" Value="3" />
|
||||
<Setter Property="MinHeight" Value="5" />
|
||||
</Style>
|
||||
<Style Selector="CheckBox">
|
||||
<Setter Property="FontSize" Value="12.5" />
|
||||
</Style>
|
||||
|
||||
<!-- ===================================================================
|
||||
自建标题栏按钮(最小化 − / 关闭 ✕)
|
||||
同样只用纯画刷换色,绝不设置 RenderTransform;
|
||||
且用更高优先级覆盖上面通用的 :pointerover / :pressed,
|
||||
避免深色标题栏上出现浅色 hover 背景。
|
||||
=================================================================== -->
|
||||
<Style Selector="Button.titlebtn">
|
||||
<Setter Property="Width" Value="38" />
|
||||
<Setter Property="Height" Value="30" />
|
||||
<Setter Property="Background" Value="Transparent" />
|
||||
<Setter Property="Foreground" Value="#A9B8D4" />
|
||||
<Setter Property="BorderThickness" Value="0" />
|
||||
<Setter Property="BorderBrush" Value="Transparent" />
|
||||
<Setter Property="FontSize" Value="13" />
|
||||
<Setter Property="HorizontalContentAlignment" Value="Center" />
|
||||
<Setter Property="VerticalContentAlignment" Value="Center" />
|
||||
<Setter Property="CornerRadius" Value="7" />
|
||||
<Setter Property="Margin" Value="2,0" />
|
||||
</Style>
|
||||
<Style Selector="Button.titlebtn:pointerover">
|
||||
<Setter Property="Background" Value="#223252" />
|
||||
<Setter Property="BorderBrush" Value="Transparent" />
|
||||
<Setter Property="Foreground" Value="#FFFFFF" />
|
||||
</Style>
|
||||
<Style Selector="Button.titlebtn:pressed">
|
||||
<Setter Property="Background" Value="#2C4270" />
|
||||
<Setter Property="Foreground" Value="#FFFFFF" />
|
||||
</Style>
|
||||
<Style Selector="Button.titlebtn.close:pointerover">
|
||||
<Setter Property="Background" Value="#D64545" />
|
||||
<Setter Property="Foreground" Value="#FFFFFF" />
|
||||
</Style>
|
||||
<Style Selector="Button.titlebtn.close:pressed">
|
||||
<Setter Property="Background" Value="#B93737" />
|
||||
<Setter Property="Foreground" Value="#FFFFFF" />
|
||||
</Style>
|
||||
|
||||
</Styles>
|
||||
@@ -1,104 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Threading.Tasks;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using GC.Services;
|
||||
|
||||
namespace GC.ViewModels;
|
||||
|
||||
/// <summary>「关于」页面:版本号 + 开发者(读取仓库 contributors)。</summary>
|
||||
public partial class AboutViewModel : ObservableObject
|
||||
{
|
||||
private readonly AppServices _services;
|
||||
private bool _loaded;
|
||||
|
||||
public ObservableCollection<ContributorItem> Contributors { get; } = new();
|
||||
|
||||
[ObservableProperty] private bool _isLoading = true;
|
||||
[ObservableProperty] private string _statusText = "";
|
||||
[ObservableProperty] private bool _hasContributors;
|
||||
|
||||
public AboutViewModel(AppServices services)
|
||||
{
|
||||
_services = services;
|
||||
LoadCommand = new AsyncRelayCommand(() => LoadAsync(force: true));
|
||||
}
|
||||
|
||||
public string AppName => "Morris GC";
|
||||
|
||||
/// <summary>启动器版本号,如 v1.0.2。</summary>
|
||||
public string VersionText => "v" + LauncherRuntimeInfo.CurrentLauncherVersion;
|
||||
|
||||
/// <summary>当前平台标识,如 win-x64 / osx-arm64。</summary>
|
||||
public string PlatformText => LauncherRuntimeInfo.CurrentRid;
|
||||
|
||||
public string RepositoryText => _services.Settings.Current.UpdateRepository;
|
||||
|
||||
public string ContributorsTitle => "开发者";
|
||||
|
||||
public IAsyncRelayCommand LoadCommand { get; }
|
||||
|
||||
/// <summary>每次进入页面时调用(首次才真正联网拉取)。</summary>
|
||||
public void OnShown()
|
||||
{
|
||||
if (_loaded) return;
|
||||
_ = LoadAsync(force: false);
|
||||
}
|
||||
|
||||
private async Task LoadAsync(bool force)
|
||||
{
|
||||
if (_loaded && !force) return;
|
||||
_loaded = true;
|
||||
|
||||
IsLoading = true;
|
||||
StatusText = "正在读取贡献者…";
|
||||
try
|
||||
{
|
||||
var list = await ContributorsService.FetchAsync(_services.Settings.Current.UpdateRepository);
|
||||
Contributors.Clear();
|
||||
foreach (var c in list)
|
||||
Contributors.Add(new ContributorItem(c));
|
||||
|
||||
HasContributors = Contributors.Count > 0;
|
||||
StatusText = HasContributors ? $"{Contributors.Count} 位贡献者" : "暂无贡献者信息";
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
StatusText = "读取失败:" + ex.Message;
|
||||
}
|
||||
finally
|
||||
{
|
||||
IsLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private void OpenRepository() => Shell.OpenUrl(RepositoryText);
|
||||
|
||||
/// <summary>重新下载启动器:关闭所有窗口,进度窗下载新版,完成后重启。</summary>
|
||||
[RelayCommand]
|
||||
private async System.Threading.Tasks.Task ReinstallLauncher()
|
||||
{
|
||||
if (LauncherUpdateFlow.IsRunning) return;
|
||||
await LauncherUpdateFlow.RunAsync(_services, "正在重新下载启动器");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>一位贡献者的展示项。</summary>
|
||||
public sealed class ContributorItem
|
||||
{
|
||||
public ContributorItem(Contributor c)
|
||||
{
|
||||
Name = c.DisplayName;
|
||||
Contributions = c.Contributions;
|
||||
AvatarUrl = c.AvatarUrl;
|
||||
}
|
||||
|
||||
public string Name { get; }
|
||||
public int Contributions { get; }
|
||||
public string? AvatarUrl { get; }
|
||||
public string ContributionsText => $"{Contributions} 次提交";
|
||||
public bool HasAvatar => !string.IsNullOrWhiteSpace(AvatarUrl);
|
||||
}
|
||||
@@ -1,411 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Collections.Specialized;
|
||||
using System.ComponentModel;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Input;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using GC.Models;
|
||||
using GC.Services;
|
||||
|
||||
namespace GC.ViewModels;
|
||||
|
||||
public partial class DownloadViewModel : ObservableObject
|
||||
{
|
||||
private readonly AppServices _services;
|
||||
private readonly MainViewModel _main;
|
||||
private bool _initialized;
|
||||
// 每次切源取消上一次加载,并用 generation 序号丢弃过期结果,避免并发写 Models 集合
|
||||
private CancellationTokenSource? _loadCts;
|
||||
private int _loadGeneration;
|
||||
|
||||
public ObservableCollection<SourceItemViewModel> Sources { get; } = new();
|
||||
public ObservableCollection<RemoteModelRowViewModel> Models { get; } = new();
|
||||
public ObservableCollection<IDownloadJob> Jobs => _services.Downloads.Jobs;
|
||||
|
||||
[ObservableProperty] private SourceItemViewModel? _selectedSource;
|
||||
[ObservableProperty] private string _importUrl = "";
|
||||
[ObservableProperty] private bool _isBusy;
|
||||
[ObservableProperty] private string _statusMessage = "";
|
||||
[ObservableProperty] private bool _hasModels;
|
||||
[ObservableProperty] private bool _isBackgroundOpen = true;
|
||||
[ObservableProperty] private string _jobSummary = "";
|
||||
[ObservableProperty] private bool _hasJobs;
|
||||
[ObservableProperty] private bool _isSourceEmpty;
|
||||
|
||||
public DownloadViewModel(AppServices services, MainViewModel main)
|
||||
{
|
||||
_services = services;
|
||||
_main = main;
|
||||
Jobs.CollectionChanged += OnJobsChanged;
|
||||
foreach (var job in Jobs) job.PropertyChanged += OnJobPropertyChanged;
|
||||
L.I.LanguageChanged += RefreshLanguage;
|
||||
RebuildSources();
|
||||
UpdateJobState();
|
||||
}
|
||||
|
||||
public string BackgroundTitle => L.I["dl.background"];
|
||||
public string ImportHint => L.I["dl.hint"];
|
||||
|
||||
// ------------------------------------------------------------ 页面生命周期
|
||||
public void OnShown()
|
||||
{
|
||||
if (_initialized) return;
|
||||
_initialized = true;
|
||||
if (SelectedSource == null)
|
||||
SelectedSource = Sources.FirstOrDefault(s => s.Model.Enabled && !string.IsNullOrWhiteSpace(s.Model.Url))
|
||||
?? Sources.FirstOrDefault();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ 模型源
|
||||
private void RebuildSources()
|
||||
{
|
||||
var keepId = SelectedSource?.Model.Id;
|
||||
Sources.Clear();
|
||||
foreach (var source in _services.Settings.Current.Sources)
|
||||
Sources.Add(new SourceItemViewModel(source, this, _services));
|
||||
|
||||
SelectedSource = Sources.FirstOrDefault(s => s.Model.Id == keepId) ?? SelectedSource;
|
||||
}
|
||||
|
||||
partial void OnSelectedSourceChanged(SourceItemViewModel? value)
|
||||
{
|
||||
if (value == null) return;
|
||||
if (string.IsNullOrWhiteSpace(value.Model.Url))
|
||||
{
|
||||
Models.Clear();
|
||||
HasModels = false;
|
||||
IsSourceEmpty = true;
|
||||
StatusMessage = L.I["dl.pickSource"];
|
||||
return;
|
||||
}
|
||||
_ = LoadAsync(value, force: false);
|
||||
}
|
||||
|
||||
internal void OnSourceEnabledChanged(SourceItemViewModel source)
|
||||
{
|
||||
if (!source.Model.Enabled && SelectedSource == source) Models.Clear();
|
||||
}
|
||||
|
||||
internal void RemoveSource(SourceItemViewModel source)
|
||||
{
|
||||
if (source.Model.BuiltIn) return; // 内置默认源不允许删除
|
||||
_services.Settings.Current.Sources.Remove(source.Model);
|
||||
_services.Settings.Save();
|
||||
var wasSelected = SelectedSource == source;
|
||||
Sources.Remove(source);
|
||||
if (wasSelected)
|
||||
{
|
||||
SelectedSource = Sources.FirstOrDefault();
|
||||
if (SelectedSource == null)
|
||||
{
|
||||
Models.Clear();
|
||||
HasModels = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 只允许两个内置源(Xhmcl / GitCode),不再接受任意地址。
|
||||
/// 旧的「自定义源」入口统一改为:按测速结果切换到更快的那个源。
|
||||
/// </summary>
|
||||
[RelayCommand]
|
||||
private async Task ImportAsync()
|
||||
{
|
||||
var fastest = await _services.Selector.PickFastestAsync(force: true);
|
||||
var target = Sources.FirstOrDefault(x =>
|
||||
SourcePreset.Find(fastest.Id) != null &&
|
||||
SourcePreset.Detect(x.Model.Url).Id == fastest.Id);
|
||||
|
||||
if (target == null)
|
||||
{
|
||||
StatusMessage = "没有可用的下载源";
|
||||
return;
|
||||
}
|
||||
|
||||
SelectedSource = target;
|
||||
var lat = _services.Selector.LastLatency;
|
||||
StatusMessage = $"已切换到 {fastest.Name}" +
|
||||
(lat.Count > 0 ? "(" + string.Join(",", lat.Select(kv =>
|
||||
$"{SourcePreset.Find(kv.Key)?.Name ?? kv.Key} {kv.Value}ms")) + ")" : "");
|
||||
await LoadAsync(target, force: true);
|
||||
}
|
||||
|
||||
private static string DeriveName(string url)
|
||||
{
|
||||
var trimmed = url.TrimEnd('/', '\\');
|
||||
var slash = trimmed.LastIndexOfAny(new[] { '/', '\\' });
|
||||
var name = slash >= 0 ? trimmed[(slash + 1)..] : trimmed;
|
||||
if (name.EndsWith(".git", StringComparison.OrdinalIgnoreCase)) name = name[..^4];
|
||||
if (name.EndsWith(".zip", StringComparison.OrdinalIgnoreCase)) name = name[..^4];
|
||||
return string.IsNullOrWhiteSpace(name) ? url : name;
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private async Task RefreshAsync()
|
||||
{
|
||||
if (SelectedSource == null) return;
|
||||
await LoadAsync(SelectedSource, force: true);
|
||||
}
|
||||
|
||||
internal async Task RefreshFromSource(SourceItemViewModel source)
|
||||
{
|
||||
SelectedSource = source;
|
||||
await LoadAsync(source, force: true);
|
||||
}
|
||||
|
||||
private async Task LoadAsync(SourceItemViewModel source, bool force)
|
||||
{
|
||||
if (!source.Model.Enabled) return;
|
||||
|
||||
// 取消上一次尚未完成的加载,避免快速切换源时并发 Clear/写入同一集合
|
||||
_loadCts?.Cancel();
|
||||
_loadCts?.Dispose();
|
||||
_loadCts = new CancellationTokenSource();
|
||||
var ct = _loadCts.Token;
|
||||
var generation = ++_loadGeneration;
|
||||
|
||||
IsBusy = true;
|
||||
StatusMessage = L.I["dl.syncing"];
|
||||
try
|
||||
{
|
||||
// 第 6 项:下载页与启动更新用同一个源、同一种下载方式。
|
||||
// 每次加载前先让选择器给出最快源(有缓存,不会真的每次都测)。
|
||||
try
|
||||
{
|
||||
var fastest = await _services.Selector.PickFastestAsync(false, ct);
|
||||
if (fastest.Id != SourcePreset.Detect(source.Model.Url).Id)
|
||||
{
|
||||
var prefer = Sources.FirstOrDefault(x =>
|
||||
SourcePreset.Detect(x.Model.Url).Id == fastest.Id && x.Model.Enabled);
|
||||
if (prefer != null && prefer != source)
|
||||
{
|
||||
SelectedSource = prefer;
|
||||
source = prefer;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { /* 测速失败就沿用当前源 */ }
|
||||
|
||||
var index = await _services.Sources.FetchAsync(source.Model, force, null, ct);
|
||||
// 只有「仍是当前选中源 + 仍是最新一次加载」才可以写 UI 集合
|
||||
if (ct.IsCancellationRequested || generation != _loadGeneration || SelectedSource != source)
|
||||
return;
|
||||
|
||||
if (index.Error != null)
|
||||
{
|
||||
Models.Clear();
|
||||
HasModels = false;
|
||||
IsSourceEmpty = true;
|
||||
StatusMessage = DescribeError(index.Error);
|
||||
return;
|
||||
}
|
||||
|
||||
var installedIds = new HashSet<string>(
|
||||
_services.Models.Scan().Select(p => p.Id), StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
Models.Clear();
|
||||
foreach (var model in index.Models)
|
||||
{
|
||||
Models.Add(new RemoteModelRowViewModel(model, source,
|
||||
installedIds.Contains(model.Id), DownloadCommand));
|
||||
}
|
||||
|
||||
HasModels = Models.Count > 0;
|
||||
IsSourceEmpty = Models.Count == 0;
|
||||
StatusMessage = index.FromCache
|
||||
? $"{L.I.F("dl.ready", Models.Count)} · {L.I["dl.fromCache"]}"
|
||||
: L.I.F("dl.ready", Models.Count);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
// 被更新的加载取代或页面关闭:忽略,不覆盖新结果
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (!ct.IsCancellationRequested) StatusMessage = ex.Message;
|
||||
}
|
||||
finally
|
||||
{
|
||||
// 只有最后一次加载才复位 Busy,避免旧任务把新任务的忙碌状态清掉
|
||||
if (generation == _loadGeneration) IsBusy = false;
|
||||
}
|
||||
}
|
||||
|
||||
private static string DescribeError(string error)
|
||||
{
|
||||
if (error.StartsWith("dl.", StringComparison.Ordinal))
|
||||
{
|
||||
var text = L.I[error];
|
||||
return text == error ? error : text;
|
||||
}
|
||||
return error;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ 下载
|
||||
[RelayCommand]
|
||||
private async Task DownloadAsync(RemoteModelRowViewModel row)
|
||||
{
|
||||
if (row == null) return;
|
||||
row.RowOpacity = 0;
|
||||
row.RowHeight = 0;
|
||||
IsBackgroundOpen = true;
|
||||
|
||||
_services.Downloads.Enqueue(row.Model);
|
||||
|
||||
await Task.Delay(240);
|
||||
Models.Remove(row);
|
||||
HasModels = Models.Count > 0;
|
||||
IsSourceEmpty = Models.Count == 0;
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private void CancelJob(IDownloadJob? job)
|
||||
{
|
||||
if (job != null) _services.Downloads.Cancel(job);
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private void RetryJob(IDownloadJob? job)
|
||||
{
|
||||
if (job != null) _services.Downloads.Retry(job);
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private void RemoveJob(IDownloadJob? job)
|
||||
{
|
||||
if (job != null) _services.Downloads.Remove(job);
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private void ClearFinished() => _services.Downloads.ClearFinished();
|
||||
|
||||
[RelayCommand]
|
||||
private void ToggleBackground() => IsBackgroundOpen = !IsBackgroundOpen;
|
||||
|
||||
// ------------------------------------------------------------ 任务展示
|
||||
private void OnJobsChanged(object? sender, NotifyCollectionChangedEventArgs e)
|
||||
{
|
||||
if (e.NewItems != null)
|
||||
foreach (IDownloadJob job in e.NewItems) job.PropertyChanged += OnJobPropertyChanged;
|
||||
if (e.OldItems != null)
|
||||
foreach (IDownloadJob job in e.OldItems) job.PropertyChanged -= OnJobPropertyChanged;
|
||||
UpdateJobState();
|
||||
}
|
||||
|
||||
private void OnJobPropertyChanged(object? sender, PropertyChangedEventArgs e)
|
||||
{
|
||||
if (e.PropertyName == nameof(IDownloadJob.State))
|
||||
{
|
||||
if (sender is IDownloadJob { State: DownloadState.Completed })
|
||||
_services.Models.NotifyChanged();
|
||||
}
|
||||
UpdateJobState();
|
||||
}
|
||||
|
||||
private void UpdateJobState()
|
||||
{
|
||||
HasJobs = Jobs.Count > 0;
|
||||
JobSummary = $"{L.I["dl.background"]} ({Jobs.Count})";
|
||||
OnPropertyChanged(nameof(JobSummary));
|
||||
}
|
||||
|
||||
private void RefreshLanguage()
|
||||
{
|
||||
foreach (var source in Sources) source.RefreshLanguage();
|
||||
foreach (var model in Models) model.RefreshLanguage();
|
||||
foreach (var job in Jobs) job.RefreshText();
|
||||
OnPropertyChanged(nameof(BackgroundTitle));
|
||||
OnPropertyChanged(nameof(ImportHint));
|
||||
UpdateJobState();
|
||||
}
|
||||
}
|
||||
|
||||
public partial class SourceItemViewModel : ObservableObject
|
||||
{
|
||||
private readonly DownloadViewModel _owner;
|
||||
private readonly AppServices _services;
|
||||
|
||||
public ModelSource Model { get; }
|
||||
|
||||
public SourceItemViewModel(ModelSource model, DownloadViewModel owner, AppServices services)
|
||||
{
|
||||
Model = model;
|
||||
_owner = owner;
|
||||
_services = services;
|
||||
RemoveCommand = new RelayCommand(() => _owner.RemoveSource(this));
|
||||
RefreshCommand = new AsyncRelayCommand(async () => await _owner.RefreshFromSource(this));
|
||||
}
|
||||
|
||||
public string Name => string.IsNullOrWhiteSpace(Model.Name) ? Model.Id : Model.Name;
|
||||
public string HostText => string.IsNullOrWhiteSpace(Model.Url) ? L.I["dl.noSource"] : Model.DisplayHost;
|
||||
public bool HasUrl => !string.IsNullOrWhiteSpace(Model.Url);
|
||||
/// <summary>内置默认源不可删除(下载页隐藏删除按钮)。</summary>
|
||||
public bool CanRemove => !Model.BuiltIn;
|
||||
|
||||
public bool Enabled
|
||||
{
|
||||
get => Model.Enabled;
|
||||
set
|
||||
{
|
||||
if (Model.Enabled == value) return;
|
||||
Model.Enabled = value;
|
||||
_services.Settings.Save();
|
||||
OnPropertyChanged();
|
||||
_owner.OnSourceEnabledChanged(this);
|
||||
}
|
||||
}
|
||||
|
||||
public ICommand RemoveCommand { get; }
|
||||
public ICommand RefreshCommand { get; }
|
||||
|
||||
public void RefreshLanguage()
|
||||
{
|
||||
OnPropertyChanged(nameof(Name));
|
||||
OnPropertyChanged(nameof(HostText));
|
||||
}
|
||||
}
|
||||
|
||||
public partial class RemoteModelRowViewModel : ObservableObject
|
||||
{
|
||||
public RemoteModel Model { get; }
|
||||
public SourceItemViewModel Source { get; }
|
||||
|
||||
public RemoteModelRowViewModel(RemoteModel model, SourceItemViewModel source, bool installed, ICommand downloadCommand)
|
||||
{
|
||||
Model = model;
|
||||
Source = source;
|
||||
Installed = installed;
|
||||
DownloadCommand = downloadCommand;
|
||||
}
|
||||
|
||||
public string Name => Model.LocalizedName;
|
||||
public string Description => Model.LocalizedDescription;
|
||||
public string VersionText => "v" + Model.Manifest.Version;
|
||||
public string SizeText => ModelScanner.HumanSize(Model.SizeBytes);
|
||||
public string MetaText => $"{VersionText} · {SizeText}";
|
||||
public string TagsText => string.Join(" · ", Model.Manifest.Tags ?? new List<string>());
|
||||
public bool HasTags => !string.IsNullOrWhiteSpace(TagsText);
|
||||
|
||||
[ObservableProperty] private bool _installed;
|
||||
[ObservableProperty] private double _rowHeight = 92;
|
||||
[ObservableProperty] private double _rowOpacity = 1;
|
||||
|
||||
public string ButtonText => Installed ? L.I["dl.reinstall"] : L.I["dl.download"];
|
||||
public ICommand DownloadCommand { get; }
|
||||
|
||||
partial void OnInstalledChanged(bool value) => OnPropertyChanged(nameof(ButtonText));
|
||||
|
||||
public void RefreshLanguage()
|
||||
{
|
||||
OnPropertyChanged(nameof(Name));
|
||||
OnPropertyChanged(nameof(Description));
|
||||
OnPropertyChanged(nameof(MetaText));
|
||||
OnPropertyChanged(nameof(TagsText));
|
||||
OnPropertyChanged(nameof(ButtonText));
|
||||
}
|
||||
}
|
||||
@@ -1,148 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Input;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using GC.Models;
|
||||
using Avalonia.Media.Imaging;
|
||||
using GC.Services;
|
||||
|
||||
namespace GC.ViewModels;
|
||||
|
||||
public partial class HomeViewModel : ObservableObject
|
||||
{
|
||||
private readonly AppServices _services;
|
||||
private readonly MainViewModel _main;
|
||||
|
||||
public ObservableCollection<ModelCardViewModel> Models { get; } = new();
|
||||
|
||||
[ObservableProperty] private ModelCardViewModel? _selected;
|
||||
[ObservableProperty] private bool _isEmpty;
|
||||
|
||||
public string CountText => L.I.F("home.count", Models.Count);
|
||||
public string SourceCountText => _services.Settings.Current.Sources
|
||||
.Count(s => s.Enabled && !string.IsNullOrWhiteSpace(s.Url)).ToString();
|
||||
public string MemoryText => $"{_services.Memory.BudgetMb} MB";
|
||||
public string SelectedHint => Selected == null ? L.I["home.recent"] : L.I["home.launchHint"];
|
||||
|
||||
public HomeViewModel(AppServices services, MainViewModel main)
|
||||
{
|
||||
_services = services;
|
||||
_main = main;
|
||||
_services.Models.Changed += Refresh;
|
||||
L.I.LanguageChanged += RefreshLanguage;
|
||||
Refresh();
|
||||
}
|
||||
|
||||
public void Refresh()
|
||||
{
|
||||
var keepId = Selected?.Package.Id;
|
||||
Models.Clear();
|
||||
foreach (var package in _services.Models.Scan())
|
||||
Models.Add(new ModelCardViewModel(package, _services, this));
|
||||
|
||||
Selected = Models.FirstOrDefault(m => m.Package.Id == keepId) ?? Models.FirstOrDefault();
|
||||
IsEmpty = Models.Count == 0;
|
||||
RefreshLanguage();
|
||||
}
|
||||
|
||||
private void RefreshLanguage()
|
||||
{
|
||||
OnPropertyChanged(nameof(CountText));
|
||||
OnPropertyChanged(nameof(SourceCountText));
|
||||
OnPropertyChanged(nameof(MemoryText));
|
||||
OnPropertyChanged(nameof(SelectedHint));
|
||||
foreach (var model in Models) model.RefreshLanguage();
|
||||
}
|
||||
|
||||
public void LaunchModel(ModelCardViewModel card)
|
||||
{
|
||||
Selected = card;
|
||||
_main.PlayModel(card.Package);
|
||||
}
|
||||
|
||||
public async Task DeleteAsync(ModelCardViewModel card)
|
||||
{
|
||||
if (!await _main.ConfirmAsync(L.I.F("home.deleteConfirm", card.Name))) return;
|
||||
_services.Models.Delete(card.Package.Id);
|
||||
_services.Models.NotifyChanged();
|
||||
Refresh();
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private void Launch()
|
||||
{
|
||||
var card = Selected ?? Models.FirstOrDefault();
|
||||
if (card != null) _main.PlayModel(card.Package);
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private void OpenDownload() => _main.GoDownload();
|
||||
|
||||
[RelayCommand]
|
||||
private void OpenSettings() => _main.GoSettings();
|
||||
|
||||
[RelayCommand]
|
||||
private void OpenFolder() => Shell.OpenFolder(_services.Paths.ModelRoot);
|
||||
}
|
||||
|
||||
public partial class ModelCardViewModel : ObservableObject
|
||||
{
|
||||
private readonly AppServices _services;
|
||||
private Bitmap? _preview;
|
||||
|
||||
public ModelPackage Package { get; }
|
||||
|
||||
public ModelCardViewModel(ModelPackage package, AppServices services, HomeViewModel home)
|
||||
{
|
||||
Package = package;
|
||||
_services = services;
|
||||
LaunchCommand = new RelayCommand(() => home.LaunchModel(this));
|
||||
DeleteCommand = new AsyncRelayCommand(() => home.DeleteAsync(this));
|
||||
OpenFolderCommand = new RelayCommand(() => Shell.OpenFolder(package.Directory));
|
||||
}
|
||||
|
||||
public string Name => Package.LocalizedName;
|
||||
public string Description => Package.LocalizedDescription;
|
||||
public string VersionText => "v" + Package.Manifest.Version;
|
||||
public string SizeText => ModelScanner.HumanSize(Package.SizeBytes);
|
||||
public string MetaText => $"{VersionText} · {SizeText}";
|
||||
public string TagsText => string.Join(" · ", Package.Manifest.Tags ?? new());
|
||||
public bool HasTags => !string.IsNullOrWhiteSpace(TagsText);
|
||||
public string AuthorText => string.IsNullOrWhiteSpace(Package.Manifest.Author) ? "" : Package.Manifest.Author;
|
||||
|
||||
/// <summary>封面图来自模型包自带的 preview.png —— 启动器只显示,不渲染。</summary>
|
||||
public Bitmap? Preview
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_preview != null) return _preview;
|
||||
try
|
||||
{
|
||||
if (File.Exists(Package.PreviewPath)) _preview = new Bitmap(Package.PreviewPath);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"读取模型封面失败 {Package.Id}: {ex.Message}");
|
||||
}
|
||||
return _preview;
|
||||
}
|
||||
}
|
||||
|
||||
public bool HasPreview => Preview != null;
|
||||
|
||||
public ICommand LaunchCommand { get; }
|
||||
public ICommand DeleteCommand { get; }
|
||||
public ICommand OpenFolderCommand { get; }
|
||||
|
||||
public void RefreshLanguage()
|
||||
{
|
||||
OnPropertyChanged(nameof(Name));
|
||||
OnPropertyChanged(nameof(Description));
|
||||
OnPropertyChanged(nameof(MetaText));
|
||||
OnPropertyChanged(nameof(TagsText));
|
||||
}
|
||||
}
|
||||
@@ -1,221 +0,0 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using GC.Models;
|
||||
using GC.Services;
|
||||
|
||||
namespace GC.ViewModels;
|
||||
|
||||
public partial class MainViewModel : ObservableObject
|
||||
{
|
||||
private readonly AppServices _services;
|
||||
private bool _updateRunning;
|
||||
|
||||
public HomeViewModel Home { get; }
|
||||
public DownloadViewModel Download { get; }
|
||||
public SettingsViewModel Settings { get; }
|
||||
public AboutViewModel About { get; }
|
||||
|
||||
/// <summary>模型宿主:按清单加载模型自带的功能程序集。</summary>
|
||||
public ModelHost Models { get; }
|
||||
|
||||
[ObservableProperty] private ObservableObject _current = null!;
|
||||
[ObservableProperty] private bool _isHomeActive = true;
|
||||
[ObservableProperty] private bool _isDownloadActive;
|
||||
[ObservableProperty] private bool _isSettingsActive;
|
||||
[ObservableProperty] private bool _isAboutActive;
|
||||
|
||||
// 启动更新状态条
|
||||
[ObservableProperty] private bool _updateBarVisible;
|
||||
[ObservableProperty] private bool _updateBusy;
|
||||
[ObservableProperty] private double _updateProgress;
|
||||
[ObservableProperty] private string _updateStatus = "";
|
||||
[ObservableProperty] private string _updateDetail = "";
|
||||
[ObservableProperty] private string _launcherNotice = "";
|
||||
|
||||
/// <summary>由主窗口注入的确认对话框。</summary>
|
||||
public Func<string, Task<bool>>? ConfirmHandler { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 由主窗口注入的「发现启动器新版本」对话框。
|
||||
/// 参数为新版本号,返回 true 表示用户选择更新。
|
||||
/// </summary>
|
||||
public Func<string, Task<bool>>? LauncherUpdateHandler { get; set; }
|
||||
|
||||
public event Action<ModelPackage>? PlayerRequested;
|
||||
|
||||
public string VersionText => "v" + LauncherRuntimeInfo.CurrentLauncherVersion;
|
||||
public string PlatformText => LauncherRuntimeInfo.CurrentRid;
|
||||
|
||||
public MainViewModel(AppServices services)
|
||||
{
|
||||
_services = services;
|
||||
Models = services.ModelHost;
|
||||
Home = new HomeViewModel(services, this);
|
||||
Download = new DownloadViewModel(services, this);
|
||||
Settings = new SettingsViewModel(services);
|
||||
About = new AboutViewModel(services);
|
||||
Current = Home;
|
||||
}
|
||||
|
||||
partial void OnCurrentChanged(ObservableObject value)
|
||||
{
|
||||
IsHomeActive = value is HomeViewModel;
|
||||
IsDownloadActive = value is DownloadViewModel;
|
||||
IsSettingsActive = value is SettingsViewModel;
|
||||
IsAboutActive = value is AboutViewModel;
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
public void GoHome()
|
||||
{
|
||||
Home.Refresh();
|
||||
Current = Home;
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
public void GoDownload()
|
||||
{
|
||||
Current = Download;
|
||||
Download.OnShown();
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
public void GoSettings()
|
||||
{
|
||||
Settings.Refresh();
|
||||
Current = Settings;
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
public void GoAbout()
|
||||
{
|
||||
About.OnShown();
|
||||
Current = About;
|
||||
}
|
||||
|
||||
/// <summary>启动模型:交给模型自己的程序集,在独立窗口中运行。</summary>
|
||||
public void PlayModel(ModelPackage package)
|
||||
{
|
||||
_services.Memory.Refresh();
|
||||
PlayerRequested?.Invoke(package);
|
||||
}
|
||||
|
||||
public async Task<bool> ConfirmAsync(string message)
|
||||
=> ConfirmHandler == null || await ConfirmHandler(message);
|
||||
|
||||
// ---- 自动更新 ----------------------------------------------------------
|
||||
|
||||
/// <summary>启动后由 App 调用:后台检查更新,不阻塞主界面。</summary>
|
||||
public Task RunStartupUpdateAsync() => RunUpdateAsync(false);
|
||||
|
||||
/// <summary>状态条 / 设置页的「检查更新」,忽略自动开关强制检查。</summary>
|
||||
[RelayCommand]
|
||||
private Task CheckUpdate() => RunUpdateAsync(true);
|
||||
|
||||
private async Task RunUpdateAsync(bool force)
|
||||
{
|
||||
if (_updateRunning) return;
|
||||
_updateRunning = true;
|
||||
try
|
||||
{
|
||||
UpdateBarVisible = true;
|
||||
UpdateBusy = true;
|
||||
UpdateProgress = 0;
|
||||
UpdateStatus = L.I["update.checking"];
|
||||
UpdateDetail = "";
|
||||
LauncherNotice = "";
|
||||
|
||||
// 在 UI 线程构造,进度回调自动回到 UI 线程
|
||||
var progress = new Progress<UpdateProgress>(p =>
|
||||
{
|
||||
UpdateProgress = Math.Clamp(p.Value, 0, 1);
|
||||
UpdateStatus = p.Message;
|
||||
UpdateDetail = p.Detail ?? "";
|
||||
});
|
||||
|
||||
// 双源测速:Xhmcl / GitCode 取快的那个(第 5 项)。
|
||||
// 启动更新与下载页共用同一个选择器,保证两处用同一个源、同一种下载方式。
|
||||
UpdateStatus = "正在选择最快的下载源…";
|
||||
try
|
||||
{
|
||||
var fastest = await _services.Selector.PickFastestAsync(
|
||||
force, default);
|
||||
_services.Updates.UseRemote(_services.DownloadModule.CreateRemote(fastest));
|
||||
var lat = _services.Selector.LastLatency;
|
||||
UpdateDetail = "源:" + fastest.Name +
|
||||
(lat.Count > 0 ? "(" + string.Join(",", lat.Select(kv =>
|
||||
$"{SourcePreset.Find(kv.Key)?.Name ?? kv.Key} {kv.Value}ms")) + ")" : "");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"[update] 测速失败,沿用当前源: {ex.Message}");
|
||||
}
|
||||
|
||||
// 启动器:读 Release latest 版本号,与当前运行版本不同就弹窗询问
|
||||
var latest = await _services.LauncherUpdates.CheckAsync(_services.Updates.Remote);
|
||||
if (latest != null)
|
||||
{
|
||||
var agreed = LauncherUpdateHandler != null &&
|
||||
await LauncherUpdateHandler(latest);
|
||||
if (agreed)
|
||||
{
|
||||
// 走完整更新流程(关窗 -> 进度窗下载 -> 重启)
|
||||
UpdateBusy = false;
|
||||
_updateRunning = false;
|
||||
UpdateBarVisible = false;
|
||||
await LauncherUpdateFlow.RunAsync(_services, "正在更新启动器");
|
||||
return;
|
||||
}
|
||||
|
||||
UpdateStatus = $"启动器有新版本 v{latest}(已跳过)";
|
||||
UpdateDetail = "点击「检查更新」可再次更新,模型仍会同步到最新";
|
||||
}
|
||||
|
||||
// 模型:同步到最新版
|
||||
var result = await _services.Updates.RunAsync(force, progress, default);
|
||||
|
||||
UpdateStatus = result.Message;
|
||||
UpdateDetail = result.Error ?? "";
|
||||
LauncherNotice = result.LauncherMessage ?? "";
|
||||
|
||||
// 首次启动 + 断网:本地一个模型都没有,这时候不能只留一个空页面。
|
||||
// 明确告诉用户「没坏、可以怎么办」,并保留状态条(不自动隐藏)。
|
||||
if (result.Outcome == UpdateOutcome.Unavailable && Home.Models.Count == 0)
|
||||
{
|
||||
UpdateStatus = "暂时连不上模型源,模型库为空";
|
||||
UpdateDetail = "可以到「下载」页点重试,或把模型文件夹放进 .GC/model/ 后重新打开";
|
||||
return;
|
||||
}
|
||||
|
||||
// 模型下载完成后本次启动就刷新列表,立刻可用
|
||||
if (result.UpdatedModels > 0) Home.Refresh();
|
||||
|
||||
if ((result.Outcome == UpdateOutcome.NoChange || result.Outcome == UpdateOutcome.Applied) &&
|
||||
string.IsNullOrEmpty(LauncherNotice))
|
||||
_ = AutoHideAsync();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
UpdateStatus = L.I["update.offline"];
|
||||
UpdateDetail = ex.Message;
|
||||
}
|
||||
finally
|
||||
{
|
||||
UpdateBusy = false;
|
||||
_updateRunning = false;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task AutoHideAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
await Task.Delay(6000);
|
||||
if (!_updateRunning && string.IsNullOrEmpty(LauncherNotice)) UpdateBarVisible = false;
|
||||
}
|
||||
catch { /* 忽略 */ }
|
||||
}
|
||||
}
|
||||
@@ -1,217 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Linq;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Windows.Input;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using GC.Models;
|
||||
using GC.Services;
|
||||
|
||||
namespace GC.ViewModels;
|
||||
|
||||
public sealed class LanguageOption
|
||||
{
|
||||
public string Code { get; init; } = "auto";
|
||||
public string Label { get; set; } = "";
|
||||
public override string ToString() => Label;
|
||||
}
|
||||
|
||||
public partial class SettingsViewModel : ObservableObject
|
||||
{
|
||||
private readonly AppServices _services;
|
||||
private bool _loading = true;
|
||||
|
||||
public ObservableCollection<SettingsSourceViewModel> Sources { get; } = new();
|
||||
public ObservableCollection<LanguageOption> Languages { get; } = new();
|
||||
public int[] FrameRates { get; } = { 24, 30, 60, 90, 120 };
|
||||
|
||||
[ObservableProperty] private LanguageOption? _selectedLanguage;
|
||||
[ObservableProperty] private int _selectedFps = 120;
|
||||
[ObservableProperty] private double _memoryValue = 2048;
|
||||
[ObservableProperty] private bool _memoryAuto = true;
|
||||
[ObservableProperty] private string _statusMessage = "";
|
||||
[ObservableProperty] private bool _autoUpdate = true;
|
||||
|
||||
public string UpdateSourceText => _services.Updates.Remote.DisplayName;
|
||||
public string LastCheckText
|
||||
{
|
||||
get
|
||||
{
|
||||
var value = _services.Settings.Current.LastUpdateCheck;
|
||||
if (string.IsNullOrWhiteSpace(value)) return L.I["update.never"];
|
||||
return DateTimeOffset.TryParse(value, out var time)
|
||||
? time.ToLocalTime().ToString("yyyy-MM-dd HH:mm") : value!;
|
||||
}
|
||||
}
|
||||
public string PendingText => string.IsNullOrWhiteSpace(_services.Settings.Current.PendingLauncherVersion)
|
||||
? L.I["update.none"] : _services.Settings.Current.PendingLauncherVersion!;
|
||||
|
||||
public string MemoryValueText => MemoryAuto
|
||||
? $"{L.I["set.memory.auto"]} ({_services.Memory.BudgetMb} MB)"
|
||||
: $"{(int)Math.Round(MemoryValue)} MB";
|
||||
public string UsageText => _services.Memory.UsageText;
|
||||
public string ModelRoot => _services.Paths.ModelRoot;
|
||||
public string DataRoot => _services.Paths.DataRoot;
|
||||
public string PlatformText => $"{RuntimeInformation.OSDescription} · {RuntimeInformation.RuntimeIdentifier}";
|
||||
public string VersionText => "v1.0.0";
|
||||
public string MemoryHint => L.I["set.memory.hint"];
|
||||
|
||||
public SettingsViewModel(AppServices services)
|
||||
{
|
||||
_services = services;
|
||||
L.I.LanguageChanged += OnLanguageChanged;
|
||||
Refresh();
|
||||
_loading = false;
|
||||
}
|
||||
|
||||
public void Refresh()
|
||||
{
|
||||
_loading = true;
|
||||
BuildLanguages();
|
||||
var settings = _services.Settings.Current;
|
||||
SelectedFps = settings.RenderFps;
|
||||
MemoryValue = settings.MemoryMb;
|
||||
MemoryAuto = settings.MemoryAuto;
|
||||
AutoUpdate = settings.AutoUpdateOnStartup;
|
||||
|
||||
Sources.Clear();
|
||||
foreach (var source in settings.Sources)
|
||||
Sources.Add(new SettingsSourceViewModel(source, _services, this));
|
||||
|
||||
_loading = false;
|
||||
OnPropertyChanged(nameof(UsageText));
|
||||
OnPropertyChanged(nameof(MemoryValueText));
|
||||
OnPropertyChanged(nameof(MemoryHint));
|
||||
OnPropertyChanged(nameof(ModelRoot));
|
||||
OnPropertyChanged(nameof(DataRoot));
|
||||
OnPropertyChanged(nameof(UpdateSourceText));
|
||||
OnPropertyChanged(nameof(LastCheckText));
|
||||
OnPropertyChanged(nameof(PendingText));
|
||||
}
|
||||
|
||||
partial void OnAutoUpdateChanged(bool value)
|
||||
{
|
||||
if (_loading) return;
|
||||
_services.Settings.Apply(s => s.AutoUpdateOnStartup = value);
|
||||
}
|
||||
|
||||
private void BuildLanguages()
|
||||
{
|
||||
var current = _services.Settings.Current.Language;
|
||||
Languages.Clear();
|
||||
Languages.Add(new LanguageOption { Code = "auto", Label = L.I["set.language.auto"] });
|
||||
foreach (var (code, label) in L.Supported)
|
||||
Languages.Add(new LanguageOption { Code = code, Label = label });
|
||||
SelectedLanguage = Languages.FirstOrDefault(l => l.Code == current) ?? Languages[0];
|
||||
}
|
||||
|
||||
private void OnLanguageChanged()
|
||||
{
|
||||
_loading = true;
|
||||
BuildLanguages();
|
||||
_loading = false;
|
||||
Refresh();
|
||||
}
|
||||
|
||||
partial void OnSelectedLanguageChanged(LanguageOption? value)
|
||||
{
|
||||
if (_loading || value == null) return;
|
||||
_services.Settings.Apply(s => s.Language = value.Code);
|
||||
L.I.SetLanguage(value.Code);
|
||||
}
|
||||
|
||||
partial void OnSelectedFpsChanged(int value)
|
||||
{
|
||||
if (_loading) return;
|
||||
_services.Settings.Apply(s => s.RenderFps = Math.Clamp(value, 12, 120));
|
||||
}
|
||||
|
||||
partial void OnMemoryValueChanged(double value)
|
||||
{
|
||||
if (_loading) return;
|
||||
var mb = (int)Math.Round(value);
|
||||
_services.Settings.Apply(s => s.MemoryMb = mb);
|
||||
_services.Memory.Apply(mb);
|
||||
OnPropertyChanged(nameof(MemoryValueText));
|
||||
OnPropertyChanged(nameof(UsageText));
|
||||
}
|
||||
|
||||
partial void OnMemoryAutoChanged(bool value)
|
||||
{
|
||||
if (_loading) return;
|
||||
_services.Settings.Apply(s => s.MemoryAuto = value);
|
||||
_services.Memory.ApplyAuto(value, (int)Math.Round(MemoryValue));
|
||||
OnPropertyChanged(nameof(MemoryValueText));
|
||||
OnPropertyChanged(nameof(UsageText));
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private void OpenModelFolder() => Shell.OpenFolder(_services.Paths.ModelRoot);
|
||||
|
||||
[RelayCommand]
|
||||
private void OpenDataFolder() => Shell.OpenFolder(_services.Paths.DataRoot);
|
||||
|
||||
[RelayCommand]
|
||||
private void ClearCache()
|
||||
{
|
||||
// 模型数据由模型自己管理;这里只回收启动器侧托管内存
|
||||
System.GC.Collect();
|
||||
System.GC.WaitForPendingFinalizers();
|
||||
_services.Memory.Refresh();
|
||||
StatusMessage = L.I["set.cacheCleared"];
|
||||
OnPropertyChanged(nameof(UsageText));
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private void ApplyMemory()
|
||||
{
|
||||
_services.Memory.Apply((int)Math.Round(MemoryValue));
|
||||
StatusMessage = L.I["common.applied"];
|
||||
OnPropertyChanged(nameof(UsageText));
|
||||
}
|
||||
|
||||
internal void RemoveSource(SettingsSourceViewModel source)
|
||||
{
|
||||
if (source.Model.BuiltIn) return; // 内置默认源不允许删除
|
||||
_services.Settings.Current.Sources.Remove(source.Model);
|
||||
_services.Settings.Save();
|
||||
Sources.Remove(source);
|
||||
_services.Settings.Notify();
|
||||
}
|
||||
}
|
||||
|
||||
public partial class SettingsSourceViewModel : ObservableObject
|
||||
{
|
||||
private readonly AppServices _services;
|
||||
private readonly SettingsViewModel _owner;
|
||||
|
||||
public ModelSource Model { get; }
|
||||
|
||||
public SettingsSourceViewModel(ModelSource model, AppServices services, SettingsViewModel owner)
|
||||
{
|
||||
Model = model;
|
||||
_services = services;
|
||||
_owner = owner;
|
||||
RemoveCommand = new RelayCommand(() => _owner.RemoveSource(this));
|
||||
}
|
||||
|
||||
public string Name => string.IsNullOrWhiteSpace(Model.Name) ? Model.Id : Model.Name;
|
||||
public string UrlText => string.IsNullOrWhiteSpace(Model.Url) ? L.I["dl.noSource"] : Model.Url;
|
||||
/// <summary>内置默认源不可删除。</summary>
|
||||
public bool CanRemove => !Model.BuiltIn;
|
||||
|
||||
public bool Enabled
|
||||
{
|
||||
get => Model.Enabled;
|
||||
set
|
||||
{
|
||||
if (Model.Enabled == value) return;
|
||||
Model.Enabled = value;
|
||||
_services.Settings.Save();
|
||||
OnPropertyChanged();
|
||||
}
|
||||
}
|
||||
|
||||
public ICommand RemoveCommand { get; }
|
||||
}
|
||||
@@ -1,147 +0,0 @@
|
||||
<UserControl xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:loc="using:GC.Services"
|
||||
xmlns:vm="using:GC.ViewModels"
|
||||
x:Class="GC.Views.AboutView"
|
||||
x:DataType="vm:AboutViewModel">
|
||||
|
||||
<ScrollViewer>
|
||||
<StackPanel Margin="28,24" Spacing="16" MaxWidth="880" HorizontalAlignment="Left">
|
||||
|
||||
<StackPanel Spacing="4">
|
||||
<TextBlock Classes="h1" Text="关于" />
|
||||
<TextBlock Classes="muted" Text="版本信息与开发者" />
|
||||
</StackPanel>
|
||||
|
||||
<!-- 应用信息 -->
|
||||
<Border Classes="card" Padding="22,20">
|
||||
<Grid ColumnDefinitions="Auto,*">
|
||||
<Border Width="62" Height="62" CornerRadius="16" Background="#1C2C4C"
|
||||
VerticalAlignment="Top">
|
||||
<TextBlock Text="◎" FontSize="32" Foreground="#8FB6FF"
|
||||
HorizontalAlignment="Center" VerticalAlignment="Center" />
|
||||
</Border>
|
||||
|
||||
<StackPanel Grid.Column="1" Margin="18,0,0,0" Spacing="10">
|
||||
<StackPanel Spacing="2">
|
||||
<TextBlock Text="{Binding AppName}" FontSize="19" FontWeight="SemiBold" />
|
||||
<TextBlock Classes="faint" Text="{Binding PlatformText}" />
|
||||
</StackPanel>
|
||||
|
||||
<Grid ColumnDefinitions="96,*" RowDefinitions="Auto,Auto,Auto">
|
||||
<TextBlock Classes="h3" Text="版本" />
|
||||
<TextBlock Grid.Column="1" Classes="muted" Text="{Binding VersionText}"
|
||||
FontWeight="SemiBold" />
|
||||
|
||||
<TextBlock Grid.Row="1" Classes="h3" Text="仓库" Margin="0,8,0,0" />
|
||||
<Button Grid.Row="1" Grid.Column="1" Classes="ghost small" Margin="0,6,0,0"
|
||||
HorizontalAlignment="Left" Padding="0"
|
||||
Command="{Binding OpenRepositoryCommand}"
|
||||
Content="{Binding RepositoryText}" />
|
||||
|
||||
<TextBlock Grid.Row="2" Classes="h3" Text="Git 服务" Margin="0,8,0,0" />
|
||||
<TextBlock Grid.Row="2" Grid.Column="1" Classes="muted" Text="itxiaohui"
|
||||
FontWeight="SemiBold" Margin="0,8,0,0" />
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- 维护 -->
|
||||
<Border Classes="card" Padding="22,20">
|
||||
<StackPanel Spacing="12">
|
||||
<TextBlock Classes="h2" Text="启动器维护" />
|
||||
<TextBlock Classes="muted" TextWrapping="Wrap"
|
||||
Text="重新下载会关闭所有窗口,显示下载进度,完成后自动启动新版本并删除旧版本。" />
|
||||
<Button Classes="primary" Content="重新下载启动器"
|
||||
HorizontalAlignment="Left" Padding="18,8"
|
||||
Command="{Binding ReinstallLauncherCommand}" />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<!-- 感谢(样式抄「开发者」卡片,内容写死,不读取数据) -->
|
||||
<Border Classes="card" Padding="22,20">
|
||||
<StackPanel Spacing="14">
|
||||
<TextBlock Classes="h2" Text="感谢" />
|
||||
|
||||
<StackPanel Orientation="Horizontal" Spacing="10">
|
||||
<Border Background="{DynamicResource SurfaceAlt}"
|
||||
BorderBrush="{DynamicResource Line}" BorderThickness="1"
|
||||
CornerRadius="12" Padding="12,10" MinWidth="190">
|
||||
<StackPanel Orientation="Horizontal" Spacing="10">
|
||||
<Border Width="34" Height="34" CornerRadius="17"
|
||||
Background="{DynamicResource AccentSoft}">
|
||||
<TextBlock Text="◉" FontSize="15" Foreground="{DynamicResource Accent}"
|
||||
HorizontalAlignment="Center" VerticalAlignment="Center" />
|
||||
</Border>
|
||||
<StackPanel VerticalAlignment="Center" Spacing="1">
|
||||
<TextBlock Text="地理洪老师" FontSize="12.5" FontWeight="SemiBold" />
|
||||
<TextBlock Classes="faint" Text="地理学科内容指导" />
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<Border Background="{DynamicResource SurfaceAlt}"
|
||||
BorderBrush="{DynamicResource Line}" BorderThickness="1"
|
||||
CornerRadius="12" Padding="12,10" MinWidth="190">
|
||||
<StackPanel Orientation="Horizontal" Spacing="10">
|
||||
<Border Width="34" Height="34" CornerRadius="17"
|
||||
Background="{DynamicResource AccentSoft}">
|
||||
<TextBlock Text="◉" FontSize="15" Foreground="{DynamicResource Accent}"
|
||||
HorizontalAlignment="Center" VerticalAlignment="Center" />
|
||||
</Border>
|
||||
<StackPanel VerticalAlignment="Center" Spacing="1">
|
||||
<TextBlock Text="itxiaohui" FontSize="12.5" FontWeight="SemiBold" />
|
||||
<TextBlock Classes="faint" Text="Git 服务与部署支持" />
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<!-- 开发者 -->
|
||||
<Border Classes="card" Padding="22,20">
|
||||
<StackPanel Spacing="14">
|
||||
<Grid ColumnDefinitions="*,Auto">
|
||||
<TextBlock Classes="h2" Text="{Binding ContributorsTitle}" />
|
||||
<Button Grid.Column="1" Classes="ghost small" Content="刷新"
|
||||
Command="{Binding LoadCommand}" IsEnabled="{Binding !IsLoading}" />
|
||||
</Grid>
|
||||
|
||||
<TextBlock Classes="faint" Text="{Binding StatusText}" />
|
||||
|
||||
<ProgressBar IsIndeterminate="True" Height="3" IsVisible="{Binding IsLoading}" />
|
||||
|
||||
<ItemsControl ItemsSource="{Binding Contributors}" IsVisible="{Binding HasContributors}">
|
||||
<ItemsControl.ItemsPanel>
|
||||
<ItemsPanelTemplate>
|
||||
<WrapPanel Orientation="Horizontal" />
|
||||
</ItemsPanelTemplate>
|
||||
</ItemsControl.ItemsPanel>
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<Border Background="{DynamicResource SurfaceAlt}"
|
||||
BorderBrush="{DynamicResource Line}" BorderThickness="1"
|
||||
CornerRadius="12" Padding="12,10" Margin="0,0,10,10" MinWidth="190">
|
||||
<StackPanel Orientation="Horizontal" Spacing="10">
|
||||
<Border Width="34" Height="34" CornerRadius="17"
|
||||
Background="{DynamicResource AccentSoft}">
|
||||
<TextBlock Text="◉" FontSize="15" Foreground="{DynamicResource Accent}"
|
||||
HorizontalAlignment="Center" VerticalAlignment="Center" />
|
||||
</Border>
|
||||
<StackPanel VerticalAlignment="Center" Spacing="1">
|
||||
<TextBlock Text="{Binding Name}" FontSize="12.5" FontWeight="SemiBold" />
|
||||
<TextBlock Classes="faint" Text="{Binding ContributionsText}" />
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
</StackPanel>
|
||||
</ScrollViewer>
|
||||
</UserControl>
|
||||
@@ -1,11 +0,0 @@
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Markup.Xaml;
|
||||
|
||||
namespace GC.Views;
|
||||
|
||||
public partial class AboutView : UserControl
|
||||
{
|
||||
public AboutView() => InitializeComponent();
|
||||
|
||||
private void InitializeComponent() => AvaloniaXamlLoader.Load(this);
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
<Window xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:loc="using:GC.Services"
|
||||
x:Class="GC.Views.ConfirmWindow"
|
||||
Title="{loc:Loc app.name}"
|
||||
Width="440" SizeToContent="Height"
|
||||
CanResize="False" ShowInTaskbar="False"
|
||||
WindowStartupLocation="CenterOwner"
|
||||
Background="Transparent"
|
||||
SystemDecorations="None"
|
||||
TransparencyLevelHint="Transparent">
|
||||
|
||||
<StackPanel Margin="24,20,24,20" Spacing="14">
|
||||
<TextBlock x:Name="TitleText" Classes="h2" Text="{loc:Loc common.confirmTitle}" />
|
||||
<TextBlock x:Name="MessageText" Classes="muted" TextWrapping="Wrap" />
|
||||
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Spacing="8" Margin="0,6,0,0">
|
||||
<Button x:Name="CancelButton" Content="{loc:Loc common.cancel}" Click="OnCancel" />
|
||||
<Button x:Name="ConfirmButton" Classes="primary" Content="{loc:Loc common.confirm}" Click="OnConfirm" />
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</Window>
|
||||
@@ -1,66 +0,0 @@
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Interactivity;
|
||||
using Avalonia.Markup.Xaml;
|
||||
using Avalonia.Media;
|
||||
|
||||
namespace GC.Views;
|
||||
|
||||
public partial class ConfirmWindow : Window
|
||||
{
|
||||
public ConfirmWindow() : this("") { }
|
||||
|
||||
public ConfirmWindow(string message) : this(null, message, null, null) { }
|
||||
|
||||
/// <summary>
|
||||
/// 可定制标题与按钮文案的确认窗。
|
||||
/// </summary>
|
||||
public ConfirmWindow(string? title, string message, string? confirmText, string? cancelText)
|
||||
{
|
||||
AvaloniaXamlLoader.Load(this);
|
||||
|
||||
TransparencyLevelHint = new[] { WindowTransparencyLevel.Transparent };
|
||||
Background = Brushes.Transparent;
|
||||
if (this.Content is Control content)
|
||||
{
|
||||
// 先把 content 从 Window 上摘下来,否则再赋给 Border.Child 会抛
|
||||
// "The Control already has a parent."
|
||||
this.Content = null;
|
||||
this.Content = new Border
|
||||
{
|
||||
CornerRadius = new CornerRadius(14),
|
||||
BorderBrush = (this.FindResource("Line") as IBrush) ?? Brushes.Gray,
|
||||
BorderThickness = new Thickness(1),
|
||||
Background = (this.FindResource("Surface") as IBrush) ?? Brushes.White,
|
||||
ClipToBounds = true,
|
||||
Child = content
|
||||
};
|
||||
}
|
||||
|
||||
var text = this.FindControl<TextBlock>("MessageText");
|
||||
if (text != null) text.Text = message;
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(title))
|
||||
{
|
||||
var titleBlock = this.FindControl<TextBlock>("TitleText");
|
||||
if (titleBlock != null) titleBlock.Text = title;
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(confirmText))
|
||||
{
|
||||
var ok = this.FindControl<Button>("ConfirmButton");
|
||||
if (ok != null) ok.Content = confirmText;
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(cancelText))
|
||||
{
|
||||
// 取消按钮是第一个("取消"),这里按名查找更稳
|
||||
var cancel = this.FindControl<Button>("CancelButton");
|
||||
if (cancel != null) cancel.Content = cancelText;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnCancel(object? sender, RoutedEventArgs e) => Close(false);
|
||||
|
||||
private void OnConfirm(object? sender, RoutedEventArgs e) => Close(true);
|
||||
}
|
||||
@@ -1,154 +0,0 @@
|
||||
<UserControl xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:loc="using:GC.Services"
|
||||
x:Class="GC.Views.DownloadView">
|
||||
|
||||
<Grid ColumnDefinitions="316,*" Margin="24,22,24,24">
|
||||
|
||||
<!-- 模型源 -->
|
||||
<Border Grid.Column="0" Classes="card" Padding="18" Margin="0,0,16,0">
|
||||
<Grid RowDefinitions="Auto,Auto,Auto,*,Auto">
|
||||
|
||||
<TextBlock Classes="h2" Text="{loc:Loc dl.sources}" />
|
||||
|
||||
<!-- 只允许 Xhmcl / GitCode 两个内置源;这里是对比测速并自动切换 -->
|
||||
<StackPanel Grid.Row="1" Margin="0,12,0,0" Spacing="8">
|
||||
<Button Classes="primary" Content="测速并切换到最快源"
|
||||
Command="{Binding ImportCommand}" HorizontalAlignment="Stretch" />
|
||||
</StackPanel>
|
||||
|
||||
<TextBlock Grid.Row="2" Classes="faint" Text="{loc:Loc dl.hint}"
|
||||
TextWrapping="Wrap" Margin="0,9,0,12" />
|
||||
|
||||
<ScrollViewer Grid.Row="3" VerticalScrollBarVisibility="Auto">
|
||||
<ListBox ItemsSource="{Binding Sources}" SelectedItem="{Binding SelectedSource}"
|
||||
Background="Transparent" BorderThickness="0" Padding="0">
|
||||
<ListBox.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<Grid ColumnDefinitions="*,Auto" Margin="0,3">
|
||||
<StackPanel Spacing="2" VerticalAlignment="Center">
|
||||
<TextBlock Text="{Binding Name}" FontSize="12.5" FontWeight="SemiBold"
|
||||
TextTrimming="CharacterEllipsis" />
|
||||
<TextBlock Text="{Binding HostText}" Classes="faint" TextTrimming="CharacterEllipsis" />
|
||||
</StackPanel>
|
||||
|
||||
</Grid>
|
||||
</DataTemplate>
|
||||
</ListBox.ItemTemplate>
|
||||
</ListBox>
|
||||
</ScrollViewer>
|
||||
|
||||
<Border Grid.Row="4" Classes="panel" Padding="12,9" Margin="0,10,0,0">
|
||||
<StackPanel Spacing="3">
|
||||
<TextBlock Classes="eyebrow" Text="{loc:Loc dl.available}" />
|
||||
<TextBlock Classes="faint" Text="{Binding StatusMessage}" TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- 可用模型 + 后台任务 -->
|
||||
<Border Grid.Column="1" Classes="card" Padding="20">
|
||||
<Grid RowDefinitions="Auto,*,Auto">
|
||||
|
||||
<Grid ColumnDefinitions="*,Auto,Auto">
|
||||
<StackPanel>
|
||||
<TextBlock Classes="h2" Text="{loc:Loc dl.available}" />
|
||||
<TextBlock Classes="muted" Text="{Binding StatusMessage}" Margin="0,3,0,0" />
|
||||
</StackPanel>
|
||||
<ProgressBar Grid.Column="1" IsIndeterminate="True" Width="90" Height="4"
|
||||
IsVisible="{Binding IsBusy}" VerticalAlignment="Center" Margin="12,0" />
|
||||
<Button Grid.Column="2" Classes="small" Content="{loc:Loc dl.refresh}"
|
||||
Command="{Binding RefreshCommand}" VerticalAlignment="Center" />
|
||||
</Grid>
|
||||
|
||||
<ScrollViewer Grid.Row="1" Margin="0,14,0,0" VerticalScrollBarVisibility="Auto">
|
||||
<ItemsControl ItemsSource="{Binding Models}">
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<Border Height="{Binding RowHeight}" Opacity="{Binding RowOpacity}"
|
||||
ClipToBounds="True" Margin="0,0,0,10">
|
||||
<Border.Transitions>
|
||||
<Transitions>
|
||||
<DoubleTransition Property="Height" Duration="0:0:0.24" Easing="CubicEaseOut" />
|
||||
<DoubleTransition Property="Opacity" Duration="0:0:0.18" />
|
||||
</Transitions>
|
||||
</Border.Transitions>
|
||||
|
||||
<Border Classes="panel" Padding="14,11">
|
||||
<Grid ColumnDefinitions="*,Auto">
|
||||
<StackPanel Spacing="3" VerticalAlignment="Center">
|
||||
<StackPanel Orientation="Horizontal" Spacing="8">
|
||||
<TextBlock Text="{Binding Name}" FontSize="13" FontWeight="SemiBold" />
|
||||
<Border Classes="tag" VerticalAlignment="Center">
|
||||
<TextBlock Text="{Binding VersionText}" Classes="faint" />
|
||||
</Border>
|
||||
<TextBlock Text="{Binding SizeText}" Classes="faint" VerticalAlignment="Center" />
|
||||
</StackPanel>
|
||||
<TextBlock Text="{Binding Description}" Classes="muted"
|
||||
MaxLines="1" TextTrimming="CharacterEllipsis" MaxWidth="520" />
|
||||
<TextBlock Text="{Binding TagsText}" Classes="faint" IsVisible="{Binding HasTags}" />
|
||||
</StackPanel>
|
||||
<Button Grid.Column="1" Classes="primary small" Content="{Binding ButtonText}"
|
||||
Command="{Binding DownloadCommand}" CommandParameter="{Binding}"
|
||||
VerticalAlignment="Center" Margin="12,0,0,0" />
|
||||
</Grid>
|
||||
</Border>
|
||||
</Border>
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
</ScrollViewer>
|
||||
|
||||
<!-- 后台任务(下载时折叠到这里) -->
|
||||
<Border Grid.Row="2" Classes="panel" Margin="0,12,0,0" Padding="6" IsVisible="{Binding HasJobs}">
|
||||
<StackPanel>
|
||||
<Grid ColumnDefinitions="*,Auto">
|
||||
<Button Classes="ghost" Content="{Binding JobSummary}" Command="{Binding ToggleBackgroundCommand}"
|
||||
HorizontalContentAlignment="Left" FontSize="12" FontWeight="SemiBold" Padding="10,7" />
|
||||
<Button Grid.Column="1" Classes="ghost small" Content="{loc:Loc dl.clearDone}"
|
||||
Command="{Binding ClearFinishedCommand}" VerticalAlignment="Center" Margin="0,0,6,0" />
|
||||
</Grid>
|
||||
|
||||
<ScrollViewer MaxHeight="200" IsVisible="{Binding IsBackgroundOpen}">
|
||||
<ItemsControl ItemsSource="{Binding Jobs}" Margin="6,0,6,6">
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<Border Background="{DynamicResource Surface}" CornerRadius="9" Padding="10,8" Margin="0,4,0,0">
|
||||
<Grid ColumnDefinitions="*,Auto">
|
||||
<StackPanel Spacing="4">
|
||||
<Grid ColumnDefinitions="*,Auto">
|
||||
<TextBlock Text="{Binding Name}" FontSize="12" FontWeight="SemiBold" />
|
||||
<TextBlock Grid.Column="1" Text="{Binding StatusText}" Classes="faint" />
|
||||
</Grid>
|
||||
<ProgressBar Value="{Binding Progress}" Maximum="1" IsVisible="{Binding IsActive}" />
|
||||
<TextBlock Text="{Binding DetailText}" Classes="faint" TextTrimming="CharacterEllipsis" />
|
||||
</StackPanel>
|
||||
<StackPanel Grid.Column="1" Orientation="Horizontal" Spacing="2"
|
||||
VerticalAlignment="Center" Margin="10,0,0,0">
|
||||
<Button Classes="ghost small" Content="{loc:Loc dl.cancel}"
|
||||
IsVisible="{Binding IsActive}"
|
||||
Command="{Binding $parent[ItemsControl].DataContext.CancelJobCommand}"
|
||||
CommandParameter="{Binding}" />
|
||||
<Button Classes="ghost small" Content="{loc:Loc dl.retry}"
|
||||
IsVisible="{Binding CanRetry}"
|
||||
Command="{Binding $parent[ItemsControl].DataContext.RetryJobCommand}"
|
||||
CommandParameter="{Binding}" />
|
||||
<Button Classes="ghost small" Content="{loc:Loc dl.removeTask}"
|
||||
Command="{Binding $parent[ItemsControl].DataContext.RemoveJobCommand}"
|
||||
CommandParameter="{Binding}" />
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</Border>
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
</ScrollViewer>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
</Grid>
|
||||
</Border>
|
||||
</Grid>
|
||||
</UserControl>
|
||||
@@ -1,9 +0,0 @@
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Markup.Xaml;
|
||||
|
||||
namespace GC.Views;
|
||||
|
||||
public partial class DownloadView : UserControl
|
||||
{
|
||||
public DownloadView() => AvaloniaXamlLoader.Load(this);
|
||||
}
|
||||
@@ -1,111 +0,0 @@
|
||||
<UserControl xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:loc="using:GC.Services"
|
||||
xmlns:controls="using:GC.Controls"
|
||||
x:Class="GC.Views.HomeView">
|
||||
|
||||
<ScrollViewer VerticalScrollBarVisibility="Auto">
|
||||
<StackPanel Margin="26,24,26,28" Spacing="18">
|
||||
|
||||
<!-- 主视觉 -->
|
||||
<Border Classes="hero" Padding="26,24">
|
||||
<Grid ColumnDefinitions="*,Auto">
|
||||
|
||||
<StackPanel Spacing="9" MaxWidth="560">
|
||||
<TextBlock Classes="h1 onDark" Text="{loc:Loc home.title}" />
|
||||
<TextBlock Text="{loc:Loc home.subtitle}" Foreground="#A9BEDF" FontSize="12.5"
|
||||
TextWrapping="Wrap" MaxWidth="500" />
|
||||
<StackPanel Orientation="Horizontal" Spacing="10" Margin="0,12,0,0">
|
||||
<Button Classes="primary" Content="{loc:Loc home.launch}" Command="{Binding LaunchCommand}" />
|
||||
<Button Classes="onDark" Content="{loc:Loc home.download}" Command="{Binding OpenDownloadCommand}" />
|
||||
<Button Classes="onDark" Content="{loc:Loc home.settings}" Command="{Binding OpenSettingsCommand}" />
|
||||
</StackPanel>
|
||||
<TextBlock Text="{Binding SelectedHint}" Foreground="#7E93B8" FontSize="11" Margin="2,2,0,0" />
|
||||
</StackPanel>
|
||||
|
||||
<StackPanel Grid.Column="1" Orientation="Horizontal" Spacing="10" VerticalAlignment="Center">
|
||||
<Border Background="#16233C" CornerRadius="14" Padding="16,12" Width="96">
|
||||
<StackPanel Spacing="2">
|
||||
<TextBlock Text="{Binding Models.Count}" Foreground="#FFFFFF" FontSize="22" FontWeight="SemiBold" />
|
||||
<TextBlock Text="{loc:Loc home.stats.models}" Foreground="#7E93B8" FontSize="10.5" />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
<Border Background="#16233C" CornerRadius="14" Padding="16,12" Width="96">
|
||||
<StackPanel Spacing="2">
|
||||
<TextBlock Text="{Binding SourceCountText}" Foreground="#FFFFFF" FontSize="22" FontWeight="SemiBold" />
|
||||
<TextBlock Text="{loc:Loc home.stats.sources}" Foreground="#7E93B8" FontSize="10.5" />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
<Border Background="#16233C" CornerRadius="14" Padding="16,12" Width="112">
|
||||
<StackPanel Spacing="2">
|
||||
<TextBlock Text="{Binding MemoryText}" Foreground="#FFFFFF" FontSize="16" FontWeight="SemiBold" />
|
||||
<TextBlock Text="{loc:Loc home.stats.memory}" Foreground="#7E93B8" FontSize="10.5" />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
</StackPanel>
|
||||
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- 列表标题 -->
|
||||
<Grid ColumnDefinitions="*,Auto" Margin="2,4,2,0">
|
||||
<TextBlock Classes="h2" Text="{loc:Loc home.installed}" />
|
||||
<TextBlock Grid.Column="1" Classes="muted" Text="{Binding CountText}" VerticalAlignment="Center" />
|
||||
</Grid>
|
||||
|
||||
<!-- 模型卡片 -->
|
||||
<ItemsControl ItemsSource="{Binding Models}" IsVisible="{Binding !IsEmpty}">
|
||||
<ItemsControl.ItemsPanel>
|
||||
<ItemsPanelTemplate>
|
||||
<WrapPanel Orientation="Horizontal" />
|
||||
</ItemsPanelTemplate>
|
||||
</ItemsControl.ItemsPanel>
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<Border Classes="card" Width="336" Margin="0,0,16,16" ClipToBounds="True">
|
||||
<StackPanel>
|
||||
<Border Height="138" Background="#0B1226" ClipToBounds="True">
|
||||
<Panel>
|
||||
<TextBlock Text="◎" FontSize="34" Foreground="#1B2A47"
|
||||
HorizontalAlignment="Center" VerticalAlignment="Center" />
|
||||
<Image Source="{Binding Preview}" Stretch="UniformToFill" />
|
||||
</Panel>
|
||||
</Border>
|
||||
<StackPanel Margin="16,13,16,15" Spacing="7">
|
||||
<Grid ColumnDefinitions="*,Auto">
|
||||
<TextBlock Classes="h3" Text="{Binding Name}" TextTrimming="CharacterEllipsis" />
|
||||
<TextBlock Grid.Column="1" Classes="faint" Text="{Binding MetaText}"
|
||||
VerticalAlignment="Center" Margin="8,0,0,0" />
|
||||
</Grid>
|
||||
<TextBlock Classes="muted" Text="{Binding Description}" TextWrapping="Wrap"
|
||||
MaxLines="2" Height="32" TextTrimming="CharacterEllipsis" />
|
||||
<TextBlock Classes="faint" Text="{Binding TagsText}" IsVisible="{Binding HasTags}" />
|
||||
<Grid ColumnDefinitions="Auto,*,Auto,Auto" Margin="0,6,0,0">
|
||||
<Button Classes="primary small" Content="{loc:Loc home.launch}"
|
||||
Command="{Binding LaunchCommand}" />
|
||||
<Button Grid.Column="2" Classes="ghost small" Content="{loc:Loc home.open}"
|
||||
Command="{Binding OpenFolderCommand}" Margin="0,0,4,0" />
|
||||
<Button Grid.Column="3" Classes="ghost small danger" Content="{loc:Loc home.delete}"
|
||||
Command="{Binding DeleteCommand}" />
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
|
||||
<!-- 空状态 -->
|
||||
<Border Classes="card" Padding="30,34" IsVisible="{Binding IsEmpty}">
|
||||
<StackPanel Spacing="10" HorizontalAlignment="Center">
|
||||
<TextBlock Classes="h2" Text="{loc:Loc home.empty}" HorizontalAlignment="Center" />
|
||||
<TextBlock Classes="muted" Text="{loc:Loc home.emptyHint}" TextWrapping="Wrap"
|
||||
MaxWidth="420" TextAlignment="Center" />
|
||||
<Button Classes="primary" Content="{loc:Loc home.emptyAction}"
|
||||
Command="{Binding OpenDownloadCommand}" HorizontalAlignment="Center" Margin="0,6,0,0" />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
</StackPanel>
|
||||
</ScrollViewer>
|
||||
</UserControl>
|
||||
@@ -1,9 +0,0 @@
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Markup.Xaml;
|
||||
|
||||
namespace GC.Views;
|
||||
|
||||
public partial class HomeView : UserControl
|
||||
{
|
||||
public HomeView() => AvaloniaXamlLoader.Load(this);
|
||||
}
|
||||
@@ -1,107 +0,0 @@
|
||||
using System;
|
||||
using Avalonia;
|
||||
using Avalonia.Animation;
|
||||
using Avalonia.Animation.Easings;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Controls.Primitives;
|
||||
using Avalonia.Layout;
|
||||
using Avalonia.Media;
|
||||
using Avalonia.Threading;
|
||||
|
||||
namespace GC.Views;
|
||||
|
||||
/// <summary>
|
||||
/// 模型启动进度窗:加载模型程序集、生成地表纹理、构建界面的真实进度。
|
||||
/// 只显示进度,不做任何渲染。
|
||||
/// </summary>
|
||||
public sealed class LoadingWindow : Window
|
||||
{
|
||||
private readonly ProgressBar _bar;
|
||||
private readonly TextBlock _stage;
|
||||
private readonly TextBlock _percent;
|
||||
|
||||
public LoadingWindow(string modelName)
|
||||
{
|
||||
Title = modelName;
|
||||
Width = 460;
|
||||
Height = 172;
|
||||
CanResize = false;
|
||||
ShowInTaskbar = false;
|
||||
WindowStartupLocation = WindowStartupLocation.CenterOwner;
|
||||
Background = new SolidColorBrush(Color.Parse("#0B1226"));
|
||||
SystemDecorations = SystemDecorations.BorderOnly;
|
||||
|
||||
var title = new TextBlock
|
||||
{
|
||||
Text = modelName,
|
||||
Foreground = new SolidColorBrush(Color.Parse("#F2F6FF")),
|
||||
FontSize = 15,
|
||||
FontWeight = FontWeight.SemiBold
|
||||
};
|
||||
|
||||
_stage = new TextBlock
|
||||
{
|
||||
Text = "正在准备模型…",
|
||||
Foreground = new SolidColorBrush(Color.Parse("#8CA0C4")),
|
||||
FontSize = 12
|
||||
};
|
||||
|
||||
_bar = new ProgressBar
|
||||
{
|
||||
Minimum = 0,
|
||||
Maximum = 1,
|
||||
Value = 0,
|
||||
Height = 6,
|
||||
IsIndeterminate = true,
|
||||
CornerRadius = new CornerRadius(3),
|
||||
Foreground = new SolidColorBrush(Color.Parse("#3B7BFF")),
|
||||
Background = new SolidColorBrush(Color.Parse("#1B2740")),
|
||||
Transitions = new Transitions
|
||||
{
|
||||
// 进度平滑增长,不会一跳一跳
|
||||
new DoubleTransition
|
||||
{
|
||||
Property = RangeBase.ValueProperty,
|
||||
Duration = TimeSpan.FromMilliseconds(240),
|
||||
Easing = new CubicEaseOut()
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
_percent = new TextBlock
|
||||
{
|
||||
Text = "",
|
||||
Foreground = new SolidColorBrush(Color.Parse("#6E86AD")),
|
||||
FontSize = 11,
|
||||
HorizontalAlignment = HorizontalAlignment.Right
|
||||
};
|
||||
|
||||
var panel = new StackPanel
|
||||
{
|
||||
Margin = new Thickness(22, 20),
|
||||
Spacing = 12
|
||||
};
|
||||
panel.Children.Add(title);
|
||||
panel.Children.Add(_bar);
|
||||
panel.Children.Add(_stage);
|
||||
panel.Children.Add(_percent);
|
||||
|
||||
Content = panel;
|
||||
}
|
||||
|
||||
/// <summary>任意线程调用都可以。</summary>
|
||||
public void Report(double value, string? message)
|
||||
{
|
||||
if (!Dispatcher.UIThread.CheckAccess())
|
||||
{
|
||||
Dispatcher.UIThread.Post(() => Report(value, message));
|
||||
return;
|
||||
}
|
||||
|
||||
var clamped = Math.Clamp(value, 0, 1);
|
||||
_bar.IsIndeterminate = false;
|
||||
_bar.Value = clamped;
|
||||
_percent.Text = $"{clamped * 100:0}%";
|
||||
if (!string.IsNullOrWhiteSpace(message)) _stage.Text = message;
|
||||
}
|
||||
}
|
||||
@@ -1,119 +0,0 @@
|
||||
<Window xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:loc="using:GC.Services"
|
||||
x:Class="GC.Views.MainWindow"
|
||||
Title="{loc:Loc app.name}"
|
||||
Width="1220" Height="800"
|
||||
MinWidth="1040" MinHeight="700"
|
||||
Background="Transparent"
|
||||
TransparencyLevelHint="Transparent"
|
||||
SystemDecorations="None"
|
||||
WindowStartupLocation="CenterScreen">
|
||||
|
||||
<!-- 禁用系统标题栏,改用自建标题栏。
|
||||
窗口本身透明(四角露出桌面 => 圆角可见),内容 Border 自己不透明并
|
||||
用 CornerRadius + ClipToBounds 裁出圆角;AcrylicBlur 会引入系统白色,
|
||||
所以这里用纯 Transparent 避免白边。 -->
|
||||
<Border CornerRadius="16" ClipToBounds="True"
|
||||
Background="{DynamicResource AppBg}"
|
||||
BorderBrush="#1B2740" BorderThickness="1"
|
||||
BoxShadow="0 18 50 0 #400A1226">
|
||||
<Grid RowDefinitions="44,*">
|
||||
<!-- 自建标题栏 -->
|
||||
<Border x:Name="TitleBar" Grid.Row="0" Background="{DynamicResource TitleBarBg}"
|
||||
PointerPressed="OnTitleBarPointerPressed">
|
||||
<Grid ColumnDefinitions="*,Auto,Auto,Auto" Margin="16,0,10,0">
|
||||
<StackPanel Orientation="Horizontal" Spacing="10" VerticalAlignment="Center">
|
||||
<Border Width="22" Height="22" CornerRadius="7" Background="#1C2C4C">
|
||||
<TextBlock Text="◎" FontSize="13" Foreground="#8FB6FF"
|
||||
HorizontalAlignment="Center" VerticalAlignment="Center" />
|
||||
</Border>
|
||||
<TextBlock Text="{loc:Loc app.name}" Foreground="#F2F6FF" FontSize="12.5"
|
||||
FontWeight="SemiBold" VerticalAlignment="Center" />
|
||||
</StackPanel>
|
||||
<!-- 与模型窗口一致的纯矢量图标:无圆圈 -->
|
||||
<Button x:Name="MinimizeButton" Grid.Column="1" Classes="titlebtn"
|
||||
Click="OnMinimizeClick">
|
||||
<Path Data="M1.5,5 L8.5,5" Stroke="#A9B8D4" StrokeThickness="1.5"
|
||||
StrokeLineCap="Round" Stretch="None" Width="10" Height="10"
|
||||
HorizontalAlignment="Center" VerticalAlignment="Center" />
|
||||
</Button>
|
||||
<Button x:Name="MaximizeButton" Grid.Column="2" Classes="titlebtn"
|
||||
Click="OnMaximizeClick">
|
||||
<Path x:Name="MaximizeGlyph" Data="M2.2,2.2 L7.8,2.2 L7.8,7.8 L2.2,7.8 Z"
|
||||
Stroke="#A9B8D4" StrokeThickness="1.5" StrokeLineCap="Round"
|
||||
StrokeJoin="Round" Stretch="None" Width="10" Height="10"
|
||||
HorizontalAlignment="Center" VerticalAlignment="Center" />
|
||||
</Button>
|
||||
<Button x:Name="CloseButton" Grid.Column="3" Classes="titlebtn close"
|
||||
Click="OnCloseClick">
|
||||
<Path Data="M2,2 L8,8 M8,2 L2,8" Stroke="#A9B8D4" StrokeThickness="1.5"
|
||||
StrokeLineCap="Round" Stretch="None" Width="10" Height="10"
|
||||
HorizontalAlignment="Center" VerticalAlignment="Center" />
|
||||
</Button>
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- 原内容整体下移一行 -->
|
||||
<Grid Grid.Row="1" ColumnDefinitions="236,*" RowDefinitions="*,Auto">
|
||||
|
||||
<!-- 侧栏:品牌已在标题栏展示,这里只留一句副标题,避免重复 -->
|
||||
<Border Grid.Column="0" Grid.RowSpan="2" Background="{DynamicResource SideBgBrush}">
|
||||
<Grid RowDefinitions="Auto,*,Auto" Margin="16,20,16,18">
|
||||
|
||||
<StackPanel Spacing="3" Margin="2,0,0,0">
|
||||
<TextBlock Text="{loc:Loc app.tagline}" Foreground="#7C90B4" FontSize="10.5"
|
||||
TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
|
||||
<StackPanel Grid.Row="1" Margin="0,26,0,0" Spacing="6">
|
||||
<TextBlock Text="MENU" Foreground="#4C5F80" FontSize="9.5" FontWeight="SemiBold" Margin="14,0,0,4" />
|
||||
<Button Classes="nav" Classes.active="{Binding IsHomeActive}"
|
||||
Command="{Binding GoHomeCommand}" Content="{loc:Loc nav.home}" />
|
||||
<Button Classes="nav" Classes.active="{Binding IsDownloadActive}"
|
||||
Command="{Binding GoDownloadCommand}" Content="{loc:Loc nav.download}" />
|
||||
<Button Classes="nav" Classes.active="{Binding IsSettingsActive}"
|
||||
Command="{Binding GoSettingsCommand}" Content="{loc:Loc nav.settings}" />
|
||||
<Button Classes="nav" Classes.active="{Binding IsAboutActive}"
|
||||
Command="{Binding GoAboutCommand}" Content="{loc:Loc nav.about}" />
|
||||
</StackPanel>
|
||||
|
||||
<StackPanel Grid.Row="2" Spacing="4">
|
||||
<Border Height="1" Background="{DynamicResource SideLine}" Margin="0,0,0,10" />
|
||||
<TextBlock Text="{Binding VersionText}" Foreground="#6F82A6" FontSize="10.5" Margin="14,0,0,0" />
|
||||
<TextBlock Text="{Binding PlatformText}" Foreground="#4F6080" FontSize="10" Margin="14,0,0,0" />
|
||||
</StackPanel>
|
||||
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- 内容:页面切换由 MainWindow 做淡入过渡,避免硬切 -->
|
||||
<ContentControl x:Name="PageHost" Grid.Column="1" Grid.Row="0" Content="{Binding Current}" />
|
||||
|
||||
<!-- 启动更新状态条:模型立即生效,启动器下次启动生效 -->
|
||||
<Border Grid.Column="1" Grid.Row="1"
|
||||
Background="{DynamicResource Surface}"
|
||||
BorderBrush="{DynamicResource Line}" BorderThickness="0,1,0,0"
|
||||
Padding="20,9" IsVisible="{Binding UpdateBarVisible}">
|
||||
<Grid ColumnDefinitions="Auto,*,Auto,Auto">
|
||||
<TextBlock Grid.Column="0" Text="⟳" FontSize="16" Foreground="{DynamicResource Accent}"
|
||||
VerticalAlignment="Center" Margin="0,0,12,0" />
|
||||
<StackPanel Grid.Column="1" Spacing="2" VerticalAlignment="Center">
|
||||
<TextBlock Text="{Binding UpdateStatus}" FontSize="12.5" FontWeight="SemiBold"
|
||||
Foreground="{DynamicResource Ink}" TextTrimming="CharacterEllipsis" />
|
||||
<TextBlock Text="{Binding UpdateDetail}" Classes="faint" TextTrimming="CharacterEllipsis" />
|
||||
<TextBlock Text="{Binding LauncherNotice}" FontSize="11" Foreground="{DynamicResource Warn}"
|
||||
TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
<ProgressBar Grid.Column="2" Width="130" Minimum="0" Maximum="1"
|
||||
Value="{Binding UpdateProgress}" IsVisible="{Binding UpdateBusy}"
|
||||
VerticalAlignment="Center" Margin="14,0" />
|
||||
<Button Grid.Column="3" Classes="ghost small" Content="{loc:Loc update.checkNow}"
|
||||
Command="{Binding CheckUpdateCommand}" IsEnabled="{Binding !UpdateBusy}"
|
||||
VerticalAlignment="Center" />
|
||||
</Grid>
|
||||
</Border>
|
||||
</Grid>
|
||||
</Grid>
|
||||
</Border>
|
||||
</Window>
|
||||
@@ -1,216 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia;
|
||||
using Avalonia.Animation;
|
||||
using Avalonia.Animation.Easings;
|
||||
using Avalonia.Threading;
|
||||
using System.Linq;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Input;
|
||||
using Avalonia.Markup.Xaml;
|
||||
using GC.Models;
|
||||
using GC.Services;
|
||||
using GC.ViewModels;
|
||||
|
||||
namespace GC.Views;
|
||||
|
||||
public partial class MainWindow : Window
|
||||
{
|
||||
private readonly List<PlayerWindow> _players = new();
|
||||
private MainViewModel? _viewModel;
|
||||
private ContentControl? _pageHost;
|
||||
private bool _isClosing;
|
||||
|
||||
public MainWindow()
|
||||
{
|
||||
InitializeComponent();
|
||||
_pageHost = this.FindControl<ContentControl>("PageHost");
|
||||
if (_pageHost != null)
|
||||
{
|
||||
// 页面切换:淡入过渡,避免瞬间硬切
|
||||
_pageHost.Transitions = new Transitions
|
||||
{
|
||||
new DoubleTransition
|
||||
{
|
||||
Property = Visual.OpacityProperty,
|
||||
Duration = TimeSpan.FromMilliseconds(200),
|
||||
Easing = new CubicEaseOut()
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
DataContextChanged += OnDataContextChanged;
|
||||
Closed += OnClosed;
|
||||
|
||||
// 最大化 / 还原:切换图标(单框 ⇄ 双框),圆角始终保持
|
||||
PropertyChanged += (_, e) =>
|
||||
{
|
||||
if (e.Property != WindowStateProperty) return;
|
||||
var max = WindowState == WindowState.Maximized;
|
||||
if (this.FindControl<Avalonia.Controls.Shapes.Path>("MaximizeGlyph") is { } glyph)
|
||||
glyph.Data = Avalonia.Media.Geometry.Parse(max
|
||||
? "M2.6,3.4 L7.4,3.4 L7.4,8.4 L2.6,8.4 Z M2.6,3.4 L2.6,1.6 L7.4,1.6 L7.4,6.6"
|
||||
: "M2.2,2.2 L7.8,2.2 L7.8,7.8 L2.2,7.8 Z");
|
||||
if (Content is Border frame) frame.CornerRadius = new Avalonia.CornerRadius(16);
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>当前打开的模型窗口(每个模型一个独立窗口)。</summary>
|
||||
public IReadOnlyList<PlayerWindow> PlayerWindows => _players;
|
||||
|
||||
private void InitializeComponent() => AvaloniaXamlLoader.Load(this);
|
||||
|
||||
private void OnDataContextChanged(object? sender, EventArgs e)
|
||||
{
|
||||
if (_viewModel != null)
|
||||
{
|
||||
_viewModel.PlayerRequested -= OpenPlayerWindow;
|
||||
_viewModel.PropertyChanged -= OnViewModelPropertyChanged;
|
||||
}
|
||||
_viewModel = DataContext as MainViewModel;
|
||||
if (_viewModel != null)
|
||||
{
|
||||
_viewModel.PlayerRequested += OpenPlayerWindow;
|
||||
_viewModel.PropertyChanged += OnViewModelPropertyChanged;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>切换页面时让内容淡入,避免「一卡一卡」的硬切。</summary>
|
||||
private void OnViewModelPropertyChanged(object? sender, PropertyChangedEventArgs e)
|
||||
{
|
||||
if (e.PropertyName != nameof(MainViewModel.Current) || _pageHost == null) return;
|
||||
_pageHost.Opacity = 0.55;
|
||||
// 下一帧回到 1,OpacityTransition 会自动插值
|
||||
Dispatcher.UIThread.Post(() =>
|
||||
{
|
||||
if (_pageHost != null) _pageHost.Opacity = 1;
|
||||
}, DispatcherPriority.Render);
|
||||
}
|
||||
|
||||
// 事件处理器必须是 void,因此包一层可观察异常的入口:
|
||||
// fire-and-forget 的 Task 也要观察异常,绝不外泄到 Avalonia 事件循环导致进程崩溃。
|
||||
private void OpenPlayerWindow(ModelPackage package) => _ = OpenPlayerWindowSafeAsync(package);
|
||||
|
||||
private async Task OpenPlayerWindowSafeAsync(ModelPackage package)
|
||||
{
|
||||
try { await OpenPlayerWindowAsync(package); }
|
||||
catch (Exception ex) { Console.Error.WriteLine($"打开模型窗口失败: {ex}"); }
|
||||
}
|
||||
|
||||
private async Task OpenPlayerWindowAsync(ModelPackage package)
|
||||
{
|
||||
if (_viewModel == null || _isClosing) return;
|
||||
|
||||
// 启动进度窗:模型加载、地表纹理生成、界面构建的真实进度
|
||||
var loading = new LoadingWindow(package.LocalizedName);
|
||||
loading.Show(this);
|
||||
loading.Report(0, "正在加载模型…");
|
||||
// 让进度窗先画出来(用调度器让出一帧,测试环境也能推进)
|
||||
await Dispatcher.UIThread.InvokeAsync(() => { }, DispatcherPriority.Render);
|
||||
|
||||
PlayerWindow? window = null;
|
||||
LoadedModel? loaded = null;
|
||||
Exception? error = null;
|
||||
|
||||
// 关键修复:requestClose 过去捕获的是「尚未赋值的 window」,加载期恒为 null,
|
||||
// 模型在 Prepare/CreateView 里调用 context.RequestClose() 会静默失效。
|
||||
// 改为关闭当前存在的窗口(加载期=进度窗,加载完成=模型窗),统一走 UI 线程。
|
||||
void RequestClose() => Dispatcher.UIThread.Post(() =>
|
||||
{
|
||||
(window ?? (Window?)loading)?.Close();
|
||||
});
|
||||
|
||||
try
|
||||
{
|
||||
loaded = await _viewModel.Models.LoadAsync(package, RequestClose,
|
||||
(value, message) => loading.Report(value, message));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
error = ex;
|
||||
}
|
||||
|
||||
loading.Close();
|
||||
|
||||
// 加载期间用户关掉了主窗口:不要再弹出幽灵模型窗口,直接释放已加载模型
|
||||
if (_isClosing)
|
||||
{
|
||||
loaded?.Dispose();
|
||||
return;
|
||||
}
|
||||
|
||||
if (loaded == null || error != null)
|
||||
{
|
||||
var message = error?.Message ?? L.I["player.errorHint"];
|
||||
var dialog = new ModelErrorWindow(
|
||||
L.I.F("player.errorTitle", package.LocalizedName),
|
||||
$"{message}\n\n{L.I["player.errorHint"]}");
|
||||
dialog.Show(this);
|
||||
return;
|
||||
}
|
||||
|
||||
window = new PlayerWindow(package, loaded);
|
||||
window.Closed += (_, _) => _players.Remove(window);
|
||||
_players.Add(window);
|
||||
window.Show(this);
|
||||
window.Activate();
|
||||
}
|
||||
|
||||
// ---- 自建标题栏 ------------------------------------------------------
|
||||
private void OnTitleBarPointerPressed(object? sender, PointerPressedEventArgs e)
|
||||
{
|
||||
// 双击标题栏 = 最大化 / 还原
|
||||
if (e.ClickCount == 2)
|
||||
{
|
||||
WindowState = WindowState == WindowState.Maximized
|
||||
? WindowState.Normal
|
||||
: WindowState.Maximized;
|
||||
return;
|
||||
}
|
||||
if (e.GetCurrentPoint(this).Properties.IsLeftButtonPressed)
|
||||
BeginMoveDrag(e);
|
||||
}
|
||||
|
||||
private void OnMinimizeClick(object? sender, global::Avalonia.Interactivity.RoutedEventArgs e)
|
||||
=> WindowState = WindowState.Minimized;
|
||||
|
||||
private void OnMaximizeClick(object? sender, global::Avalonia.Interactivity.RoutedEventArgs e)
|
||||
=> WindowState = WindowState == WindowState.Maximized
|
||||
? WindowState.Normal
|
||||
: WindowState.Maximized;
|
||||
|
||||
// 关闭动画:先淡出再真正 Close(第 4 项)
|
||||
private async void OnCloseClick(object? sender, global::Avalonia.Interactivity.RoutedEventArgs e)
|
||||
{
|
||||
if (_isClosing) return;
|
||||
Opacity = 1;
|
||||
Transitions = new Transitions
|
||||
{
|
||||
new DoubleTransition
|
||||
{
|
||||
Property = OpacityProperty,
|
||||
Duration = TimeSpan.FromMilliseconds(180),
|
||||
Easing = new CubicEaseIn()
|
||||
}
|
||||
};
|
||||
Opacity = 0;
|
||||
await Task.Delay(190);
|
||||
Close();
|
||||
}
|
||||
|
||||
private void OnClosed(object? sender, EventArgs e)
|
||||
{
|
||||
_isClosing = true;
|
||||
if (_viewModel != null)
|
||||
{
|
||||
_viewModel.PlayerRequested -= OpenPlayerWindow;
|
||||
_viewModel.PropertyChanged -= OnViewModelPropertyChanged;
|
||||
}
|
||||
// 先取快照再关闭:PlayerWindow.Closed 回调会 _players.Remove,
|
||||
// 直接遍历原集合会在 foreach 期间修改底层导致异常。
|
||||
foreach (var window in _players.ToList()) window.Close();
|
||||
_players.Clear();
|
||||
}
|
||||
}
|
||||
@@ -1,143 +0,0 @@
|
||||
<UserControl xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:loc="using:GC.Services"
|
||||
x:Class="GC.Views.SettingsView">
|
||||
|
||||
<ScrollViewer VerticalScrollBarVisibility="Auto">
|
||||
<StackPanel Margin="26,24,26,32" Spacing="16" MaxWidth="880" HorizontalAlignment="Left">
|
||||
|
||||
<StackPanel Spacing="4">
|
||||
<TextBlock Classes="h1" Text="{loc:Loc set.title}" />
|
||||
<TextBlock Classes="muted" Text="{loc:Loc set.subtitle}" />
|
||||
</StackPanel>
|
||||
|
||||
<!-- 通用 -->
|
||||
<Border Classes="card" Padding="20,18">
|
||||
<StackPanel Spacing="16">
|
||||
<TextBlock Classes="h2" Text="{loc:Loc set.general}" />
|
||||
|
||||
<Grid ColumnDefinitions="200,*">
|
||||
<StackPanel VerticalAlignment="Center" Spacing="2">
|
||||
<TextBlock Classes="h3" Text="{loc:Loc set.language}" />
|
||||
</StackPanel>
|
||||
<ComboBox Grid.Column="1" ItemsSource="{Binding Languages}"
|
||||
SelectedItem="{Binding SelectedLanguage}" Width="220" HorizontalAlignment="Left">
|
||||
<ComboBox.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<TextBlock Text="{Binding Label}" />
|
||||
</DataTemplate>
|
||||
</ComboBox.ItemTemplate>
|
||||
</ComboBox>
|
||||
</Grid>
|
||||
|
||||
<Grid ColumnDefinitions="200,*">
|
||||
<StackPanel VerticalAlignment="Center" Spacing="2">
|
||||
<TextBlock Classes="h3" Text="{loc:Loc set.fps}" />
|
||||
<TextBlock Classes="faint" Text="{loc:Loc set.fps.desc}" TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
<ComboBox Grid.Column="1" ItemsSource="{Binding FrameRates}"
|
||||
SelectedItem="{Binding SelectedFps}" Width="120" HorizontalAlignment="Left" />
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<!-- 内存 -->
|
||||
<Border Classes="card" Padding="20,18">
|
||||
<StackPanel Spacing="12">
|
||||
<Grid ColumnDefinitions="*,Auto">
|
||||
<TextBlock Classes="h2" Text="{loc:Loc set.memory}" />
|
||||
<TextBlock Grid.Column="1" Text="{Binding MemoryValueText}" Classes="h3"
|
||||
Foreground="{DynamicResource Accent}" VerticalAlignment="Center" />
|
||||
</Grid>
|
||||
<TextBlock Classes="muted" Text="{loc:Loc set.memory.desc}" TextWrapping="Wrap" />
|
||||
<CheckBox Content="{loc:Loc set.memory.auto}" IsChecked="{Binding MemoryAuto}"
|
||||
Margin="0,2,0,0" />
|
||||
<Slider Minimum="512" Maximum="8192" TickFrequency="256" IsSnapToTickEnabled="False"
|
||||
IsEnabled="{Binding !MemoryAuto}"
|
||||
Value="{Binding MemoryValue}" Margin="0,4,0,0" />
|
||||
<Grid ColumnDefinitions="*,Auto">
|
||||
<TextBlock Classes="faint" Text="{loc:Loc set.memory.hint}" TextWrapping="Wrap" />
|
||||
<TextBlock Grid.Column="1" Classes="faint" Text="{Binding UsageText}" Margin="16,0,0,0" />
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<!-- 模型源 -->
|
||||
<Border Classes="card" Padding="20,18">
|
||||
<StackPanel Spacing="10">
|
||||
<TextBlock Classes="h2" Text="{loc:Loc set.sources}" />
|
||||
<TextBlock Classes="muted" Text="{loc:Loc set.sources.desc}" TextWrapping="Wrap" />
|
||||
<ItemsControl ItemsSource="{Binding Sources}" Margin="0,4,0,0">
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<Border Classes="panel" Padding="12,9" Margin="0,0,0,8">
|
||||
<Grid ColumnDefinitions="Auto,*,Auto">
|
||||
<CheckBox IsChecked="{Binding Enabled}" VerticalAlignment="Center" Margin="0,0,10,0" />
|
||||
<StackPanel Grid.Column="1" Spacing="2" VerticalAlignment="Center">
|
||||
<TextBlock Text="{Binding Name}" FontSize="12.5" FontWeight="SemiBold" />
|
||||
<TextBlock Text="{Binding UrlText}" Classes="faint" TextTrimming="CharacterEllipsis" MaxWidth="520" />
|
||||
</StackPanel>
|
||||
<Button Grid.Column="2" Classes="ghost small" Content="✕"
|
||||
IsVisible="{Binding CanRemove}" Command="{Binding RemoveCommand}" VerticalAlignment="Center" />
|
||||
</Grid>
|
||||
</Border>
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<!-- 自动更新 -->
|
||||
<Border Classes="card" Padding="20,18">
|
||||
<StackPanel Spacing="12">
|
||||
<TextBlock Classes="h2" Text="{loc:Loc update.title}" />
|
||||
<TextBlock Classes="muted" Text="{loc:Loc update.desc}" TextWrapping="Wrap" />
|
||||
<CheckBox IsChecked="{Binding AutoUpdate}" Content="{loc:Loc update.auto}" />
|
||||
<Grid ColumnDefinitions="200,*">
|
||||
<TextBlock Classes="h3" Text="{loc:Loc update.source}" VerticalAlignment="Center" />
|
||||
<TextBlock Grid.Column="1" Classes="muted" Text="{Binding UpdateSourceText}"
|
||||
TextTrimming="CharacterEllipsis" VerticalAlignment="Center" />
|
||||
</Grid>
|
||||
<Grid ColumnDefinitions="200,*">
|
||||
<TextBlock Classes="h3" Text="{loc:Loc update.lastCheck}" />
|
||||
<TextBlock Grid.Column="1" Classes="muted" Text="{Binding LastCheckText}" />
|
||||
</Grid>
|
||||
<Grid ColumnDefinitions="200,*">
|
||||
<TextBlock Classes="h3" Text="{loc:Loc update.pending}" />
|
||||
<TextBlock Grid.Column="1" Classes="muted" Text="{Binding PendingText}" />
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<!-- 存储 -->
|
||||
<Border Classes="card" Padding="20,18">
|
||||
<StackPanel Spacing="14">
|
||||
<TextBlock Classes="h2" Text="{loc:Loc set.storage}" />
|
||||
|
||||
<Grid ColumnDefinitions="200,*,Auto">
|
||||
<TextBlock Classes="h3" Text="{loc:Loc set.modelDir}" VerticalAlignment="Center" />
|
||||
<TextBlock Grid.Column="1" Classes="muted" Text="{Binding ModelRoot}"
|
||||
TextTrimming="CharacterEllipsis" VerticalAlignment="Center" Margin="0,0,10,0" />
|
||||
<Button Grid.Column="2" Classes="small" Content="{loc:Loc set.openFolder}"
|
||||
Command="{Binding OpenModelFolderCommand}" />
|
||||
</Grid>
|
||||
|
||||
<Grid ColumnDefinitions="200,*,Auto">
|
||||
<TextBlock Classes="h3" Text="{loc:Loc set.dataDir}" VerticalAlignment="Center" />
|
||||
<TextBlock Grid.Column="1" Classes="muted" Text="{Binding DataRoot}"
|
||||
TextTrimming="CharacterEllipsis" VerticalAlignment="Center" Margin="0,0,10,0" />
|
||||
<Button Grid.Column="2" Classes="small" Content="{loc:Loc set.openFolder}"
|
||||
Command="{Binding OpenDataFolderCommand}" />
|
||||
</Grid>
|
||||
|
||||
<Grid ColumnDefinitions="*,Auto">
|
||||
<TextBlock Classes="faint" Text="{Binding StatusMessage}" VerticalAlignment="Center" />
|
||||
<Button Grid.Column="1" Classes="small" Content="{loc:Loc set.clearCache}"
|
||||
Command="{Binding ClearCacheCommand}" />
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
</StackPanel>
|
||||
</ScrollViewer>
|
||||
</UserControl>
|
||||
@@ -1,9 +0,0 @@
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Markup.Xaml;
|
||||
|
||||
namespace GC.Views;
|
||||
|
||||
public partial class SettingsView : UserControl
|
||||
{
|
||||
public SettingsView() => AvaloniaXamlLoader.Load(this);
|
||||
}
|
||||
@@ -1,109 +0,0 @@
|
||||
using System;
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Layout;
|
||||
using Avalonia.Media;
|
||||
using Avalonia.Threading;
|
||||
using GC.Services;
|
||||
|
||||
namespace GC.Views;
|
||||
|
||||
/// <summary>
|
||||
/// 启动器更新进度窗:更新期间主窗口已关闭,由这个独立小窗展示下载进度。
|
||||
/// 窗口本身透明,圆角由内部 Border 裁出。
|
||||
/// </summary>
|
||||
public sealed class UpdaterWindow : Window
|
||||
{
|
||||
private readonly ProgressBar _bar;
|
||||
private readonly TextBlock _stage;
|
||||
private readonly TextBlock _detail;
|
||||
private readonly TextBlock _percent;
|
||||
|
||||
public UpdaterWindow(string title)
|
||||
{
|
||||
Title = title;
|
||||
Width = 460;
|
||||
Height = 210;
|
||||
CanResize = false;
|
||||
ShowInTaskbar = false;
|
||||
WindowStartupLocation = WindowStartupLocation.CenterScreen;
|
||||
// 必须透明,否则会把内部 Border 的圆角填平
|
||||
Background = Brushes.Transparent;
|
||||
TransparencyLevelHint = new[] { WindowTransparencyLevel.Transparent };
|
||||
SystemDecorations = SystemDecorations.None;
|
||||
|
||||
var titleBlock = new TextBlock
|
||||
{
|
||||
Text = title,
|
||||
Foreground = new SolidColorBrush(Color.Parse("#F2F6FF")),
|
||||
FontSize = 15,
|
||||
FontWeight = FontWeight.SemiBold
|
||||
};
|
||||
|
||||
_stage = new TextBlock
|
||||
{
|
||||
Text = "正在准备…",
|
||||
Foreground = new SolidColorBrush(Color.Parse("#8CA0C4")),
|
||||
FontSize = 12
|
||||
};
|
||||
|
||||
_bar = new ProgressBar
|
||||
{
|
||||
Minimum = 0,
|
||||
Maximum = 1,
|
||||
Value = 0,
|
||||
Height = 6,
|
||||
CornerRadius = new CornerRadius(3),
|
||||
Foreground = new SolidColorBrush(Color.Parse("#3B7BFF")),
|
||||
Background = new SolidColorBrush(Color.Parse("#1B2740"))
|
||||
};
|
||||
|
||||
_percent = new TextBlock
|
||||
{
|
||||
Text = "0%",
|
||||
Foreground = new SolidColorBrush(Color.Parse("#6E86AD")),
|
||||
FontSize = 11,
|
||||
HorizontalAlignment = HorizontalAlignment.Right
|
||||
};
|
||||
|
||||
_detail = new TextBlock
|
||||
{
|
||||
Text = "",
|
||||
Foreground = new SolidColorBrush(Color.Parse("#4F6382")),
|
||||
FontSize = 10.5
|
||||
};
|
||||
|
||||
var panel = new StackPanel { Margin = new Thickness(24, 22), Spacing = 12 };
|
||||
panel.Children.Add(titleBlock);
|
||||
panel.Children.Add(_bar);
|
||||
panel.Children.Add(_stage);
|
||||
panel.Children.Add(_percent);
|
||||
panel.Children.Add(_detail);
|
||||
|
||||
Content = new Border
|
||||
{
|
||||
CornerRadius = new CornerRadius(16),
|
||||
Background = new SolidColorBrush(Color.Parse("#0B1226")),
|
||||
BorderBrush = new SolidColorBrush(Color.Parse("#223252")),
|
||||
BorderThickness = new Thickness(1),
|
||||
ClipToBounds = true,
|
||||
Child = panel
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>任意线程调用都可以。</summary>
|
||||
public void Report(double value, string? stage, string? detail = null)
|
||||
{
|
||||
if (!Dispatcher.UIThread.CheckAccess())
|
||||
{
|
||||
Dispatcher.UIThread.Post(() => Report(value, stage, detail));
|
||||
return;
|
||||
}
|
||||
|
||||
var clamped = Math.Clamp(value, 0, 1);
|
||||
_bar.Value = clamped;
|
||||
_percent.Text = $"{clamped * 100:0}%";
|
||||
if (!string.IsNullOrWhiteSpace(stage)) _stage.Text = stage;
|
||||
if (!string.IsNullOrWhiteSpace(detail)) _detail.Text = detail;
|
||||
}
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<Nullable>enable</Nullable>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<RootNamespace>GC.Tests</RootNamespace>
|
||||
<AssemblyName>GC.Tests</AssemblyName>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Avalonia.Headless" Version="$(AvaloniaVersion)" />
|
||||
<PackageReference Include="Avalonia.Skia" Version="$(AvaloniaVersion)" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../../../GC.Core.csproj" />
|
||||
<ProjectReference Include="../../../../../GC-DOWNLOAD/GC-DOWNLOAD.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -1,67 +0,0 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using GC.Services;
|
||||
|
||||
namespace GC.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// 日志模块的用例:双语写入、跨天文件命名、旧日志清理、不误删用户文件。
|
||||
///
|
||||
/// 这些看起来是小事,但 <c>.GC/logs</c> 会随程序跑很久:写入路径每行开两个文件句柄,
|
||||
/// 或者完全不清理,都会在几个月后变成用户磁盘上的几 GB。用例锁住这两个行为。
|
||||
/// </summary>
|
||||
internal static class LogTests
|
||||
{
|
||||
private static int _failed;
|
||||
|
||||
public static int Run()
|
||||
{
|
||||
var dir = Path.Combine(Path.GetTempPath(), "gc-log-" + Guid.NewGuid().ToString("N")[..8]);
|
||||
Directory.CreateDirectory(dir);
|
||||
try
|
||||
{
|
||||
// 过期日志(2000 年)+ 用户自己的文件
|
||||
var oldZh = Path.Combine(dir, "gc-20000101.log");
|
||||
var oldEn = Path.Combine(dir, "gc-20000101.en.log");
|
||||
var userFile = Path.Combine(dir, "keep-me.txt");
|
||||
File.WriteAllText(oldZh, "old");
|
||||
File.WriteAllText(oldEn, "old");
|
||||
File.WriteAllText(userFile, "user data");
|
||||
|
||||
GcLog.Init(dir);
|
||||
GcLog.Info("测试中文", "test english");
|
||||
|
||||
var day = DateTime.Now.ToString("yyyyMMdd");
|
||||
var zhPath = Path.Combine(dir, $"gc-{day}.log");
|
||||
var enPath = Path.Combine(dir, $"gc-{day}.en.log");
|
||||
|
||||
Check("中文日志写入", File.Exists(zhPath) && File.ReadAllText(zhPath).Contains("测试中文"), "中文日志缺失");
|
||||
Check("英文日志写入", File.Exists(enPath) && File.ReadAllText(enPath).Contains("test english"), "英文日志缺失");
|
||||
Check("过期日志被清理", !File.Exists(oldZh) && !File.Exists(oldEn), "2000 年的日志还在");
|
||||
Check("目录里的用户文件不被误删", File.Exists(userFile), "keep-me.txt 被删了");
|
||||
|
||||
var names = Directory.GetFiles(dir).Select(Path.GetFileName).OrderBy(n => n).ToArray();
|
||||
Check("日志目录只剩当天两份 + 用户文件",
|
||||
names.Length == 3, "目录内容: " + string.Join(", ", names));
|
||||
}
|
||||
finally
|
||||
{
|
||||
try { Directory.Delete(dir, true); } catch { }
|
||||
}
|
||||
|
||||
Console.WriteLine(_failed == 0 ? "日志测试全部通过" : $"日志测试失败 {_failed} 项");
|
||||
return _failed;
|
||||
}
|
||||
|
||||
private static void Check(string label, bool ok, string detail)
|
||||
{
|
||||
if (ok)
|
||||
{
|
||||
Console.WriteLine(" ✓ " + label);
|
||||
return;
|
||||
}
|
||||
_failed++;
|
||||
Console.WriteLine($" ✗ {label} —— {detail}");
|
||||
}
|
||||
}
|
||||
@@ -1,562 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
using System.Linq;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text.Json;
|
||||
using GC.Models;
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Headless;
|
||||
using Avalonia.Threading;
|
||||
using Avalonia.VisualTree;
|
||||
using GC;
|
||||
using GC.Download;
|
||||
using GC.Services;
|
||||
using GC.ViewModels;
|
||||
using GC.Views;
|
||||
|
||||
namespace GC.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// 离屏校验工具:把启动器页面和模型窗口渲染成 PNG。
|
||||
/// 用法:dotnet run --project GC/src/test/dotnet/GC.Tests -- build/screenshots
|
||||
/// </summary>
|
||||
internal static class Program
|
||||
{
|
||||
private static string _outDir = "screenshots";
|
||||
|
||||
[STAThread]
|
||||
public static int Main(string[] args)
|
||||
{
|
||||
DownloadModuleHost.Factory = new DownloadModuleFactory();
|
||||
if (args.Length > 0 && args[0] == "--update-test")
|
||||
return RunUpdateTest(args.Length > 1 ? args[1] : FindRepoRoot());
|
||||
|
||||
_outDir = args.Length > 0 ? args[0] : "screenshots";
|
||||
Directory.CreateDirectory(_outDir);
|
||||
Environment.SetEnvironmentVariable("EMS_HOME", FindRepoRoot());
|
||||
Environment.SetEnvironmentVariable("EMS_DATA", Path.Combine(_outDir, ".data"));
|
||||
|
||||
AppBuilder.Configure<App>()
|
||||
.UseSkia()
|
||||
.UseHeadless(new AvaloniaHeadlessPlatformOptions { UseHeadlessDrawing = false })
|
||||
.SetupWithoutStarting();
|
||||
|
||||
var services = AppServices.Create();
|
||||
RenderPages(services);
|
||||
|
||||
Console.WriteLine("截图输出: " + Path.GetFullPath(_outDir));
|
||||
|
||||
// 日志模块的用例放在渲染之后:它会切换 GcLog 的输出目录
|
||||
return LogTests.Run() == 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 离线验证自动更新完整链路:用本地目录冒充 gitcode 仓库,不访问网络、不替换真实程序。
|
||||
/// </summary>
|
||||
private static int RunUpdateTest(string repoRoot)
|
||||
{
|
||||
Console.WriteLine("=== 离线自动更新链路验证 ===");
|
||||
AppBuilder.Configure<App>()
|
||||
.UseSkia()
|
||||
.UseHeadless(new AvaloniaHeadlessPlatformOptions { UseHeadlessDrawing = false })
|
||||
.SetupWithoutStarting();
|
||||
L.I.Initialize("zh-CN");
|
||||
|
||||
var versionFile = Path.Combine(repoRoot, "version.json");
|
||||
if (!File.Exists(versionFile))
|
||||
{
|
||||
Console.WriteLine("FAIL: 缺少 version.json,请先执行 ./build.sh stamp");
|
||||
return 1;
|
||||
}
|
||||
|
||||
var tmp = Path.Combine(Path.GetTempPath(), "ems-update-" + Guid.NewGuid().ToString("N")[..8]);
|
||||
var remote = Path.Combine(tmp, "remote");
|
||||
var home = Path.Combine(tmp, ".GC");
|
||||
var modelRoot = Path.Combine(home, "model");
|
||||
Directory.CreateDirectory(modelRoot);
|
||||
|
||||
// 模拟远端仓库:version.json + 每个模型的 <id>.json / <id>.model/
|
||||
Directory.CreateDirectory(Path.Combine(remote, "model"));
|
||||
var fixtureVersion = Json.Read<RepoVersion>(versionFile)!;
|
||||
fixtureVersion.Models.RemoveAll(model =>
|
||||
model.Id is not "earth-rotation" and not "earth-revolution");
|
||||
foreach (var dir in Directory.GetDirectories(Path.Combine(repoRoot, "model")))
|
||||
{
|
||||
var id = Path.GetFileName(dir);
|
||||
if (id.StartsWith('_')) continue;
|
||||
var manifest = Path.Combine(dir, id + ".json");
|
||||
var data = Path.Combine(dir, id + ".model");
|
||||
if (!File.Exists(manifest) || !Directory.Exists(data)) continue;
|
||||
var dest = Path.Combine(remote, "model", id);
|
||||
Directory.CreateDirectory(dest);
|
||||
File.Copy(manifest, Path.Combine(dest, id + ".json"), true);
|
||||
CopyTree(data, Path.Combine(dest, id + ".model"));
|
||||
}
|
||||
|
||||
// 按远端实际内容重算完整性哈希(与 VersionStamp 同一算法),然后签名。
|
||||
// 客户端会复算这两项,不一致就拒绝安装 —— 这一步必须与构建端一致。
|
||||
foreach (var m in fixtureVersion.Models)
|
||||
{
|
||||
var computed = ModelIntegrity.Compute(Path.Combine(remote, "model", m.Id), m.Id);
|
||||
m.ManifestSha256 = computed.ManifestSha256;
|
||||
m.FilesSha256 = computed.FilesSha256;
|
||||
m.Files = computed.Files.Count;
|
||||
}
|
||||
|
||||
var signer = ManifestSignature.TryLoadPrivateKey(
|
||||
Path.Combine(repoRoot, ".signing", "gc-signing.pem"));
|
||||
if (signer == null)
|
||||
{
|
||||
Console.WriteLine("FAIL: 缺少签名私钥 .signing/gc-signing.pem,无法构造可信清单");
|
||||
return 1;
|
||||
}
|
||||
|
||||
var remoteManifest = Path.Combine(remote, "version.json");
|
||||
WriteSigned(remoteManifest, fixtureVersion, signer);
|
||||
Console.WriteLine($"远端清单已签名({ManifestSignature.Algorithm})");
|
||||
|
||||
// EMS_HOME 指向不含 .sln 的临时目录 -> 非开发态,走真实 .GC 布局
|
||||
Environment.SetEnvironmentVariable("EMS_HOME", tmp);
|
||||
Environment.SetEnvironmentVariable("EMS_DATA", home);
|
||||
Environment.SetEnvironmentVariable("EMS_MODELS", null);
|
||||
Environment.SetEnvironmentVariable("EMS_NO_SELF_UPDATE", "1");
|
||||
|
||||
var paths = AppPaths.Discover();
|
||||
paths.EnsureCreated();
|
||||
var settings = new SettingsService(paths);
|
||||
settings.Load();
|
||||
var updater = new UpdateService(paths, settings, new DirectoryRemote(remote));
|
||||
|
||||
var failures = 0;
|
||||
void Check(bool ok, string label)
|
||||
{
|
||||
Console.WriteLine($" {(ok ? "OK " : "FAIL")} {label}");
|
||||
if (!ok) failures++;
|
||||
}
|
||||
|
||||
Console.WriteLine($"运行目录: {paths.HomeRoot}");
|
||||
Console.WriteLine($"模型库: {paths.ModelRoot}");
|
||||
Check(paths.ModelRoot == modelRoot, "模型安装目录位于 .GC/model");
|
||||
Check(paths.CacheRoot.StartsWith(paths.HomeRoot, StringComparison.Ordinal), "模型与启动器下载暂存位于 .GC/cache");
|
||||
Check(paths.UpdateRoot.StartsWith(paths.HomeRoot, StringComparison.Ordinal), "启动器更新位于 .GC/update");
|
||||
Check(File.Exists(paths.SettingsFile), ".GC/config/settings.json 已创建");
|
||||
|
||||
// 1) 首次启动:模型全部下载并立即落地
|
||||
var r1 = Task.Run(() => updater.RunAsync(true, null)).GetAwaiter().GetResult();
|
||||
Console.WriteLine($"首次启动: {r1.Message} 更新数={r1.UpdatedModels}");
|
||||
Check(r1.UpdatedModels == 2, "首次启动下载 2 个模型");
|
||||
foreach (var id in new[] { "earth-rotation", "earth-revolution" })
|
||||
{
|
||||
var dir = Path.Combine(modelRoot, id);
|
||||
Check(File.Exists(Path.Combine(dir, id + ".json")), id + " 清单已落地");
|
||||
Check(File.Exists(Path.Combine(dir, id + ".model", "scene.json")), id + " 场景数据已落地");
|
||||
Check(!Directory.Exists(Path.Combine(dir, "src")), id + " 源码没有下到运行目录");
|
||||
Check(settings.Current.InstalledModelVersions.ContainsKey(id), id + " 版本已记录到 settings");
|
||||
}
|
||||
|
||||
// 2) 版本没变:不重复下载
|
||||
var r2 = Task.Run(() => updater.RunAsync(true, null)).GetAwaiter().GetResult();
|
||||
Console.WriteLine($"二次检查: {r2.Message} 更新数={r2.UpdatedModels}");
|
||||
Check(r2.UpdatedModels == 0, "版本未变时不重复下载");
|
||||
|
||||
// 3) 远端模型改版:只更新这一个,并且本次启动立即生效
|
||||
var rv = Json.Read<RepoVersion>(remoteManifest)!;
|
||||
Check(rv.Models.Count == 2 && !string.IsNullOrWhiteSpace(rv.Models[0].Version),
|
||||
"version.json 里模型版本由构建自动生成");
|
||||
var changed = rv.Models[0];
|
||||
changed.Version += "-changed";
|
||||
var stampName = "_version-stamp.txt";
|
||||
File.WriteAllText(Path.Combine(remote, "model", changed.Id,
|
||||
changed.Id + ".model", stampName), "new content");
|
||||
|
||||
// 内容变了 → 指纹必须跟着变,并且清单要重新签名,否则客户端会(正确地)拒绝
|
||||
var changedHash = ModelIntegrity.Compute(Path.Combine(remote, "model", changed.Id), changed.Id);
|
||||
changed.ManifestSha256 = changedHash.ManifestSha256;
|
||||
changed.FilesSha256 = changedHash.FilesSha256;
|
||||
changed.Files = changedHash.Files.Count;
|
||||
WriteSigned(remoteManifest, rv, signer);
|
||||
|
||||
var r3 = Task.Run(() => updater.RunAsync(true, null)).GetAwaiter().GetResult();
|
||||
Console.WriteLine($"模型改版: {r3.Message} 更新数={r3.UpdatedModels}");
|
||||
Check(r3.UpdatedModels == 1, "模型版本变化只更新 1 个模型");
|
||||
Check(File.Exists(Path.Combine(modelRoot, changed.Id, changed.Id + ".model", stampName)),
|
||||
"新版本本次启动立即生效");
|
||||
Check(File.Exists(Path.Combine(modelRoot, changed.Id, changed.Id + ".integrity.json")),
|
||||
"安装后写入完整性记录");
|
||||
|
||||
// 4) 启动器新版:用 LauncherUpdater 下载到当前目录(与旧版并列)
|
||||
var rid = LauncherRuntimeInfo.CurrentRid;
|
||||
Console.WriteLine($"当前平台: {rid},启动器版本: {LauncherRuntimeInfo.CurrentLauncherVersion}");
|
||||
var stage = Path.Combine(tmp, "launcher-stage");
|
||||
Directory.CreateDirectory(stage);
|
||||
// Linux 的启动器没有扩展名,测试包名要跟着平台走
|
||||
var launcherExt = OperatingSystem.IsWindows() ? ".exe" : "";
|
||||
File.WriteAllText(Path.Combine(stage, "GCL-9.9.9-" + LauncherUpdater.PlatformLabel + launcherExt),
|
||||
"new launcher");
|
||||
var zip = Path.Combine(tmp, "GC-" + rid + ".zip");
|
||||
ZipFile.CreateFromDirectory(stage, zip);
|
||||
rv.Launcher.Version = "9.9.9";
|
||||
rv.Launcher.Packages[rid] = new RepoPackage
|
||||
{
|
||||
Url = zip,
|
||||
Sha256 = Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(zip))).ToLowerInvariant(),
|
||||
Size = new FileInfo(zip).Length
|
||||
};
|
||||
WriteSigned(remoteManifest, rv, signer);
|
||||
|
||||
// 造一个旧版在当前目录
|
||||
var oldName = "GC-1.0.0-" + LauncherUpdater.PlatformLabel + launcherExt;
|
||||
File.WriteAllText(Path.Combine(paths.InstallDirectory, oldName), "old launcher");
|
||||
|
||||
var dl = Task.Run(() => LauncherUpdater.DownloadAsync(paths, updater.Remote, null))
|
||||
.GetAwaiter().GetResult();
|
||||
Console.WriteLine($"启动器下载: {dl.Message}");
|
||||
Check(dl.State == UpdateRunState.Ready, "启动器下载成功");
|
||||
Check(!string.IsNullOrWhiteSpace(dl.PackageName), "得到新版包名");
|
||||
Check(File.Exists(Path.Combine(paths.UpdateRoot, "payload", dl.PackageName ?? "")) ||
|
||||
Directory.Exists(Path.Combine(paths.UpdateRoot, "payload", dl.PackageName ?? "")),
|
||||
"新版暂存于 .GC/update/payload");
|
||||
Check(!File.Exists(Path.Combine(paths.InstallDirectory, dl.PackageName ?? "")) &&
|
||||
!Directory.Exists(Path.Combine(paths.InstallDirectory, dl.PackageName ?? "")),
|
||||
"下载阶段不会把新版写入安装目录");
|
||||
Check(File.Exists(Path.Combine(paths.InstallDirectory, oldName)),
|
||||
"旧版仍在(删除由替换脚本在重启后做)");
|
||||
|
||||
// 5) 校验标记文件与替换脚本(相对路径,无绝对路径)
|
||||
var marker = Path.Combine(paths.UpdateRoot, "update.txt");
|
||||
Check(File.Exists(marker), "写出更新标记 update.txt");
|
||||
// 只验证脚本内容,不真的执行(否则脚本会在临时目录被删掉后搬文件、刷错误)
|
||||
var scheduled = LauncherUpdater.ScheduleApply(paths, dl.PackageName ?? "", execute: false);
|
||||
var scriptPath = Path.Combine(paths.UpdateRoot,
|
||||
OperatingSystem.IsWindows() ? "apply.bat" : "apply.sh");
|
||||
Check(scheduled && File.Exists(scriptPath), "替换脚本可生成");
|
||||
if (File.Exists(scriptPath))
|
||||
{
|
||||
var script = File.ReadAllText(scriptPath);
|
||||
Check(!script.Contains(tmp), "脚本不含绝对路径");
|
||||
Check(script.Contains("GC-*") || script.Contains("GCL-*"), "脚本按 GC-*/GCL-* 匹配删除");
|
||||
}
|
||||
|
||||
// 5b) 只发产物、不发 Release:更新包只存在于仓库 dist/<系统>-<架构>/ 目录里。
|
||||
// 清单不写 url、不写 path,只给 dir + name + sha256,客户端要能自己找过去。
|
||||
var distDir = Path.Combine(remote, "dist", LauncherUpdater.PlatformLabel);
|
||||
Directory.CreateDirectory(distDir);
|
||||
var distName = "GCL-9.9.10-" + LauncherUpdater.PlatformLabel + ".zip";
|
||||
var distZip = Path.Combine(distDir, distName);
|
||||
File.Copy(zip, distZip, true);
|
||||
|
||||
string Sha(string file) =>
|
||||
Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(file))).ToLowerInvariant();
|
||||
|
||||
rv.Launcher.Version = "9.9.10";
|
||||
rv.Launcher.Packages[rid] = new RepoPackage
|
||||
{
|
||||
Dir = "dist/" + LauncherUpdater.PlatformLabel,
|
||||
Name = distName,
|
||||
Sha256 = Sha(distZip),
|
||||
Size = new FileInfo(distZip).Length
|
||||
};
|
||||
WriteSigned(remoteManifest, rv, signer);
|
||||
|
||||
var dlDist = Task.Run(() => LauncherUpdater.DownloadAsync(paths, updater.Remote, null))
|
||||
.GetAwaiter().GetResult();
|
||||
Console.WriteLine($"dist 目录更新: {dlDist.Message}");
|
||||
Check(dlDist.State == UpdateRunState.Ready, "仓库 dist/<系统>-<架构>/ 里的产物能找到并下载");
|
||||
// 包名来自 zip 内容(这里仍是 9.9.9 的文件),所以要断言清单版本
|
||||
Check(dlDist.Version == "9.9.10", "下载的确实是 dist 目录里声明的那个版本");
|
||||
|
||||
// 5c) 往 dist/ 里塞一个哈希不匹配的包:必须拒绝(sha256 来自已签名清单)
|
||||
File.WriteAllText(distZip, "evil payload");
|
||||
var dlEvil = Task.Run(() => LauncherUpdater.DownloadAsync(paths, updater.Remote, null))
|
||||
.GetAwaiter().GetResult();
|
||||
Check(dlEvil.State == UpdateRunState.Failed, "dist 目录里哈希不符的包被拒绝");
|
||||
|
||||
// 还原到 9.9.9,后面的篡改 / 断网用例继续用这份清单
|
||||
rv.Launcher.Version = "9.9.9";
|
||||
rv.Launcher.Packages[rid] = new RepoPackage
|
||||
{
|
||||
Url = zip,
|
||||
Sha256 = Sha(zip),
|
||||
Size = new FileInfo(zip).Length
|
||||
};
|
||||
WriteSigned(remoteManifest, rv, signer);
|
||||
|
||||
// 6) 篡改检测:改一个字节但不重新签名 -> 必须判为不可信
|
||||
var tampered = File.ReadAllText(remoteManifest).Replace("\"9.9.9\"", "\"9.9.8\"");
|
||||
var tamperResult = ManifestSignature.Verify(tampered, requireSignature: true);
|
||||
Check(tamperResult.Trust == ManifestTrust.Invalid, "被篡改的清单验签失败");
|
||||
File.WriteAllText(remoteManifest, tampered);
|
||||
var r6 = Task.Run(() => updater.RunAsync(true, null)).GetAwaiter().GetResult();
|
||||
Check(r6.Outcome == UpdateOutcome.Unavailable, "清单被篡改时拒绝更新");
|
||||
WriteSigned(remoteManifest, rv, signer);
|
||||
|
||||
// 7) 断网兜底:保留本地模型,不清空
|
||||
var offline = new UpdateService(paths, settings, new GitCodeRemote("http://127.0.0.1:1/nope"));
|
||||
var beforeCount = settings.Current.InstalledModelVersions.Count;
|
||||
var r5 = Task.Run(() => offline.RunAsync(true, null)).GetAwaiter().GetResult();
|
||||
Check(r5.Outcome == UpdateOutcome.Unavailable &&
|
||||
settings.Current.InstalledModelVersions.Count == beforeCount &&
|
||||
Directory.Exists(Path.Combine(modelRoot, "earth-rotation")),
|
||||
"断网时保留本地模型、不清空模型库");
|
||||
|
||||
try { Directory.Delete(tmp, true); } catch { }
|
||||
Console.WriteLine(failures == 0
|
||||
? "=== 自动更新链路全部通过 ==="
|
||||
: $"=== 有 {failures} 项失败 ===");
|
||||
return failures == 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
/// <summary>序列化清单并用私钥签名(测试里模拟一次正式发布)。</summary>
|
||||
private static void WriteSigned(string path, RepoVersion version, ECDsa key)
|
||||
{
|
||||
// keyId 必须与 .signing/ 里的私钥对应的公钥条目一致,否则客户端按 keyId
|
||||
// 查不到受信任公钥,会判成 Invalid 而不是 Verified。
|
||||
var text = JsonSerializer.Serialize(version, Json.Options) + "\n";
|
||||
File.WriteAllText(path, ManifestSignature.SignDocument(text, key, "gc-2026-12"));
|
||||
}
|
||||
|
||||
private static void CopyTree(string src, string dst)
|
||||
{
|
||||
Directory.CreateDirectory(dst);
|
||||
foreach (var file in Directory.GetFiles(src, "*", SearchOption.AllDirectories))
|
||||
{
|
||||
if (Path.GetFileName(file).StartsWith('.')) continue;
|
||||
var dest = Path.Combine(dst, Path.GetRelativePath(src, file));
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(dest)!);
|
||||
File.Copy(file, dest, true);
|
||||
}
|
||||
}
|
||||
|
||||
private static string FindRepoRoot()
|
||||
{
|
||||
var dir = new DirectoryInfo(AppContext.BaseDirectory);
|
||||
for (var i = 0; i < 10 && dir != null; i++, dir = dir.Parent)
|
||||
{
|
||||
if (File.Exists(Path.Combine(dir.FullName, "GC.sln"))) return dir.FullName;
|
||||
}
|
||||
return Directory.GetCurrentDirectory();
|
||||
}
|
||||
|
||||
private static void RenderPages(AppServices services)
|
||||
{
|
||||
var vm = new MainViewModel(services);
|
||||
var window = new MainWindow { DataContext = vm };
|
||||
window.Show();
|
||||
Dispatcher.UIThread.RunJobs();
|
||||
Capture(window, "page-home.png");
|
||||
|
||||
vm.GoDownloadCommand.Execute(null);
|
||||
Dispatcher.UIThread.RunJobs();
|
||||
Capture(window, "page-download.png");
|
||||
|
||||
vm.GoSettingsCommand.Execute(null);
|
||||
Dispatcher.UIThread.RunJobs();
|
||||
Capture(window, "page-settings.png");
|
||||
|
||||
// 启动进度窗(单独截图)
|
||||
var demoLoading = new LoadingWindow("地球自转");
|
||||
demoLoading.Show(window);
|
||||
demoLoading.Report(0.42, "生成地表纹理");
|
||||
Dispatcher.UIThread.RunJobs();
|
||||
Capture(demoLoading, "page-loading.png");
|
||||
demoLoading.Close();
|
||||
|
||||
var packages = services.Models.Scan();
|
||||
Console.WriteLine($"模型数: {packages.Count}");
|
||||
foreach (var p in packages)
|
||||
Console.WriteLine($" {p.Id}: 程序集={Path.GetFileName(p.AssemblyPath)} 存在={File.Exists(p.AssemblyPath)} 封面={File.Exists(p.PreviewPath)}");
|
||||
|
||||
// 启动模型:应当新开窗口,主窗口保持原页面
|
||||
for (var i = 0; i < packages.Count && i < 2; i++)
|
||||
{
|
||||
var before = window.PlayerWindows.Count;
|
||||
vm.PlayModel(packages[i]);
|
||||
// 加载是异步的(带进度窗),这里泵一下调度器等它完成
|
||||
var appeared = WaitFor(() => window.PlayerWindows.Count > before);
|
||||
var player = window.PlayerWindows.LastOrDefault();
|
||||
Console.WriteLine($"player windows = {window.PlayerWindows.Count} ({packages[i].Id}) appeared={appeared}");
|
||||
if (player == null) continue;
|
||||
|
||||
if (i == 0)
|
||||
{
|
||||
Dispatcher.UIThread.RunJobs();
|
||||
Capture(player, "page-player.png");
|
||||
}
|
||||
else
|
||||
{
|
||||
Capture(player, "page-player-rotation.png");
|
||||
}
|
||||
|
||||
// 节气定位 / 视图切换只属于公转模型;自转模型不该出现
|
||||
var hasSeasons = Descendants(player).OfType<TextBlock>()
|
||||
.Any(t => (t.Text ?? "").Contains("节气定位", StringComparison.Ordinal) && ShownInTree(t));
|
||||
var hasViewSwitch = Descendants(player).OfType<Button>()
|
||||
.Any(b => b.Tag is string tag && (tag == "rotation" || tag == "revolution") && ShownInTree(b));
|
||||
Console.WriteLine($" {packages[i].Id}: 节气定位={hasSeasons} 视图切换={hasViewSwitch}");
|
||||
|
||||
// 缩放 / 触控 / 教学能力:模型画布由模型程序集提供,这里用反射逐项校验
|
||||
var canvases = Descendants(player).Where(c => c.GetType().Name == "CelestialView").ToList();
|
||||
var canvas = canvases.FirstOrDefault(c => Prop(c, "InsetMode") is bool inset && !inset)
|
||||
?? canvases.FirstOrDefault();
|
||||
var isRevolution = packages[i].Id.Contains("revolution", StringComparison.OrdinalIgnoreCase);
|
||||
Console.WriteLine($" {packages[i].Id}: 画布数={canvases.Count}(含课堂特写)");
|
||||
if (canvas != null)
|
||||
{
|
||||
var type = canvas.GetType();
|
||||
var zoomProp = type.GetProperty("Zoom");
|
||||
var zoomBy = type.GetMethod("ZoomBy");
|
||||
var resetView = type.GetMethod("ResetView");
|
||||
var beforeZoom = (double)(zoomProp?.GetValue(canvas) ?? 0d);
|
||||
zoomBy?.Invoke(canvas, new object[] { 1.25 });
|
||||
var afterZoom = (double)(zoomProp?.GetValue(canvas) ?? 0d);
|
||||
resetView?.Invoke(canvas, null);
|
||||
var resetZoom = (double)(zoomProp?.GetValue(canvas) ?? 0d);
|
||||
var hasPointerOverride = type.GetMethod("OnPointerMoved",
|
||||
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic) != null;
|
||||
var hasMultiTouch = type.GetField("_pointers",
|
||||
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic) != null;
|
||||
Console.WriteLine($" {packages[i].Id}: 缩放={beforeZoom:0.00}→{afterZoom:0.00}→{resetZoom:0.00} 拖动={hasPointerOverride} 多指跟踪={hasMultiTouch}");
|
||||
|
||||
// 双指捏合:两指间距 100→150,缩放应当 1.00→1.50
|
||||
var pinch = type.GetMethod("PinchZoom",
|
||||
System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
|
||||
var pinchZoom = (double)(pinch?.Invoke(null, new object[] { 1.0, 100.0, 150.0 }) ?? 0d);
|
||||
Console.WriteLine($" {packages[i].Id}: 捏合 100→150px = {pinchZoom:0.00}×");
|
||||
|
||||
// 手动转动:竖直拖动 300px 也不能改变视角平面
|
||||
var elevBefore = Field(canvas, "_camElevTarget");
|
||||
var angleBefore = (double)(Prop(canvas, isRevolution ? "OrbitAngle" : "SpinAngle") ?? 0d);
|
||||
type.GetMethod("DragBy")?.Invoke(canvas, new object[] { 40.0, 300.0 });
|
||||
var elevAfter = Field(canvas, "_camElevTarget");
|
||||
var angleAfter = (double)(Prop(canvas, isRevolution ? "OrbitAngle" : "SpinAngle") ?? 0d);
|
||||
Console.WriteLine($" {packages[i].Id}: 拖动 视角={elevBefore}→{elevAfter} 地球角度={angleBefore:0.0}→{angleAfter:0.0} 平面不变={Equals(elevBefore, elevAfter)}");
|
||||
|
||||
if (isRevolution)
|
||||
{
|
||||
// 两至日的直射点必须是教材值 23.5°
|
||||
foreach (var (angle, expect) in new[] { (0d, 0d), (90d, 23.5d), (180d, 0d), (270d, -23.5d) })
|
||||
{
|
||||
type.GetMethod("JumpToOrbit")?.Invoke(canvas, new object[] { angle });
|
||||
var decl = (double)(Prop(canvas, "SubsolarLatitude") ?? double.NaN);
|
||||
Console.WriteLine($" 直射点 {angle:0}° => {decl:0.00}° (应 {expect:0.0}°,误差 {Math.Abs(decl - expect):0.000})");
|
||||
}
|
||||
|
||||
// 点「夏至」应自动定格,并显示 23.5°N 的课堂读数
|
||||
var summer = Descendants(player).OfType<Button>()
|
||||
.FirstOrDefault(b => (b.Content as TextBlock)?.Text == "夏至" && ShownInTree(b));
|
||||
summer?.RaiseEvent(new Avalonia.Interactivity.RoutedEventArgs(Button.ClickEvent));
|
||||
Dispatcher.UIThread.RunJobs();
|
||||
var frozen = Prop(canvas, "IsPlaying") is bool play && !play;
|
||||
var frozenAngle = (double)(Prop(canvas, "OrbitAngle") ?? -1d);
|
||||
var cardReadout = Descendants(player).OfType<TextBlock>()
|
||||
.Any(t => (t.Text ?? "") == "23.5°N" && ShownInTree(t));
|
||||
Console.WriteLine($" 夏至按钮: 已定格={frozen} 角度={frozenAngle:0} 课堂卡显示 23.5°N={cardReadout}");
|
||||
Capture(player, "page-player-solstice.png");
|
||||
}
|
||||
}
|
||||
|
||||
// 课堂演示卡 / 底部触控提示
|
||||
var hasCard = Descendants(player).OfType<TextBlock>()
|
||||
.Any(t => (t.Text ?? "").Contains("课堂演示", StringComparison.Ordinal) && ShownInTree(t));
|
||||
var hasHint = Descendants(player).OfType<TextBlock>()
|
||||
.Any(t => (t.Text ?? "").Contains("拖动", StringComparison.Ordinal) && ShownInTree(t));
|
||||
Console.WriteLine($" {packages[i].Id}: 课堂演示卡={hasCard} 交互提示={hasHint}");
|
||||
}
|
||||
|
||||
// 关掉第二个窗口,只留一个继续验证主窗口
|
||||
var second = window.PlayerWindows.LastOrDefault();
|
||||
if (second != null) second.Close();
|
||||
Dispatcher.UIThread.RunJobs();
|
||||
Console.WriteLine($"window after closing second = {window.PlayerWindows.Count}");
|
||||
|
||||
// 主窗口仍停留在设置页 —— 说明没有被模型画面覆盖
|
||||
Capture(window, "page-main-while-playing.png");
|
||||
|
||||
foreach (var player in window.PlayerWindows.ToList()) player.Close();
|
||||
Dispatcher.UIThread.RunJobs();
|
||||
|
||||
window.Close();
|
||||
}
|
||||
|
||||
private static object? Prop(Control control, string name)
|
||||
=> control.GetType().GetProperty(name)?.GetValue(control);
|
||||
|
||||
private static object? Field(Control control, string name)
|
||||
=> control.GetType().GetField(name,
|
||||
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)?.GetValue(control);
|
||||
|
||||
private static bool WaitFor(Func<bool> condition, int timeoutMs = 20000)
|
||||
{
|
||||
var watch = Stopwatch.StartNew();
|
||||
while (watch.ElapsedMilliseconds < timeoutMs)
|
||||
{
|
||||
Dispatcher.UIThread.RunJobs();
|
||||
if (condition()) return true;
|
||||
Thread.Sleep(15);
|
||||
}
|
||||
return condition();
|
||||
}
|
||||
|
||||
private static bool ShownInTree(Control control)
|
||||
{
|
||||
Visual? current = control;
|
||||
while (current != null)
|
||||
{
|
||||
if (current is Control c && !c.IsVisible) return false;
|
||||
current = current.GetVisualParent();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static IEnumerable<Control> Descendants(Control root)
|
||||
{
|
||||
var stack = new Stack<Control>();
|
||||
stack.Push(root);
|
||||
while (stack.Count > 0)
|
||||
{
|
||||
var current = stack.Pop();
|
||||
yield return current;
|
||||
switch (current)
|
||||
{
|
||||
case Panel panel:
|
||||
foreach (var child in panel.Children) stack.Push(child);
|
||||
break;
|
||||
case Border { Child: Control only }:
|
||||
stack.Push(only);
|
||||
break;
|
||||
case ScrollViewer { Content: Control scrolled }:
|
||||
stack.Push(scrolled);
|
||||
break;
|
||||
case ContentControl { Content: Control content }:
|
||||
stack.Push(content);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void Capture(Window window, string fileName)
|
||||
{
|
||||
try
|
||||
{
|
||||
var frame = window.CaptureRenderedFrame();
|
||||
if (frame == null)
|
||||
{
|
||||
Console.WriteLine("capture failed: " + fileName);
|
||||
return;
|
||||
}
|
||||
var path = Path.Combine(_outDir, fileName);
|
||||
frame.Save(path);
|
||||
Console.WriteLine($"page -> {path}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"capture error {fileName}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
# 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>
|
||||
@@ -2,15 +2,24 @@
|
||||
# ---------------------------------------------------------------------------
|
||||
# GC 构建入口(薄封装)
|
||||
#
|
||||
# ./build.sh build 完整发布(原 publish),带 apt 风格进度条
|
||||
# 默认要求每个平台都带 Flutter 前端;--allow-no-ui 允许降级
|
||||
# ./build.sh check 验证:编译 + 自检 + 离屏渲染 + 产物
|
||||
# ./build.sh models 编译模型 dll + 封面 + 版本戳
|
||||
# ./build.sh stamp 重新生成 version.json
|
||||
# ./build.sh run / test / update-test / pack-models / pack-launcher
|
||||
# ./build.sh clean 清理
|
||||
# ./build.sh doctor dotnet 信息
|
||||
# ./build.sh dist 列出产物
|
||||
# ./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 build --allow-no-ui 允许不带 Flutter 前端(回退 Avalonia)
|
||||
# ./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 关闭进度条(保留步骤行)
|
||||
# FLUTTER_BIN 指定 flutter 可执行文件
|
||||
#
|
||||
# 实际代码都在 buildsh/ 里,本文件只负责加载模块与分发。
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -21,12 +30,11 @@ 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"
|
||||
PREVIEW_PROJ="model/_engine/PreviewGen/PreviewGen.csproj"
|
||||
STAMP_PROJ="model/_engine/VersionStamp/VersionStamp.csproj"
|
||||
TEST_PROJ="GC/src/test/dotnet/GC.Tests/GC.Tests.csproj"
|
||||
SLN="GC.sln"
|
||||
VERSION=$(sed -n 's/.*<Version>\(.*\)<\/Version>.*/\1/p' Directory.Build.props | head -1)
|
||||
[ -n "$VERSION" ] || VERSION="1.0.0"
|
||||
@@ -34,11 +42,12 @@ VERSION=$(sed -n 's/.*<Version>\(.*\)<\/Version>.*/\1/p' Directory.Build.props |
|
||||
TASK="${1:-build}"
|
||||
shift 2>/dev/null || true
|
||||
|
||||
# 解析 -version=<版本号>(也接受 --version=)与 --allow-no-ui
|
||||
# 解析 -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#*=}" ;;
|
||||
-allow-no-ui|--allow-no-ui) export GC_ALLOW_NO_UI=1 ;;
|
||||
esac
|
||||
done
|
||||
@@ -49,21 +58,23 @@ if [ -n "$CLI_VERSION" ]; then
|
||||
sed -i.bak "s|<Version>[^<]*</Version>|<Version>${VERSION}</Version>|" Directory.Build.props
|
||||
rm -f Directory.Build.props.bak
|
||||
fi
|
||||
echo "==> 版本号设为 ${VERSION}"
|
||||
printf '==> 版本号设为 %s\n' "$VERSION"
|
||||
fi
|
||||
mkdir -p "$ROOT_DIR/build/logs"
|
||||
|
||||
# 加载 buildsh 模块
|
||||
. "$ROOT_DIR/buildsh/lib/progress.sh"
|
||||
. "$ROOT_DIR/buildsh/lib/build_funcs.sh"
|
||||
# 加载模块(顺序即依赖顺序)
|
||||
for _m in log progress publish core flutter 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" ;;
|
||||
build) bs_build "$ROOT_DIR" ;;
|
||||
check) bs_check "$ROOT_DIR" ;;
|
||||
release-verify) bs_verify_release "$ROOT_DIR" "$@" ;;
|
||||
*) bs_tools "$ROOT_DIR" "$TASK" ;;
|
||||
esac
|
||||
+240
-133
@@ -1,154 +1,261 @@
|
||||
#!/bin/sh
|
||||
# buildsh/build.sh —— 完整发布(原 publish)
|
||||
# buildsh/build.sh —— 完整发布
|
||||
#
|
||||
# 目标平台按构建主机决定,每条产物都带 Flutter 前端:
|
||||
# macOS 主机 : mac-arm64(原生)+ win-amd64 / win-arm64(mingw 交叉)
|
||||
# 目标平台(默认按构建主机推断,可用 --targets= 覆盖):
|
||||
# macOS 主机 : mac-arm64(原生) + win-amd64 / win-arm64(mingw 交叉)
|
||||
# Linux 主机 : win-amd64 / win-arm64(mingw 交叉)
|
||||
# Linux 产物默认不构建:目标为 linux-arm64,官方 Flutter 引擎只有
|
||||
# x64 产物,必须在 aarch64 主机上编。需要时用 GC_BUILD_LINUX=1 显式开启
|
||||
# (云端 aarch64 runner 就是这么用的)。
|
||||
# Linux 产物默认不构建(目标 linux-arm64,官方 Flutter 引擎只有 x64,
|
||||
# 必须在 aarch64 主机上编);需要时 GC_BUILD_LINUX=1 显式开启
|
||||
# Windows 主机: win-amd64 / win-arm64(原生)
|
||||
#
|
||||
# 前端是默认必需项:flutter 缺失或编译失败一律中断,不再悄悄产出只带 Avalonia
|
||||
# 回退界面的包。确实要降级时用 ./build.sh build --allow-no-ui。
|
||||
# ./build.sh build 全平台
|
||||
# ./build.sh build --targets=mac 只出 macOS(跳过 Windows 交叉编译,秒级省下几分钟)
|
||||
# ./build.sh build --targets=win 只出 Windows
|
||||
#
|
||||
# 进度权重按实测耗时设定,供进度条估算总进度与剩余时间。
|
||||
# 前端是必需项:flutter 缺失或编译失败一律中断,不出只有 Avalonia 回退界面的包。
|
||||
# 确实要降级时用 ./build.sh build --allow-no-ui。
|
||||
#
|
||||
# 并行:Flutter 前端编译 与 C# 各 RID 发布 互不依赖,两组同时跑。
|
||||
|
||||
bs_build() {
|
||||
ROOT_DIR="$1"
|
||||
: "${APP_PROJ:?}" "${SLN:?}" "${VERSION:?}"
|
||||
# ---------------------------------------------------------------- 目标与权重
|
||||
|
||||
HOST=$(uname -s)
|
||||
BUILD_MAC=0
|
||||
BUILD_LINUX=0
|
||||
case "$HOST" in
|
||||
Darwin) BUILD_MAC=1 ;;
|
||||
MINGW*|MSYS*|CYGWIN*) : ;; # Windows 主机只能编 Windows
|
||||
*) BUILD_LINUX=1 ;;
|
||||
_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
|
||||
# Linux 产物默认不出:目标平台是 linux-arm64,而官方 Flutter 引擎只发 x64 产物,
|
||||
# x64 主机上编出来的是 x64 二进制,装到 arm 机器上跑不起来。
|
||||
# 需要时显式开启(云端 aarch64 runner):GC_BUILD_LINUX=1 ./build.sh build
|
||||
if [ "$BUILD_LINUX" = 1 ]; then
|
||||
case "${GC_BUILD_LINUX:-0}" in
|
||||
1|true|yes)
|
||||
case "$(uname -m)" in
|
||||
aarch64|arm64) ;;
|
||||
*)
|
||||
BUILD_LINUX=0
|
||||
echo "!! 已请求 Linux 产物,但当前主机是 $(uname -m)"
|
||||
echo " (linux-arm64 需要有 aarch64 主机,Flutter 引擎只有 x64 官方产物)"
|
||||
;;
|
||||
esac
|
||||
;;
|
||||
*)
|
||||
BUILD_LINUX=0
|
||||
echo "==> 跳过 Linux 产物(默认不构建;需要时用 GC_BUILD_LINUX=1 显式开启)"
|
||||
;;
|
||||
GC_HOST="$_host"
|
||||
|
||||
_want="${GC_TARGETS:-}"
|
||||
if [ -z "$_want" ]; then
|
||||
case "$_host" in
|
||||
mac) _want="mac,win" ;;
|
||||
windows) _want="win" ;;
|
||||
*) _want="win" ;;
|
||||
esac
|
||||
fi
|
||||
|
||||
# 显式降级:允许在没有该平台 Flutter 宿主的情况下仍出 Avalonia 版包
|
||||
ALLOW_NO_UI="${GC_ALLOW_NO_UI:-0}"
|
||||
|
||||
# 权重:清理 版本 Mac WinX64 WinArm64 Linux 前端 骨架 打包 收尾
|
||||
WEIGHTS="2 3"
|
||||
[ "$BUILD_MAC" = 1 ] && WEIGHTS="$WEIGHTS 35"
|
||||
WEIGHTS="$WEIGHTS 25 25"
|
||||
[ "$BUILD_LINUX" = 1 ] && WEIGHTS="$WEIGHTS 30"
|
||||
WEIGHTS="$WEIGHTS 25 3 5 2"
|
||||
TOTAL=0
|
||||
for _w in $WEIGHTS; do TOTAL=$((TOTAL + _w)); done
|
||||
|
||||
progress_init "$TOTAL" $WEIGHTS
|
||||
|
||||
progress_step "清理旧产物"; progress_tick 100
|
||||
rm -rf "$ROOT_DIR/dist"; mkdir -p "$ROOT_DIR/dist"
|
||||
# 上次打包挪出来的中间产物(.app 目录,体积大、文件多)直接移出 build,
|
||||
# 不做递归删除:避免动辄几百个文件的不可逆删除。
|
||||
if [ -d "$ROOT_DIR/build/trash" ]; then
|
||||
mv "$ROOT_DIR/build/trash" "${TMPDIR:-/tmp}/gc-trash-$(date +%s)" 2>/dev/null || true
|
||||
fi
|
||||
|
||||
progress_step "版本戳"; progress_tick 100
|
||||
# 末次签名:这里只生成清单不签名,等 pack_launcher 打完 zip、刷新完包信息后统一签一次。
|
||||
# 避免 ECDSA 随机签名 + 时间戳导致清单在中间反复变化。
|
||||
stamp_versions --no-sign
|
||||
|
||||
# 每个 publish 用后台任务包裹,边跑边按「已用时/预估用时」推进当前步骤进度
|
||||
_run_publish() {
|
||||
_label="$1"; _est="$2"; shift 2
|
||||
( "$@" >"$ROOT_DIR/build/logs/publish-$_label.log" 2>&1 ) &
|
||||
_pid=$!
|
||||
_t0=$(date +%s)
|
||||
while kill -0 "$_pid" 2>/dev/null; do
|
||||
_elapsed=$(( $(date +%s) - _t0 ))
|
||||
_p=$(( _elapsed * 100 / _est ))
|
||||
[ "$_p" -gt 96 ] && _p=96
|
||||
progress_tick "$_p"
|
||||
sleep 1
|
||||
done
|
||||
wait "$_pid" || { echo; echo "!! $_label 编译失败,见 build/logs/publish-$_label.log"; return 1; }
|
||||
progress_tick 100
|
||||
}
|
||||
|
||||
if [ "$BUILD_MAC" = 1 ]; then
|
||||
progress_step "编译 Mac"
|
||||
_run_publish mac 90 publish_rid "osx-arm64" "dist/mac-arm64" true || return 1
|
||||
# Flutter 的 macOS 产物必须用 Xcode 在本机编,Linux 上无法替代
|
||||
build_flutter_ui macos "dist/mac-arm64" || {
|
||||
echo "!! macOS 前端编译失败。macOS 版 Flutter 只能在 macOS 上编。"
|
||||
return 1
|
||||
}
|
||||
elif [ "$ALLOW_NO_UI" = 1 ]; then
|
||||
progress_step "编译 Mac"
|
||||
_run_publish mac 90 publish_rid "osx-arm64" "dist/mac-arm64" true || return 1
|
||||
echo "!! --allow-no-ui:macOS 包内不含 Flutter 前端,启动器将回退 Avalonia"
|
||||
fi
|
||||
|
||||
progress_step "编译 Win-x64"
|
||||
_run_publish winx64 70 publish_rid "win-x64" "dist/win-amd64" true || return 1
|
||||
|
||||
progress_step "编译 Win-arm64"
|
||||
_run_publish winarm 70 publish_rid "win-arm64" "dist/win-arm64" true || return 1
|
||||
|
||||
if [ "$BUILD_LINUX" = 1 ]; then
|
||||
progress_step "编译 Linux"
|
||||
_run_publish linux 70 publish_rid "linux-arm64" "dist/linux-arm64" true || return 1
|
||||
build_flutter_ui linux "dist/linux-arm64" || return 1
|
||||
fi
|
||||
|
||||
# Windows 前端:Windows 主机走官方 toolchain;Linux/macOS 主机用 mingw-w64 +
|
||||
# wine 交叉编译(buildsh/cross)。只产出 x64 一份,两个包共用,
|
||||
# ARM64 上由系统模拟 x64 进程运行前端。
|
||||
progress_step "编译 Win 前端"
|
||||
case "$HOST" in
|
||||
MINGW*|MSYS*|CYGWIN*) build_flutter_ui windows "dist/win-flutter" || return 1 ;;
|
||||
*) build_flutter_ui_cross "dist/win-flutter" || return 1 ;;
|
||||
esac
|
||||
for label in win-amd64 win-arm64; do
|
||||
cp -R "$ROOT_DIR/dist/win-flutter/." "$ROOT_DIR/dist/$label/"
|
||||
_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
|
||||
rm -rf "$ROOT_DIR/dist/win-flutter"
|
||||
IFS=$_ifs
|
||||
|
||||
progress_step "运行骨架"; progress_tick 100
|
||||
if [ -d "$ROOT_DIR/dist/mac-arm64" ]; then
|
||||
package_mac_app
|
||||
if [ "$BUILD_MAC" = 1 ] && [ "$_host" != mac ]; then
|
||||
err "macOS 产物只能在 macOS 上编译(当前 $(uname -s))"; return 1
|
||||
fi
|
||||
prepare_runtime_layout "dist/win-amd64"
|
||||
prepare_runtime_layout "dist/win-arm64"
|
||||
|
||||
# Linux 产物:必须是 aarch64 主机且显式开启
|
||||
if [ "$BUILD_LINUX" = 1 ]; then
|
||||
prepare_runtime_layout "dist/linux-arm64"
|
||||
fi
|
||||
if [ -d "$ROOT_DIR/dist/mac-arm64/GC.app/Contents/MacOS" ]; then
|
||||
prepare_runtime_layout "dist/mac-arm64/GC.app/Contents/MacOS"
|
||||
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
|
||||
|
||||
progress_step "打包 zip"; progress_tick 100
|
||||
pack_launcher
|
||||
# 发布计划: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"
|
||||
|
||||
progress_step "收尾"; progress_tick 100
|
||||
[ -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 52" # 准备 / 编译发布
|
||||
[ "$BUILD_WIN" = 1 ] && _ws="$_ws 8" # Win 前端交叉编译
|
||||
_ws="$_ws 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
|
||||
_e=$((_n * 70))
|
||||
[ "$BUILD_MAC" = 1 ] && _e=$((_e + 60))
|
||||
printf '%s' "$_e"
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------- 脚本自检
|
||||
|
||||
# `$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 发布 + macOS 前端:两条链互不依赖,同时进行
|
||||
_phase_compile() {
|
||||
_fbg=""
|
||||
if [ "$BUILD_MAC" = 1 ]; then
|
||||
# 后台编前端;GC_QUIET 避免它的输出打乱进度条
|
||||
( GC_QUIET=1; flutter_build macos ) &
|
||||
_fbg=$!
|
||||
fi
|
||||
|
||||
_rc=0
|
||||
for _t in $_PLAN; do
|
||||
publish_rid "${_t%%:*}" "${_t##*:}" || { _rc=1; break; }
|
||||
done
|
||||
|
||||
if [ -n "$_fbg" ]; then
|
||||
if [ "$_rc" != 0 ]; then
|
||||
kill "$_fbg" 2>/dev/null || true
|
||||
else
|
||||
if wait "$_fbg"; then
|
||||
flutter_stage macos "$GC_STAGE/mac-arm64" || _rc=1
|
||||
else
|
||||
err "Flutter macOS 前端编译失败(日志:build/logs/flutter-macos.log)"
|
||||
_rc=1
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
return "$_rc"
|
||||
}
|
||||
|
||||
# Windows 前端:只产出一份 x64,两个包共用(ARM64 上由系统模拟 x64 进程运行)。
|
||||
# Windows 主机走官方 toolchain,其它主机走 mingw + wine 交叉编译。
|
||||
_phase_win_ui() {
|
||||
if [ "$GC_HOST" = windows ]; then
|
||||
( GC_QUIET=1; build_flutter_ui windows "$GC_STAGE/win-flutter" ) || return 1
|
||||
else
|
||||
build_flutter_ui_cross "$GC_STAGE/win-flutter" || return 1
|
||||
fi
|
||||
for _l in win-amd64 win-arm64; do
|
||||
[ -d "$GC_STAGE/$_l" ] || continue
|
||||
cp -R "$GC_STAGE/win-flutter/." "$GC_STAGE/$_l/" || return 1
|
||||
done
|
||||
_trash "$GC_STAGE/win-flutter"
|
||||
}
|
||||
|
||||
_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 发布 ‖ Flutter mac 前端
|
||||
progress_step "编译"
|
||||
_run_phase "$(_est_compile)" _phase_compile || return 1
|
||||
|
||||
# ---- Windows 前端(mac 前端编完后才启动,避免两个 flutter 抢 SDK 锁)
|
||||
if [ "$BUILD_WIN" = 1 ]; then
|
||||
progress_step "Win 前端"
|
||||
_run_phase 70 _phase_win_ui || return 1
|
||||
fi
|
||||
|
||||
# ---- 组装:运行目录布局 + 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
|
||||
echo "==> 完成,产物:"
|
||||
ls -lh "$ROOT_DIR"/dist/*/GCL-"$VERSION"-*.zip 2>/dev/null || true
|
||||
_summary
|
||||
}
|
||||
+28
-29
@@ -1,46 +1,45 @@
|
||||
#!/bin/sh
|
||||
# buildsh/check.sh —— 验证:编译 + 自检 + 离屏测试 + 产物完整性
|
||||
# 步骤权重:编译(40) 自检(15) 离屏(25) 产物(20)
|
||||
# buildsh/check.sh —— 验证:编译 + 产物完整性
|
||||
#
|
||||
# 原先的「模型自检」和「离屏渲染」两项都依赖 Avalonia 界面与截图工程;
|
||||
# 界面与模型渲染迁到 Flutter 之后它们已经没有意义 —— 前端正确性交给
|
||||
# `flutter analyze`,这里只保证 C# 侧编译干净、发布包齐备。
|
||||
#
|
||||
# 步骤权重:编译(60) 产物(40)
|
||||
|
||||
bs_check() {
|
||||
ROOT_DIR="$1"
|
||||
progress_init 100 40 15 25 20
|
||||
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 dotnet build "$SLN" -c Debug -v quiet >"$ROOT_DIR/build/logs/check-build.log" 2>&1; then
|
||||
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
|
||||
progress_tick 100; _fail=1
|
||||
echo; echo "!! 编译失败,见 build/logs/check-build.log"
|
||||
_fail=1; progress_tick 100
|
||||
fi
|
||||
|
||||
progress_step "模型自检"
|
||||
if EMS_SELFTEST=1 dotnet run --project "$APP_PROJ" -c Debug --no-build \
|
||||
>"$ROOT_DIR/build/logs/check-selftest.log" 2>&1; then
|
||||
grep -q "FAIL" "$ROOT_DIR/build/logs/check-selftest.log" && { _fail=1; echo; echo "!! 自检有失败项"; }
|
||||
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; echo; echo "!! 自检异常"
|
||||
_fail=1; warn "dist 下没有发布包(先跑 ./build.sh build)"
|
||||
fi
|
||||
progress_tick 100
|
||||
|
||||
progress_step "离屏渲染"
|
||||
if dotnet run --project "$TEST_PROJ" -c Debug --no-build -- \
|
||||
"$ROOT_DIR/build/screenshots" >"$ROOT_DIR/build/logs/check-render.log" 2>&1; then
|
||||
progress_tick 100
|
||||
else
|
||||
_fail=1; progress_tick 100; echo; echo "!! 离屏渲染失败"
|
||||
fi
|
||||
|
||||
progress_step "产物检查"
|
||||
_n=$(ls "$ROOT_DIR"/dist/*/GC-"$VERSION"-*.zip 2>/dev/null | wc -l | tr -d ' ')
|
||||
if [ "$_n" -ge 3 ]; then
|
||||
progress_tick 100
|
||||
else
|
||||
_fail=1; progress_tick 100; echo; echo "!! 产物不足 3 个(当前 $_n)"
|
||||
fi
|
||||
|
||||
progress_done
|
||||
[ "$_fail" -eq 0 ] && echo "==> 全部通过" || echo "==> 有失败项"
|
||||
if [ "$_fail" -eq 0 ]; then
|
||||
step_ok "全部通过"
|
||||
else
|
||||
err "有失败项"
|
||||
fi
|
||||
return "$_fail"
|
||||
}
|
||||
@@ -87,7 +87,7 @@ resolve_flutter() {
|
||||
# pubspec 要求 Dart 3.5+(Flutter 3.24+),版本不对直接提醒
|
||||
local dart_ver
|
||||
dart_ver=$("$root/bin/cache/dart-sdk/bin/dart" --version 2>/dev/null | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1) || dart_ver=""
|
||||
say "Flutter SDK: $root(engine ${ENGINE_HASH:0:10}${dart_ver:+, dart $dart_ver})"
|
||||
say "Flutter SDK: ${root}(engine ${ENGINE_HASH:0:10}${dart_ver:+, dart $dart_ver})"
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------- 引擎产物
|
||||
@@ -96,14 +96,18 @@ ENGINE_DIR="" # 由 resolve_flutter 填充
|
||||
|
||||
fetch_engine() {
|
||||
local base="$MIRROR/flutter/$ENGINE_HASH"
|
||||
local cache="${TMPDIR:-/tmp}/gc-win-engine"
|
||||
# 缓存放仓库内 build/cache(原来放 ${TMPDIR},系统会清理,导致每次构建都重下 200MB+)
|
||||
local cache="${GC_WIN_ENGINE_CACHE:-$ROOT_DIR/build/cache/win-engine}"
|
||||
mkdir -p "$cache" 2>/dev/null || cache="${TMPDIR:-/tmp}/gc-win-engine"
|
||||
mkdir -p "$cache"
|
||||
|
||||
# 每个条目:远端相对路径 | 落地目录 | 落地后的标志文件
|
||||
# 注意 flutter-cpp-client-wrapper.zip 内部已经带一层 cpp_client_wrapper/,
|
||||
# 所以落地目录只能是 windows-x64,否则会解成 cpp_client_wrapper/cpp_client_wrapper。
|
||||
local -a items=(
|
||||
"windows-x64-release/windows-x64-flutter.zip|$ENGINE_DIR/windows-x64-release|flutter_windows.dll.lib"
|
||||
"windows-x64/artifacts.zip|$ENGINE_DIR/windows-x64|frontend_server_aot.dart.snapshot"
|
||||
"windows-x64/flutter-cpp-client-wrapper.zip|$ENGINE_DIR/windows-x64/cpp_client_wrapper|core_implementations.cc"
|
||||
"windows-x64/flutter-cpp-client-wrapper.zip|$ENGINE_DIR/windows-x64|cpp_client_wrapper/core_implementations.cc"
|
||||
)
|
||||
|
||||
local item remote dest marker zip
|
||||
@@ -114,7 +118,11 @@ fetch_engine() {
|
||||
zip="$cache/$(echo "$remote" | tr '/' '_')"
|
||||
if [ ! -s "$zip" ]; then
|
||||
say "下载 $(basename "$remote")"
|
||||
curl -fL --retry 3 --retry-delay 2 -o "$zip.part" "$base/$remote" \
|
||||
# -C - 断点续传:中断后重跑接着下,不从头开始
|
||||
# --speed-limit/--speed-time:网速掉到 4KB/s 持续 30 秒就放弃重试,避免无限挂住
|
||||
curl -fL -sS -C - --retry 5 --retry-delay 2 \
|
||||
--connect-timeout 20 --speed-limit 4096 --speed-time 30 \
|
||||
-o "$zip.part" "$base/$remote" \
|
||||
|| die "下载失败:$base/$remote
|
||||
可设置 WIN_ENGINE_MIRROR=https://storage.flutter-io.cn/flutter_infra_release 走国内镜像"
|
||||
mv "$zip.part" "$zip"
|
||||
|
||||
@@ -34,3 +34,14 @@ set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)
|
||||
# 和系统 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")
|
||||
|
||||
# 强制 C++17,避免 GCC 16 的 C++20 三路比较问题
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||
|
||||
# 兼容 mingw-w64 14 + GCC 16 的问题
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++17 -Wno-error -D__STDC_CONSTANT_MACROS")
|
||||
+14
-491
@@ -1,494 +1,17 @@
|
||||
#!/bin/sh
|
||||
# buildsh/lib/build_funcs.sh —— 构建函数库(由入口脚本 source)
|
||||
# 依赖调用方提供:ROOT_DIR, APP_PROJ, PREVIEW_PROJ, STAMP_PROJ, TEST_PROJ, SLN, VERSION
|
||||
# 以及任务进度上报函数 step / progress(由进度条引擎提供,未定义时降级为 echo)
|
||||
|
||||
if ! type step >/dev/null 2>&1; then step() { echo "==> $1"; }; fi
|
||||
if ! type progress >/dev/null 2>&1; then progress() { :; }; fi
|
||||
|
||||
# $1=--no-sign 时只生成清单、不签名。
|
||||
# 完整 build 会在 pack_launcher 末尾统一签一次(末次签名),中间这次签名是浪费的:
|
||||
# ECDSA 用随机 nonce + signedAt 时间戳,每次签名字节都不同,白白多一次全量签名,
|
||||
# 也让中间产物反复抖动。单独的 stamp / models 工具没有后续打包,仍走默认签名。
|
||||
stamp_versions() {
|
||||
echo "==> 自动计算模型版本并生成 version.json"
|
||||
dotnet run --project "$STAMP_PROJ" -c Release -- "$ROOT_DIR" "$VERSION"
|
||||
case "${1:-}" in
|
||||
--no-sign) echo " (跳过签名,打包结束后统一签一次)" ;;
|
||||
*) sign_manifest ;;
|
||||
esac
|
||||
}
|
||||
|
||||
# 打完 zip 之后刷新 launcher.packages(写入 path / dir / name / sha256 / size)。
|
||||
# 只重写清单的启动器段:模型指纹可能涉及几百 MB 文件,没必要再算一遍。
|
||||
stamp_launcher_only() {
|
||||
echo "==> 刷新启动器包信息(sha256 / 体积 / dist 路径)"
|
||||
dotnet run --project "$STAMP_PROJ" -c Release -- "$ROOT_DIR" "$VERSION" --launcher-only
|
||||
sign_manifest
|
||||
}
|
||||
|
||||
# 用 .signing/ 里的私钥给 version.json 签名(私钥不入库)。
|
||||
# 没有私钥时只警告:清单不带 signature,客户端会按「未签名」处理。
|
||||
sign_manifest() {
|
||||
KEY="$ROOT_DIR/.signing/gc-signing.pem"
|
||||
KEYID="${GC_SIGNING_KEY_ID:-gc-2026-12}"
|
||||
if [ ! -f "$KEY" ]; then
|
||||
echo "!! 未找到签名私钥 ${KEY},本次 version.json 未签名(客户端会拒绝更新)"
|
||||
echo " 生成密钥:dotnet run --project GC-SAVEDOG -- keygen"
|
||||
return 0
|
||||
fi
|
||||
echo "==> 签名 version.json(${KEYID})"
|
||||
if dotnet run --project "$ROOT_DIR/GC-SAVEDOG/GC-SAVEDOG.csproj" -c Release -- \
|
||||
sign --manifest "$ROOT_DIR/version.json" --key "$KEY" --key-id "$KEYID"; then
|
||||
# model/version.json 必须与根清单完全一致(同一个签名),否则走 model 地址的源会验签失败
|
||||
cp "$ROOT_DIR/version.json" "$ROOT_DIR/model/version.json"
|
||||
else
|
||||
echo "!! 签名失败,version.json 保持未签名状态"
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
# 编译模型自己的功能程序集,并把 dll / 封面直接写进模型包
|
||||
build_models() {
|
||||
echo "==> 编译模型功能程序集(源码就在各模型目录的 src/ 里)"
|
||||
for DIR in "$ROOT_DIR"/model/*/; do
|
||||
ID=$(basename "$DIR")
|
||||
[ -d "$DIR/src" ] || continue
|
||||
PROJ=$(ls "$DIR"src/*.csproj 2>/dev/null | head -1)
|
||||
[ -n "$PROJ" ] || continue
|
||||
dotnet build "$PROJ" -c Release
|
||||
if [ -d "$DIR$ID.model" ]; then
|
||||
for DLL in "$DIR"src/bin/Release/net8.0/*.dll; do
|
||||
[ -f "$DLL" ] || continue
|
||||
NAME=$(basename "$DLL")
|
||||
[ "$NAME" = "GC.ModelSdk.dll" ] && continue
|
||||
cp "$DLL" "$DIR$ID.model/"
|
||||
echo " -> model/$ID/$ID.model/$NAME"
|
||||
done
|
||||
fi
|
||||
done
|
||||
echo "==> 用模型自己的渲染器生成封面"
|
||||
dotnet run --project "$PREVIEW_PROJ" -c Release -- "$ROOT_DIR"
|
||||
stamp_versions
|
||||
}
|
||||
|
||||
# 发布目录只放程序本体:不预置 .GC,也不放模型。
|
||||
# .GC(config / model / cache / update / safedog / logs)一律在首次启动时
|
||||
# 由 AppPaths.EnsureCreated + RuntimeLayout 创建,压缩包里只有 GC 本体。
|
||||
prepare_runtime_layout() {
|
||||
REL="$1"
|
||||
DEST="$ROOT_DIR/$REL"
|
||||
[ -d "$DEST" ] || return 0
|
||||
rm -rf "$DEST/model" "$DEST/examples" "$DEST/.GC"
|
||||
echo " 运行目录 -> $REL(首次启动后生成 .GC/:config model cache update safedog logs)"
|
||||
}
|
||||
|
||||
# 剔除与目标平台无关 / 只在调试诊断时才会加载的组件。
|
||||
# 判定依据:Windows 包用 Kestrel 自托管,不经过 IIS/HttpSys;Avalonia 在 Windows
|
||||
# 上只用 Win32 后端;DAC/DBI/DiaSymReader 只有调试器与读 PDB 时才需要,
|
||||
# 而发布包 DebugType=none、不带 PDB。全都不在启动与正常运行路径上。
|
||||
prune_package() {
|
||||
DEST="$1"; PLAT="$2"
|
||||
[ -d "$DEST" ] || return 0
|
||||
case "$PLAT" in
|
||||
win)
|
||||
# ProjectReference 会把后端 exe 的 runtimeconfig 一起拷过来;后端已编入启动器,
|
||||
# 这些残留没有用。
|
||||
rm -f "$DEST"/GC.UI.Server.exe "$DEST"/GC.UI.Server.dll \
|
||||
"$DEST"/GC.UI.Server.deps.json "$DEST"/GC.UI.Server.runtimeconfig.json
|
||||
rm -f "$DEST"/mscordaccore*.dll \
|
||||
"$DEST"/mscordbi.dll \
|
||||
"$DEST"/Microsoft.DiaSymReader.Native*.dll \
|
||||
"$DEST"/web.config \
|
||||
"$DEST"/aspnetcorev2_inprocess.dll \
|
||||
"$DEST"/Microsoft.AspNetCore.Server.IIS.dll \
|
||||
"$DEST"/Microsoft.AspNetCore.Server.IISIntegration.dll \
|
||||
"$DEST"/Microsoft.AspNetCore.Server.HttpSys.dll \
|
||||
"$DEST"/Avalonia.X11.dll \
|
||||
"$DEST"/Avalonia.Native.dll \
|
||||
"$DEST"/Avalonia.FreeDesktop.dll \
|
||||
"$DEST"/Tmds.DBus.Protocol.dll
|
||||
;;
|
||||
linux)
|
||||
rm -f "$DEST"/mscordaccore*.dll \
|
||||
"$DEST"/mscordbi.dll \
|
||||
"$DEST"/Microsoft.DiaSymReader.Native*.dll \
|
||||
"$DEST"/web.config \
|
||||
"$DEST"/aspnetcorev2_inprocess.dll \
|
||||
"$DEST"/Microsoft.AspNetCore.Server.IIS.dll \
|
||||
"$DEST"/Microsoft.AspNetCore.Server.IISIntegration.dll \
|
||||
"$DEST"/Microsoft.AspNetCore.Server.HttpSys.dll \
|
||||
"$DEST"/Avalonia.Win32.dll \
|
||||
"$DEST"/Avalonia.Win32.Automation.dll
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
# $1=RID $2=输出目录 $3=singlefile(true/false)
|
||||
publish_rid() {
|
||||
RID="$1"; OUT="$2"; SINGLE="${3:-true}"
|
||||
echo ""
|
||||
echo "==> 编译 ${RID} (single-file=${SINGLE}) -> ${OUT}"
|
||||
# 先删旧产物,避免上次 publish 的残留文件混进新包
|
||||
rm -rf "$ROOT_DIR/$OUT"
|
||||
dotnet publish "$APP_PROJ" \
|
||||
-c Release \
|
||||
-r "$RID" \
|
||||
--self-contained true \
|
||||
-p:Version="$VERSION" \
|
||||
-p:DebugType=none \
|
||||
-p:PublishSingleFile="$SINGLE" \
|
||||
-p:IncludeNativeLibrariesForSelfExtract="$SINGLE" \
|
||||
-p:EnableCompressionInSingleFile="$SINGLE" \
|
||||
-p:PublishTrimmed=false \
|
||||
-o "$ROOT_DIR/$OUT" || return 1
|
||||
|
||||
# 更新守护进程:与主程序同目录(macOS 打包时会被一起移入 Contents/MacOS)
|
||||
if [ -n "${SAVEDOG_PROJ:-}" ] && [ -f "$ROOT_DIR/$SAVEDOG_PROJ" ]; then
|
||||
echo "==> 编译 GC-SAVEDOG (${RID}) -> ${OUT}(裁剪 + 压缩单文件)"
|
||||
# 守护进程不引用 Avalonia,可以安全裁剪:70MB -> 14MB。
|
||||
# 前提是 JSON 全部走源生成上下文(GC-SAVEDOG/SavedogJson.cs),新增 JSON 类型
|
||||
# 忘了注册只会在发布产物里炸,所以 update-test 会跑一次真实 apply 兜底。
|
||||
# EnableCompressionInSingleFile:运行时不常驻,启动时解压一次即可,
|
||||
# 换来包内少 4MB 左右,对「下载一次、只在更新时跑」的守护进程很划算。
|
||||
dotnet publish "$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 \
|
||||
-o "$ROOT_DIR/$OUT"
|
||||
fi
|
||||
|
||||
rm -rf "$ROOT_DIR/$OUT/model" "$ROOT_DIR/$OUT/examples"
|
||||
}
|
||||
|
||||
# 把 model/ 里的模型数据单独打包(与启动器分开分发)
|
||||
pack_models() {
|
||||
mkdir -p "$ROOT_DIR/dist"
|
||||
ZIP="$ROOT_DIR/dist/models-$VERSION.zip"
|
||||
rm -f "$ZIP"
|
||||
echo "==> 打包模型数据 -> dist/models-$VERSION.zip"
|
||||
( cd "$ROOT_DIR" && zip -qrX "$ZIP" model \
|
||||
-x "*.DS_Store" "*/bin/*" "*/obj/*" "*.user" )
|
||||
du -sh "$ZIP"
|
||||
}
|
||||
|
||||
# 启动器更新包:安装目录根只放 GC 本体;非本体文件(守护进程等)收进 .GC/bin。
|
||||
# .GC 下的用户数据(config / model / cache / update / logs / safedog)不进包。
|
||||
# buildsh/lib/build_funcs.sh —— 兼容入口
|
||||
#
|
||||
# 产物落点遵循「仓库 dist/<系统>-<架构>/」布局:
|
||||
# dist/mac-arm64/GCL-<版本>-mac-arm64.zip
|
||||
# dist/win-amd64/GCL-<版本>-win-amd64.zip
|
||||
# dist/win-arm64/GCL-<版本>-win-arm64.zip
|
||||
# dist/linux-arm64/GCL-<版本>-linux-arm64.zip
|
||||
# 启动器更新时既可以从 Release 附件下载,也会到这些目录里找编译产物
|
||||
# (见 GC-DOWNLOAD/LauncherArtifacts.cs),所以两种发布方式都能用。
|
||||
# 原先是单文件函数库,现按职责拆成:
|
||||
# log.sh 输出层(say / step_ok / note / detail / warn / err / run_logged)
|
||||
# progress.sh 进度显示(终端进度条 / 非终端逐行)
|
||||
# publish.sh 环境预检、工具程序集缓存、dotnet 发布、阶段执行
|
||||
# core.sh 版本清单、签名、模型构建
|
||||
# flutter.sh Flutter 构建与落位
|
||||
# package.sh 组装 .app、生成发布 zip
|
||||
#
|
||||
# Windows: 单文件 exe 直接改名(本身就是可执行产物)
|
||||
# macOS: .app 必须打成 zip 才能作为单文件分发;文件名用 .app.zip,
|
||||
# 这样 macOS 双击会用归档工具解压出可运行的 .app。
|
||||
# 若直接命名 .app,系统会把 zip 当成应用包解析 => 报「已损坏/打不开」。
|
||||
# 当前主机原生构建 Flutter 前端(Windows 主机编 Windows,macOS 主机编 macOS,
|
||||
# Linux 主机编 Linux)。跨平台的 Windows 版由 build_flutter_ui_cross 负责。
|
||||
#
|
||||
# 默认「必须有前端」:缺 flutter 或编译失败直接返回非 0,让 build.sh 停下来说明
|
||||
# 原因,而不是悄悄出一个只有 Avalonia 回退界面的包。确实需要降级时用
|
||||
# ./build.sh build --allow-no-ui 显式声明。
|
||||
build_flutter_ui() {
|
||||
PLAT="$1"; DEST="$2"
|
||||
UI_SRC="$ROOT_DIR/GC-UI/frontend"
|
||||
if [ ! -d "$UI_SRC" ]; then
|
||||
echo "!! 找不到 Flutter 工程:$UI_SRC"
|
||||
return 1
|
||||
fi
|
||||
|
||||
FLUTTER_BIN="${FLUTTER_BIN:-flutter}"
|
||||
if ! command -v "$FLUTTER_BIN" >/dev/null 2>&1; then
|
||||
echo "!! 未找到 flutter(可用 FLUTTER_BIN=<路径> 指定)"
|
||||
return 1
|
||||
fi
|
||||
|
||||
echo "==> 构建 Flutter 前端 (${PLAT})"
|
||||
( cd "$UI_SRC" && "$FLUTTER_BIN" pub get && "$FLUTTER_BIN" build "$PLAT" --release ) || return 1
|
||||
|
||||
mkdir -p "$ROOT_DIR/$DEST"
|
||||
case "$PLAT" in
|
||||
windows)
|
||||
# Release/ 里含 GC-UI.exe、flutter_windows.dll 和 data/
|
||||
cp -R "$UI_SRC/build/windows/x64/runner/Release/." "$ROOT_DIR/$DEST/"
|
||||
;;
|
||||
macos)
|
||||
rm -rf "$ROOT_DIR/$DEST/GC-UI.app"
|
||||
cp -R "$UI_SRC/build/macos/Build/Products/Release/GC-UI.app" "$ROOT_DIR/$DEST/"
|
||||
;;
|
||||
linux)
|
||||
# bundle/ 里是 GC-UI、lib/*.so 与 data/,整体铺到包的根目录。
|
||||
# 目录名跟着目标架构走:aarch64 主机在 build/linux/arm64/,x64 在 build/linux/x64/。
|
||||
BUNDLE=""
|
||||
for cand in "$UI_SRC/build/linux/arm64/release/bundle" \
|
||||
"$UI_SRC/build/linux/x64/release/bundle"; do
|
||||
[ -d "$cand" ] && BUNDLE="$cand" && break
|
||||
done
|
||||
if [ -z "$BUNDLE" ]; then
|
||||
echo "!! 找不到 Flutter Linux bundle(期望 build/linux/{arm64,x64}/release/bundle)"
|
||||
return 1
|
||||
fi
|
||||
# 目标包是 arm64,却只编出 x64 bundle:说明主机架构不对,宁可失败也不出坏包
|
||||
case "$BUNDLE" in
|
||||
*/arm64/*) ;;
|
||||
*)
|
||||
if [ "$(uname -m)" != "aarch64" ] && [ "$(uname -m)" != "arm64" ]; then
|
||||
echo "!! Linux 包目标为 arm64,但当前主机 $(uname -m) 只能编出 x64 前端"
|
||||
return 1
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
cp -R "$BUNDLE/." "$ROOT_DIR/$DEST/"
|
||||
;;
|
||||
*)
|
||||
echo "!! 不支持的 Flutter 目标平台:$PLAT"
|
||||
return 1
|
||||
;;
|
||||
esac
|
||||
echo " -> $DEST(Flutter ${PLAT})"
|
||||
}
|
||||
|
||||
# 在 Linux / macOS 上交叉编译 Windows 前端:mingw-w64 编 C++ 外壳,
|
||||
# wine 跑 Windows 版 gen_snapshot 生成 AOT 快照,无需 Windows 机器。
|
||||
# 产物布局与官方 toolchain 完全一致(GC-UI.exe + flutter_windows.dll + data/)。
|
||||
build_flutter_ui_cross() {
|
||||
DEST="$1"
|
||||
UI_SRC="$ROOT_DIR/GC-UI/frontend"
|
||||
[ -d "$UI_SRC" ] || return 0
|
||||
|
||||
FLUTTER_BIN="${FLUTTER_BIN:-flutter}"
|
||||
if ! command -v "$FLUTTER_BIN" >/dev/null 2>&1; then
|
||||
echo "!! 未找到 flutter(可用 FLUTTER_BIN=<路径> 指定)"
|
||||
return 1
|
||||
fi
|
||||
|
||||
mkdir -p "$ROOT_DIR/build/logs"
|
||||
echo "==> 交叉编译 Windows 前端(mingw-w64 + wine)"
|
||||
if ! FLUTTER_BIN="$FLUTTER_BIN" bash "$ROOT_DIR/buildsh/cross/build-ui-win-cross.sh" \
|
||||
"$UI_SRC/build/windows/x64/runner/Release" \
|
||||
>"$ROOT_DIR/build/logs/flutter-win-cross.log" 2>&1; then
|
||||
echo "!! 交叉编译失败(日志:build/logs/flutter-win-cross.log)"
|
||||
tail -5 "$ROOT_DIR/build/logs/flutter-win-cross.log" 2>/dev/null | sed 's/^/ /'
|
||||
return 1
|
||||
fi
|
||||
|
||||
mkdir -p "$ROOT_DIR/$DEST"
|
||||
cp -R "$UI_SRC/build/windows/x64/runner/Release/." "$ROOT_DIR/$DEST/"
|
||||
echo " -> $DEST(Flutter windows,交叉编译)"
|
||||
}
|
||||
|
||||
pack_launcher() {
|
||||
echo "==> 生成启动器产物(GCL-<版本>-<系统>-<架构>)"
|
||||
|
||||
# --- Windows:启动器 + 守护进程 + UI 后端 + Flutter 前端,整目录打包 ---
|
||||
for pair in "win-x64:win-amd64" "win-arm64:win-arm64"; do
|
||||
RID="${pair%%:*}"; LABEL="${pair##*:}"
|
||||
SRC="$ROOT_DIR/dist/$LABEL"
|
||||
[ -d "$SRC" ] || SRC="$ROOT_DIR/dist/$RID" # 兼容旧布局
|
||||
[ -d "$SRC" ] || continue
|
||||
|
||||
# 启动器固定是 GC.exe;后端与前端是可选的随包产物,不能当成启动器。
|
||||
EXE="$SRC/GC.exe"
|
||||
[ -f "$EXE" ] || EXE=$(ls "$SRC"/*.exe 2>/dev/null | grep -v 'GC-SAVEDOG\|GC.UI.Server\|GC-UI' | head -1)
|
||||
[ -n "$EXE" ] || continue
|
||||
|
||||
# 包内只有一个顶层目录(GCL-<版本>-<平台>),解压后不会散落一屏 dll。
|
||||
TMP="$ROOT_DIR/dist/.winpkg-$LABEL"
|
||||
PKGNAME="GCL-${VERSION}-${LABEL}"
|
||||
PKG="$TMP/$PKGNAME"
|
||||
rm -rf "$TMP"; mkdir -p "$PKG"
|
||||
cp -R "$SRC"/. "$PKG"/
|
||||
rm -f "$PKG"/*.zip
|
||||
prune_package "$PKG" win
|
||||
mv "$PKG/$(basename "$EXE")" "$PKG/$PKGNAME.exe"
|
||||
chmod +x "$PKG/$PKGNAME.exe" 2>/dev/null || true
|
||||
if [ ! -f "$PKG/GC-SAVEDOG.exe" ]; then
|
||||
echo " !! 缺少 GC-SAVEDOG.exe,该平台将退回旧脚本更新"
|
||||
else
|
||||
# 非本体文件统一收进 .GC/bin:安装目录根只留 GC 本体。
|
||||
# 首次启动复制到 .GC/safedog 再运行,所以这里的源文件更新时可安全替换。
|
||||
mkdir -p "$PKG/.GC/bin"
|
||||
mv "$PKG/GC-SAVEDOG.exe" "$PKG/.GC/bin/"
|
||||
fi
|
||||
if [ ! -f "$PKG/GC-UI.exe" ]; then
|
||||
echo " !! 包内没有 Flutter 前端,启动器将使用内置 Avalonia 界面"
|
||||
fi
|
||||
|
||||
ZIP="$ROOT_DIR/dist/$LABEL/$PKGNAME.zip"
|
||||
rm -f "$ZIP"
|
||||
( cd "$TMP" && zip -qrX "$ZIP" "$PKGNAME" )
|
||||
rm -rf "$TMP"
|
||||
echo " -> dist/$LABEL/$PKGNAME.zip"
|
||||
done
|
||||
|
||||
# --- Linux:整目录打包(启动器 + 守护 + 后端 + Flutter 前端)---
|
||||
SRC="$ROOT_DIR/dist/linux-arm64"
|
||||
if [ -d "$SRC" ]; then
|
||||
TMP="$ROOT_DIR/dist/.linuxpkg"
|
||||
PKGNAME="GCL-${VERSION}-linux-arm64"
|
||||
PKG="$TMP/$PKGNAME"
|
||||
rm -rf "$TMP"; mkdir -p "$PKG"
|
||||
cp -R "$SRC"/. "$PKG"/
|
||||
rm -f "$PKG"/*.zip
|
||||
prune_package "$PKG" linux
|
||||
if [ -f "$PKG/GC" ]; then
|
||||
mv "$PKG/GC" "$PKG/$PKGNAME"
|
||||
chmod +x "$PKG/$PKGNAME" 2>/dev/null || true
|
||||
fi
|
||||
if [ -f "$PKG/GC-SAVEDOG" ]; then
|
||||
mkdir -p "$PKG/.GC/bin"
|
||||
mv "$PKG/GC-SAVEDOG" "$PKG/.GC/bin/"
|
||||
fi
|
||||
if [ ! -f "$PKG/GC-UI" ]; then
|
||||
echo " !! 包内没有 Flutter 前端,启动器将使用内置 Avalonia 界面"
|
||||
fi
|
||||
ZIP="$ROOT_DIR/dist/linux-arm64/$PKGNAME.zip"
|
||||
rm -f "$ZIP"
|
||||
( cd "$TMP" && zip -qryX "$ZIP" "$PKGNAME" )
|
||||
rm -rf "$TMP"
|
||||
echo " -> dist/linux-arm64/$PKGNAME.zip"
|
||||
fi
|
||||
|
||||
# --- macOS:先得到真实 .app 目录(改名 + 同步 Info.plist)---
|
||||
MACAPP="$ROOT_DIR/dist/mac-arm64/GC.app"
|
||||
if [ -d "$MACAPP" ]; then
|
||||
FINAL="$ROOT_DIR/dist/GCL-${VERSION}-mac-arm64.app"
|
||||
rm -rf "$FINAL"
|
||||
mv "$MACAPP" "$FINAL"
|
||||
chmod +x "$FINAL/Contents/MacOS/GC" 2>/dev/null || true
|
||||
PLIST="$FINAL/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
|
||||
# 非本体文件收进 .GC/bin(与 Windows 布局一致):.GC 位置不变,仍在启动器同级
|
||||
# (也就是 .app/Contents/MacOS/),首次启动复制到 .GC/safedog 再运行。
|
||||
if [ -f "$FINAL/Contents/MacOS/GC-SAVEDOG" ]; then
|
||||
mkdir -p "$FINAL/Contents/MacOS/.GC/bin"
|
||||
mv "$FINAL/Contents/MacOS/GC-SAVEDOG" "$FINAL/Contents/MacOS/.GC/bin/"
|
||||
chmod +x "$FINAL/Contents/MacOS/.GC/bin/GC-SAVEDOG" 2>/dev/null || true
|
||||
fi
|
||||
xattr -cr "$FINAL" 2>/dev/null || true
|
||||
echo " -> $(basename "$FINAL")/"
|
||||
fi
|
||||
|
||||
# --- 统一压缩:每个产物都打成同名 .zip,放进自己的平台目录 ---
|
||||
# GCL-1.0.3-mac-arm64.app -> dist/mac-arm64/GCL-1.0.3-mac-arm64.zip
|
||||
# 客户端下载时按「原名去掉扩展名 + .zip」取包,再解压回原名。
|
||||
echo "==> 压缩为 zip"
|
||||
for art in "$ROOT_DIR"/dist/GCL-"$VERSION"-*.exe "$ROOT_DIR"/dist/GCL-"$VERSION"-*.app; do
|
||||
[ -e "$art" ] || continue
|
||||
base=$(basename "$art")
|
||||
name="${base%.*}" # 去掉 .exe / .app
|
||||
label="${name#GCL-${VERSION}-}" # mac-arm64 / win-amd64
|
||||
ZIP="$ROOT_DIR/dist/${label}/${name}.zip"
|
||||
mkdir -p "$ROOT_DIR/dist/${label}"
|
||||
rm -f "$ZIP"
|
||||
if [ -d "$art" ]; then
|
||||
# 目录(.app):保留权限与符号链接
|
||||
if command -v ditto >/dev/null 2>&1; then
|
||||
ditto -c -k --sequesterRsrc --keepParent "$art" "$ZIP"
|
||||
else
|
||||
( cd "$(dirname "$art")" && zip -qryX "$ZIP" "$base" -x "*.DS_Store" )
|
||||
fi
|
||||
else
|
||||
( cd "$(dirname "$art")" && zip -qX "$ZIP" "$base" )
|
||||
fi
|
||||
echo " -> dist/${label}/${name}.zip"
|
||||
done
|
||||
|
||||
# 原始产物(.exe / .app 目录)不再保留:只发布 zip。
|
||||
# 用「移入暂存区」而不是 rm -rf:.app 里有两百多个文件,
|
||||
# 一次性删除又慢又不可逆,先挪走更安全(暂存区在下次构建开始时挪出 dist)。
|
||||
TRASH="$ROOT_DIR/build/trash"
|
||||
mkdir -p "$TRASH"
|
||||
for leftover in "$ROOT_DIR"/dist/GCL-"$VERSION"-*.exe "$ROOT_DIR"/dist/GCL-"$VERSION"-*.app; do
|
||||
[ -e "$leftover" ] || continue
|
||||
mv "$leftover" "$TRASH/$(basename "$leftover")-$(date +%s)" 2>/dev/null || true
|
||||
done
|
||||
|
||||
strip_intermediate_dirs
|
||||
stamp_launcher_only
|
||||
echo ""
|
||||
echo "==> dist 里可发布的 zip:"
|
||||
ls -lh "$ROOT_DIR"/dist/*/GCL-"$VERSION"-*.zip 2>/dev/null || true
|
||||
}
|
||||
|
||||
# 删除 publish 过程中的中间目录:平台目录里只留最终 zip
|
||||
strip_intermediate_dirs() {
|
||||
for d in win-amd64 win-x64 win-arm64 mac-arm64 linux-arm64 linux-x64; do
|
||||
[ -d "$ROOT_DIR/dist/$d" ] || continue
|
||||
find "$ROOT_DIR/dist/$d" -mindepth 1 -maxdepth 1 \
|
||||
! -name "GCL-${VERSION}-*.zip" -exec rm -rf {} + 2>/dev/null || true
|
||||
done
|
||||
find "$ROOT_DIR/dist" -name ".DS_Store" -delete 2>/dev/null || true
|
||||
}
|
||||
|
||||
package_mac_app() {
|
||||
DIST="$ROOT_DIR/dist/mac-arm64"
|
||||
APP="$DIST/GC.app"
|
||||
rm -rf "$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/>
|
||||
</dict>
|
||||
</plist>
|
||||
PLIST
|
||||
for f in "$DIST"/*; do
|
||||
base=$(basename "$f")
|
||||
[ "$base" = "GC.app" ] && continue
|
||||
[ "$base" = ".DS_Store" ] && continue
|
||||
mv "$f" "$APP/Contents/MacOS/"
|
||||
done
|
||||
# 应用图标:由 Assets/icon-1024.png 生成 .icns
|
||||
ICONSRC="$ROOT_DIR/GC/src/Assets/icon-1024.png"
|
||||
if [ -f "$ICONSRC" ] && command -v iconutil >/dev/null 2>&1; then
|
||||
ICONSET="$DIST/AppIcon.iconset"
|
||||
rm -rf "$ICONSET"; mkdir -p "$ICONSET"
|
||||
for sz in 16 32 64 128 256 512; do
|
||||
sips -z $sz $sz "$ICONSRC" --out "$ICONSET/icon_${sz}x${sz}.png" >/dev/null 2>&1
|
||||
d=$((sz * 2))
|
||||
sips -z $d $d "$ICONSRC" --out "$ICONSET/icon_${sz}x${sz}@2x.png" >/dev/null 2>&1
|
||||
done
|
||||
iconutil -c icns "$ICONSET" -o "$APP/Contents/Resources/AppIcon.icns" 2>/dev/null && \
|
||||
echo " + AppIcon.icns"
|
||||
rm -rf "$ICONSET"
|
||||
# Info.plist 增加图标项
|
||||
if [ -f "$APP/Contents/Info.plist" ]; then
|
||||
/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(config / model / cache / update / logs):首次启动自行创建,
|
||||
# 包里只保留 .GC/bin 这一个由 pack_launcher 补上的非本体文件目录。
|
||||
rm -rf "$APP/Contents/MacOS/.GC"
|
||||
chmod +x "$APP/Contents/MacOS/GC"
|
||||
echo "==> 已打包 $APP"
|
||||
}
|
||||
|
||||
# 保留本文件是为了老的 `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 flutter package; do
|
||||
. "$_bf_root/buildsh/lib/$_bf_m.sh"
|
||||
done
|
||||
unset _bf_m _bf_root
|
||||
@@ -0,0 +1,75 @@
|
||||
#!/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
|
||||
}
|
||||
|
||||
# 模型已全部用 Flutter 实现(GC-UI/frontend/lib/models/),不再编译 C# 程序集,
|
||||
# 也不再需要 Avalonia 渲染引擎生成封面。这里只刷新清单里的模型指纹。
|
||||
build_models() {
|
||||
say "模型清单"
|
||||
note "模型渲染已迁到 Flutter,跳过 C# 程序集编译与封面生成"
|
||||
stamp_versions
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
#!/bin/sh
|
||||
# buildsh/lib/flutter.sh —— Flutter 前端构建与落位
|
||||
#
|
||||
# 分两步,便于和其它编译并行:
|
||||
# flutter_build <平台> 只编译,产物留在 GC-UI/frontend/build/
|
||||
# flutter_stage <平台> <目录> 把产物铺进打包目录
|
||||
#
|
||||
# 输出策略:flutter 的输出(尤其 macOS 上 flutter_inappwebview 那几百行 Swift
|
||||
# 弃用警告)全部进 build/logs/flutter-<平台>.log,成功时不显示,失败才回显尾部。
|
||||
|
||||
_ui_src() { printf '%s' "$GC_ROOT/GC-UI/frontend"; }
|
||||
|
||||
# pub get 只在 pubspec 变了才跑:package_config.json 比 pubspec.yaml / pubspec.lock
|
||||
# 都新就说明依赖已就绪,省掉每次构建的解析与 "Changed N dependencies!" 抖动
|
||||
_flutter_deps_ready() {
|
||||
_pc="$(_ui_src)/.dart_tool/package_config.json"
|
||||
[ -f "$_pc" ] && [ -f "$(_ui_src)/pubspec.lock" ] &&
|
||||
[ "$_pc" -nt "$(_ui_src)/pubspec.yaml" ] && [ "$_pc" -nt "$(_ui_src)/pubspec.lock" ]
|
||||
}
|
||||
|
||||
_flutter() { ( cd "$(_ui_src)" && "$FLUTTER_BIN" "$@" ); }
|
||||
|
||||
flutter_build() {
|
||||
_plat="$1"
|
||||
UI_SRC="$(_ui_src)"
|
||||
FLUTTER_BIN="${FLUTTER_BIN:-flutter}"
|
||||
|
||||
[ -d "$UI_SRC" ] || { err "找不到 Flutter 工程:GC-UI/frontend"; return 1; }
|
||||
command -v "$FLUTTER_BIN" >/dev/null 2>&1 ||
|
||||
{ err "未找到 flutter(可用 FLUTTER_BIN=<路径> 指定)"; return 1; }
|
||||
|
||||
say "编译 Flutter 前端(${_plat})"
|
||||
if _flutter_deps_ready; then
|
||||
detail "依赖已就绪,跳过 pub get"
|
||||
else
|
||||
run_logged "$GC_ROOT/build/logs/flutter-pubget.log" "pub get " \
|
||||
_flutter pub get || return 1
|
||||
fi
|
||||
|
||||
# 注意:macOS 的 `flutter build macos` 没有 --no-codesign 选项(那是 iOS 的),
|
||||
# 传了会直接报 "Could not find an option named no-codesign"。
|
||||
# macOS 模板默认用 ad-hoc 签名(CODE_SIGN_IDENTITY = "-"),无证书的 CI 也能构建出 .app,
|
||||
# 只是首次打开需要右键「打开」。
|
||||
run_logged "$GC_ROOT/build/logs/flutter-$_plat.log" "Flutter $_plat 构建 " \
|
||||
_flutter build "$_plat" --release || return 1
|
||||
step_ok "Flutter ${_plat}"
|
||||
}
|
||||
|
||||
# flutter_stage <平台> <目标目录(绝对路径)>
|
||||
flutter_stage() {
|
||||
_plat="$1"; _dest="$2"
|
||||
UI_SRC="$(_ui_src)"
|
||||
mkdir -p "$_dest"
|
||||
|
||||
case "$_plat" in
|
||||
windows)
|
||||
# Release/ 里含 GC-UI.exe、flutter_windows.dll 和 data/
|
||||
cp -R "$UI_SRC/build/windows/x64/runner/Release/." "$_dest/" || return 1
|
||||
;;
|
||||
macos)
|
||||
_app="$UI_SRC/build/macos/Build/Products/Release/GC-UI.app"
|
||||
[ -d "$_app" ] || { err "找不到 Flutter macOS 产物(GC-UI.app)"; return 1; }
|
||||
_trash "$_dest/GC-UI.app"
|
||||
cp -R "$_app" "$_dest/" || return 1
|
||||
;;
|
||||
linux)
|
||||
_bundle=""
|
||||
for _cand in "$UI_SRC/build/linux/arm64/release/bundle" \
|
||||
"$UI_SRC/build/linux/x64/release/bundle"; do
|
||||
[ -d "$_cand" ] && _bundle="$_cand" && break
|
||||
done
|
||||
[ -n "$_bundle" ] ||
|
||||
{ err "找不到 Flutter Linux bundle(期望 build/linux/{arm64,x64}/release/bundle)"; return 1; }
|
||||
# 目标包是 arm64 却只编出 x64:主机架构不对,宁可失败也不出坏包
|
||||
case "$_bundle" in
|
||||
*/arm64/*) ;;
|
||||
*) [ "$(uname -m)" = aarch64 ] || [ "$(uname -m)" = arm64 ] ||
|
||||
{ err "Linux 包目标 arm64,但当前主机 $(uname -m) 只能编出 x64 前端"; return 1; } ;;
|
||||
esac
|
||||
cp -R "$_bundle/." "$_dest/" || return 1
|
||||
;;
|
||||
*)
|
||||
err "不支持的 Flutter 目标平台:$_plat"; return 1
|
||||
;;
|
||||
esac
|
||||
detail "$(_rel "$_dest")(Flutter ${_plat})"
|
||||
}
|
||||
|
||||
# 兼容旧调用:编译 + 落位一起做。DEST 可为相对仓库根的路径。
|
||||
build_flutter_ui() {
|
||||
_plat="$1"; _dest="$2"
|
||||
case "$_dest" in
|
||||
/*) : ;;
|
||||
*) _dest="$GC_ROOT/$_dest" ;;
|
||||
esac
|
||||
flutter_build "$_plat" || return 1
|
||||
flutter_stage "$_plat" "$_dest"
|
||||
}
|
||||
|
||||
# 在 Linux / macOS 上交叉编译 Windows 前端:mingw-w64 编 C++ 外壳,
|
||||
# wine 跑 Windows 版 gen_snapshot 生成 AOT 快照。产物布局与官方 toolchain 一致。
|
||||
build_flutter_ui_cross() {
|
||||
_dest="$1"
|
||||
UI_SRC="$(_ui_src)"
|
||||
FLUTTER_BIN="${FLUTTER_BIN:-flutter}"
|
||||
[ -d "$UI_SRC" ] || { err "找不到 Flutter 工程:GC-UI/frontend"; return 1; }
|
||||
|
||||
_log="$GC_ROOT/build/logs/flutter-win-cross.log"
|
||||
say "交叉编译 Windows 前端(mingw-w64 + wine)"
|
||||
# 交叉脚本只接受官方默认输出位置,先按官方 toolchain 编一份骨架(依赖它下载引擎产物)
|
||||
FLUTTER_BIN="$FLUTTER_BIN" \
|
||||
run_logged "$_log" "Windows 前端 " \
|
||||
bash "$GC_ROOT/buildsh/cross/build-ui-win-cross.sh" \
|
||||
"$UI_SRC/build/windows/x64/runner/Release" || return 1
|
||||
|
||||
mkdir -p "$_dest"
|
||||
cp -R "$UI_SRC/build/windows/x64/runner/Release/." "$_dest/" || return 1
|
||||
step_ok "Windows 前端(交叉编译)"
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
#!/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
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
#!/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(GC-UI.app 作为子应用嵌入)
|
||||
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/>
|
||||
<!-- 启动器只承担后端宿主,界面在 GC-UI.app:不出现在 Dock,避免出现两个图标 -->
|
||||
<key>LSUIElement</key><true/>
|
||||
</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 缺少守护进程,该平台将退回旧脚本更新"
|
||||
[ -f "$_pkg/GC-UI.exe" ] || [ -f "$_pkg/GC-UI" ] || \
|
||||
note "$_label 包内没有 Flutter 前端,启动器将使用内置 Avalonia 界面"
|
||||
|
||||
_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"))"
|
||||
}
|
||||
+61
-53
@@ -1,82 +1,80 @@
|
||||
#!/bin/sh
|
||||
# buildsh/lib/progress.sh —— apt 风格底部实时进度条
|
||||
# buildsh/lib/progress.sh —— 进度显示
|
||||
#
|
||||
# 底部一行:任务 当前任务进度 总进度 剩余时间
|
||||
# 编译MacOS 95% 30% 10s
|
||||
# 终端:底部单行实时进度条 [####....] 编译Mac 45% 30% 1m20s
|
||||
# 非终端(重定向 / CI / 日志):逐行打印步骤,不打 \r,不刷屏
|
||||
#
|
||||
# 用法:
|
||||
# progress_init <总步骤数> <每步权重...>
|
||||
# progress_step <步骤名> # 开始某步骤
|
||||
# progress_tick <0-100> # 更新当前步骤完成度
|
||||
# progress_done # 结束
|
||||
# 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_LAST=0
|
||||
PROGRESS_HISTORY=""
|
||||
PROGRESS_TASK="准备"
|
||||
_P_OVERALL=0
|
||||
_P_ETA="--"
|
||||
|
||||
_now() { date +%s; }
|
||||
GC_PROGRESS_TTY=0
|
||||
if [ -t 1 ] && [ -z "${GC_NO_PROGRESS:-}" ] && [ "${GC_QUIET:-0}" != 1 ]; then
|
||||
GC_PROGRESS_TTY=1
|
||||
fi
|
||||
|
||||
# 加权总进度:前序步骤权重之和 + 当前步骤权重*完成度
|
||||
_progress_overall() {
|
||||
# 一次算出整体百分比 + 剩余时间(原来每帧要循环两遍、fork 三次 date)
|
||||
_progress_refresh() {
|
||||
_sum=0; _i=1
|
||||
for _w in $PROGRESS_WEIGHTS; do
|
||||
if [ "$_i" -lt "$PROGRESS_IDX" ]; then
|
||||
_sum=$((_sum + _w)) # 已完成的步骤:全额
|
||||
_sum=$((_sum + _w))
|
||||
elif [ "$_i" -eq "$PROGRESS_IDX" ]; then
|
||||
_sum=$((_sum + _w * PROGRESS_CUR / 100)) # 当前步骤:按完成度
|
||||
_sum=$((_sum + _w * PROGRESS_CUR / 100))
|
||||
fi
|
||||
_i=$((_i + 1))
|
||||
done
|
||||
_p=$((_sum * 100 / PROGRESS_TOTAL))
|
||||
[ "$_p" -gt 100 ] && _p=100
|
||||
echo "$_p"
|
||||
_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_eta() {
|
||||
_p=$(_progress_overall)
|
||||
_t=$(( $(_now) - PROGRESS_STARTED ))
|
||||
# 前期用「预估总时长」估算(按各步骤经验权重),后期用实测速率外推,更稳
|
||||
if [ "$_p" -le 3 ] || [ "$_t" -le 0 ]; then
|
||||
_eta=$(( PROGRESS_TOTAL * 8 / 100 )) # 粗估:每 1% 约 8 秒 -> 总约 800s? 见下
|
||||
_eta=$(( 240 )) # 默认预估 4 分钟
|
||||
else
|
||||
_eta=$(( _t * (100 - _p) / _p ))
|
||||
fi
|
||||
if [ "$_eta" -ge 60 ]; then echo "$(( _eta / 60 ))m$((_eta % 60))s"; else echo "${_eta}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() {
|
||||
_task="$PROGRESS_TASK"
|
||||
_cur=$PROGRESS_CUR
|
||||
_overall=$(_progress_overall)
|
||||
_eta=$(_progress_eta)
|
||||
|
||||
# 进度条(20 格)
|
||||
_filled=$((_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 '\r\033[K[%s] %-14s %3d%% %3d%% %s' \
|
||||
"$_bar" "$_task" "$_cur" "$_overall" "$_eta"
|
||||
[ "$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_TOTAL=$1; shift
|
||||
PROGRESS_WEIGHTS="$*"
|
||||
PROGRESS_IDX=0
|
||||
PROGRESS_CUR=0
|
||||
PROGRESS_STARTED=$(_now)
|
||||
PROGRESS_STARTED=$(date +%s)
|
||||
PROGRESS_TASK="准备"
|
||||
progress_draw
|
||||
}
|
||||
@@ -85,16 +83,26 @@ progress_step() {
|
||||
PROGRESS_TASK="$1"
|
||||
PROGRESS_CUR=0
|
||||
PROGRESS_IDX=$((PROGRESS_IDX + 1))
|
||||
progress_draw
|
||||
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
|
||||
progress_tick 100
|
||||
printf '\n'
|
||||
if [ "$GC_PROGRESS_TTY" = 1 ]; then
|
||||
progress_draw
|
||||
printf '\n'
|
||||
fi
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
#!/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: 系统自带"
|
||||
|
||||
if [ "$BUILD_MAC" = 1 ] || [ "$BUILD_WIN" = 1 ]; then
|
||||
need "${FLUTTER_BIN:-flutter}" || _add flutter "设置 FLUTTER_BIN=<路径> 或加入 PATH"
|
||||
fi
|
||||
|
||||
# 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
|
||||
|
||||
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
|
||||
}
|
||||
+9
-14
@@ -10,33 +10,28 @@
|
||||
|
||||
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"
|
||||
|
||||
echo "==> 核对 Release ${TAG}"
|
||||
rc=0
|
||||
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=$?
|
||||
|
||||
if [ "$rc" -ne 0 ]; then
|
||||
return "$rc"
|
||||
fi
|
||||
"$@" || _rc=$?
|
||||
[ "$_rc" -eq 0 ] || return "$_rc"
|
||||
|
||||
# 资产对得上还不够:清单本身必须是我签的,否则客户端一样会拒
|
||||
echo ""
|
||||
echo "==> 校验 tag 清单签名"
|
||||
if dotnet run --project "$ROOT_DIR/GC-SAVEDOG/GC-SAVEDOG.csproj" -c Release -- \
|
||||
verify --manifest "$WORK/$TAG.json"; then
|
||||
echo "结论: 签名可信,可以发布 / 已经发布正确"
|
||||
say "校验 tag 清单签名"
|
||||
if dt_tool savedog "$SAVEDOG_PROJ" GC-SAVEDOG verify --manifest "$WORK/$TAG.json"; then
|
||||
step_ok "签名可信,可以发布 / 已经发布正确"
|
||||
return 0
|
||||
fi
|
||||
|
||||
echo "!! 签名校验未通过,客户端会拒绝这次更新"
|
||||
err "签名校验未通过,客户端会拒绝这次更新"
|
||||
return 1
|
||||
}
|
||||
+23
-12
@@ -1,8 +1,11 @@
|
||||
#!/bin/sh
|
||||
# buildsh/tools.sh —— 实用工具:模型、版本戳、清理、运行、医生、打开目录
|
||||
# buildsh/tools.sh —— 实用工具:模型、版本戳、打包、清理、运行、医生
|
||||
|
||||
bs_tools() {
|
||||
ROOT_DIR="$1"; TASK="$2"
|
||||
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 ;;
|
||||
@@ -11,23 +14,31 @@ bs_tools() {
|
||||
pack-models)
|
||||
build_models; pack_models ;;
|
||||
pack-launcher)
|
||||
# 单独打包:数据源优先 build/stage,缺失时回落到 dist
|
||||
mkdir -p "$GC_ROOT/build/logs"
|
||||
pack_launcher ;;
|
||||
run)
|
||||
dotnet run --project "$APP_PROJ" -c Debug ;;
|
||||
test)
|
||||
dotnet run --project "$TEST_PROJ" -c Debug -- "$ROOT_DIR/build/screenshots" ;;
|
||||
update-test)
|
||||
dotnet run --project "$TEST_PROJ" -c Debug -- --update-test "$ROOT_DIR" ;;
|
||||
clean)
|
||||
rm -rf "$ROOT_DIR/build" "$ROOT_DIR/dist"
|
||||
find "$ROOT_DIR/src" -type d \( -name bin -o -name obj \) -prune -exec rm -rf {} + 2>/dev/null || true
|
||||
echo "==> 已清理" ;;
|
||||
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)
|
||||
echo "==> dist 产物:"
|
||||
ls -lh "$ROOT_DIR"/dist/*/GCL-*.zip 2>/dev/null || ls -lh "$ROOT_DIR"/dist 2>/dev/null || true ;;
|
||||
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 "(暂无产物)" ;;
|
||||
*)
|
||||
echo "未知工具: $TASK"; return 1 ;;
|
||||
err "未知工具:${TASK:-(空)}"
|
||||
note "可用:models / stamp / pack-models / pack-launcher / run / clean / doctor / dist"
|
||||
return 1 ;;
|
||||
esac
|
||||
}
|
||||
Binary file not shown.
@@ -1,663 +0,0 @@
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
const STEP_COPY = [
|
||||
{ title: "等高切割", description: "观察水平面与山体在同一海拔相交,形成连续闭合线。" },
|
||||
{ title: "形成交线", description: "每个水平切面都会留下同高交线,多层交线共同描述山体起伏。" },
|
||||
{ title: "投影成图", description: "把各高度交线垂直投影到同一平面,得到完整等高线地形图。" },
|
||||
{ title: "疏密判坡", description: "等高线越密,坡度越陡;等高线越疏,坡度越缓。" }
|
||||
];
|
||||
|
||||
const DEFAULT_VIEW = {
|
||||
title: "实验流程",
|
||||
summary: "点击开始实验,在当前背景中观察等高切割与交线形成,再通过右侧图解理解垂直投影和疏密判坡。",
|
||||
features: ["同一条等高线上海拔相等", "相邻等高线高差保持一致"],
|
||||
hint: "点击“开始实验”,直接在当前画面播放形成交线视频"
|
||||
};
|
||||
|
||||
const LANDFORMS = {
|
||||
peak: {
|
||||
name: "山峰",
|
||||
subtitle: "闭合等高线",
|
||||
image: "assets/peak-3d.png",
|
||||
topImage: "assets/peak-top.png",
|
||||
alt: "山峰立体示意图,蓝色等高线围绕山体逐级闭合",
|
||||
topAlt: "山峰真实俯视图,多层近同心闭合等高线向中心收缩",
|
||||
summary: "山峰四周较低、中心突起;等高线闭合成环,海拔数值由外向内逐渐升高。",
|
||||
features: ["中心海拔高、四周海拔低", "闭合线越向内,数值越大", "若数值向内降低,则应判为洼地"],
|
||||
hint: "山峰:闭合曲线,数值向中心升高"
|
||||
},
|
||||
ridge: {
|
||||
name: "山脊",
|
||||
subtitle: "凸低为脊",
|
||||
image: "assets/ridge-3d.png",
|
||||
topImage: "assets/ridge-top.png",
|
||||
alt: "山脊立体示意图,蓝色等高线沿凸出的脊线向低处弯曲",
|
||||
topAlt: "山脊真实俯视图,等高线沿狭长高地呈舌状延伸",
|
||||
summary: "等高线弯曲部分向海拔低处凸出,脊线常成为两侧水系的分水岭。",
|
||||
features: ["等高线凸向低值方向", "脊线由高处向低处延伸", "雨水沿脊线两侧分流"],
|
||||
hint: "山脊:等高线向低处凸出,凸低为脊"
|
||||
},
|
||||
valley: {
|
||||
name: "山谷",
|
||||
subtitle: "凸高为谷",
|
||||
image: "assets/valley-3d.png",
|
||||
topImage: "assets/valley-top.png",
|
||||
alt: "山谷立体示意图,两座山体之间的谷地有河流穿过",
|
||||
topAlt: "山谷真实俯视图,两侧坡面夹持低槽,等高线形成 V 形凹入",
|
||||
summary: "等高线弯曲部分向海拔高处凸出,谷底低洼并容易汇水形成河流。",
|
||||
features: ["等高线凸向高值方向", "V 形尖端指向上游高处", "谷底常发育河流"],
|
||||
hint: "山谷:等高线向高处凸出,凸高为谷"
|
||||
},
|
||||
saddle: {
|
||||
name: "鞍部",
|
||||
subtitle: "两峰之间",
|
||||
image: "assets/saddle-3d.png",
|
||||
topImage: "assets/saddle-top.png",
|
||||
alt: "鞍部立体示意图,两座山峰之间形成马鞍状低地",
|
||||
topAlt: "鞍部真实俯视图,两组峰顶闭合圈之间的等高线明显收腰",
|
||||
summary: "鞍部位于相邻两座山峰之间,是沿山脊方向相对低洼的过渡地带。",
|
||||
features: ["两组闭合等高线相邻", "中部线条收窄,形似马鞍", "常是翻越山岭的低垭口"],
|
||||
hint: "鞍部:两峰之间相对低洼,俯视轮廓呈收腰形"
|
||||
},
|
||||
cliff: {
|
||||
name: "陡崖",
|
||||
subtitle: "密集或重合",
|
||||
image: "assets/cliff-3d.png",
|
||||
topImage: "assets/cliff-top.png",
|
||||
alt: "陡崖立体示意图,崖壁处蓝色等高线高度密集",
|
||||
topAlt: "陡崖真实俯视图,崖壁处大量等高线极密集并近似重合",
|
||||
summary: "陡崖坡面近直立,不同高程的等高线会高度密集,局部可投影到同一位置而重合。",
|
||||
features: ["密集表示陡坡,重合才是陡崖特征", "单位水平距离内高差很大", "n 条线重合时:(n−1)d ≤ ΔH < (n+1)d"],
|
||||
hint: "陡崖:等高线密集或重合,坡度极陡"
|
||||
}
|
||||
};
|
||||
|
||||
const dom = {
|
||||
app: document.getElementById("app-shell"),
|
||||
experimentVideo: document.getElementById("experiment-video"),
|
||||
densityBackground: document.getElementById("density-background"),
|
||||
landformImage: document.getElementById("landform-image"),
|
||||
landformTopImage: document.getElementById("landform-top-image"),
|
||||
projectionDiagram: document.getElementById("projection-diagram"),
|
||||
densityDiagram: document.getElementById("density-diagram"),
|
||||
mediaLoading: document.getElementById("media-loading"),
|
||||
mediaLabelKicker: document.getElementById("media-label-kicker"),
|
||||
mediaLabelTitle: document.getElementById("media-label-title"),
|
||||
mediaLabelCopy: document.getElementById("media-label-copy"),
|
||||
progress: document.getElementById("video-progress-fill"),
|
||||
playButton: document.getElementById("play-button"),
|
||||
playIcon: document.getElementById("play-icon"),
|
||||
playLabel: document.getElementById("play-label"),
|
||||
resetButton: document.getElementById("reset-button"),
|
||||
fullscreenButton: document.getElementById("fullscreen-button"),
|
||||
fullscreenLabel: document.getElementById("fullscreen-label"),
|
||||
workflowOpen: document.getElementById("workflow-open"),
|
||||
flowSteps: Array.from(document.querySelectorAll(".flow-step[data-step]")),
|
||||
flowCount: document.getElementById("flow-count"),
|
||||
flowLineFill: document.getElementById("flow-line-fill"),
|
||||
taskTitle: document.getElementById("task-title"),
|
||||
taskDescription: document.getElementById("task-description"),
|
||||
terrainTabs: Array.from(document.querySelectorAll(".terrain-tab[data-landform]")),
|
||||
returnExperiment: document.getElementById("return-experiment"),
|
||||
observationHeading: document.getElementById("observation-heading"),
|
||||
observationSummary: document.getElementById("observation-summary"),
|
||||
featureList: document.getElementById("feature-list"),
|
||||
topViewToggle: document.getElementById("top-view-toggle"),
|
||||
topViewToggleLabel: document.getElementById("top-view-toggle-label"),
|
||||
topViewToggleHint: document.getElementById("top-view-toggle-hint"),
|
||||
topViewThumbnail: document.getElementById("top-view-thumbnail"),
|
||||
hintText: document.getElementById("hint-text"),
|
||||
controlPanel: document.querySelector(".control-panel"),
|
||||
panelClose: document.getElementById("panel-close"),
|
||||
panelOpen: document.getElementById("panel-open"),
|
||||
toast: document.getElementById("toast")
|
||||
};
|
||||
|
||||
const state = {
|
||||
selectedLandform: null,
|
||||
pendingLandform: null,
|
||||
viewMode: "perspective",
|
||||
step: 0,
|
||||
imageToken: 0,
|
||||
scanTimer: 0,
|
||||
annotationTimer: 0,
|
||||
toastTimer: 0,
|
||||
pendingStep: null,
|
||||
workflowTimer: 0,
|
||||
workflowRunToken: 0,
|
||||
workflowAutoPlaying: false
|
||||
};
|
||||
|
||||
const ICONS = {
|
||||
play: '<svg viewBox="0 0 24 24"><path d="m9 6 9 6-9 6V6Z"/></svg>',
|
||||
pause: '<svg viewBox="0 0 24 24"><path d="M7 6h4v12H7V6Zm6 0h4v12h-4V6Z"/></svg>'
|
||||
};
|
||||
|
||||
function showToast(message) {
|
||||
window.clearTimeout(state.toastTimer);
|
||||
dom.toast.textContent = message;
|
||||
dom.toast.classList.add("is-visible");
|
||||
state.toastTimer = window.setTimeout(function () {
|
||||
dom.toast.classList.remove("is-visible");
|
||||
}, 2600);
|
||||
}
|
||||
|
||||
function hideLoading() {
|
||||
dom.mediaLoading.classList.add("is-hidden");
|
||||
}
|
||||
|
||||
function cancelWorkflowSequence() {
|
||||
window.clearTimeout(state.workflowTimer);
|
||||
state.workflowTimer = 0;
|
||||
state.workflowRunToken += 1;
|
||||
state.workflowAutoPlaying = false;
|
||||
}
|
||||
|
||||
function setWorkflowDiagram(element, active) {
|
||||
element.toggleAttribute("hidden", !active);
|
||||
element.classList.toggle("is-active", active);
|
||||
}
|
||||
|
||||
function hideWorkflowVisuals() {
|
||||
setWorkflowDiagram(dom.projectionDiagram, false);
|
||||
setWorkflowDiagram(dom.densityDiagram, false);
|
||||
dom.densityBackground.classList.remove("is-visible");
|
||||
dom.app.classList.remove("has-workflow-visual");
|
||||
}
|
||||
|
||||
function syncWorkflowPresentation(index) {
|
||||
const safeIndex = Math.max(0, Math.min(3, Number(index) || 0));
|
||||
const isExperiment = !state.selectedLandform;
|
||||
const showProjection = isExperiment && safeIndex === 2;
|
||||
const showDensity = isExperiment && safeIndex === 3;
|
||||
const densityWasVisible = dom.densityBackground.classList.contains("is-visible");
|
||||
setWorkflowDiagram(dom.projectionDiagram, showProjection);
|
||||
setWorkflowDiagram(dom.densityDiagram, showDensity);
|
||||
dom.densityBackground.classList.toggle("is-visible", showDensity);
|
||||
dom.app.classList.toggle("has-workflow-visual", showProjection || showDensity);
|
||||
if (isExperiment) dom.experimentVideo.classList.toggle("is-visible", !showDensity);
|
||||
if (showDensity && !densityWasVisible) triggerScan(dom.densityBackground);
|
||||
}
|
||||
|
||||
function beginStaticWorkflowSequence() {
|
||||
cancelWorkflowSequence();
|
||||
const token = state.workflowRunToken;
|
||||
state.workflowAutoPlaying = true;
|
||||
renderStep(2);
|
||||
setPlayButton();
|
||||
dom.hintText.textContent = "自动演示:" + STEP_COPY[2].description;
|
||||
state.workflowTimer = window.setTimeout(function () {
|
||||
if (token !== state.workflowRunToken) return;
|
||||
renderStep(3);
|
||||
dom.hintText.textContent = "自动演示:" + STEP_COPY[3].description;
|
||||
state.workflowTimer = window.setTimeout(function () {
|
||||
if (token !== state.workflowRunToken) return;
|
||||
state.workflowTimer = 0;
|
||||
state.workflowAutoPlaying = false;
|
||||
setPlayButton();
|
||||
dom.hintText.textContent = "实验流程播放完成 · 可重新实验或选择典型地貌观察";
|
||||
}, 3600);
|
||||
}, 3200);
|
||||
}
|
||||
|
||||
function renderStep(index) {
|
||||
const safeIndex = Math.max(0, Math.min(3, Number(index) || 0));
|
||||
state.step = safeIndex;
|
||||
const copy = STEP_COPY[safeIndex];
|
||||
dom.flowCount.textContent = (safeIndex + 1) + "/4";
|
||||
dom.flowLineFill.style.width = (safeIndex / 3) * 100 + "%";
|
||||
dom.taskTitle.textContent = copy.title;
|
||||
dom.taskDescription.textContent = copy.description;
|
||||
dom.flowSteps.forEach(function (button, buttonIndex) {
|
||||
button.classList.toggle("is-active", buttonIndex === safeIndex);
|
||||
button.classList.toggle("is-complete", buttonIndex < safeIndex);
|
||||
button.setAttribute("aria-current", buttonIndex === safeIndex ? "step" : "false");
|
||||
});
|
||||
syncWorkflowPresentation(safeIndex);
|
||||
}
|
||||
|
||||
function renderObservation(view) {
|
||||
dom.observationHeading.textContent = view.name || view.title;
|
||||
dom.observationSummary.textContent = view.summary;
|
||||
dom.featureList.replaceChildren();
|
||||
view.features.forEach(function (feature) {
|
||||
const item = document.createElement("li");
|
||||
item.textContent = feature;
|
||||
dom.featureList.appendChild(item);
|
||||
});
|
||||
}
|
||||
|
||||
function setPlayButton() {
|
||||
const duration = dom.experimentVideo.duration;
|
||||
const finished = dom.experimentVideo.ended || (Number.isFinite(duration) && duration > 0 && dom.experimentVideo.currentTime >= duration - 0.08);
|
||||
if (!dom.experimentVideo.paused) {
|
||||
dom.playLabel.textContent = "暂停实验";
|
||||
dom.playIcon.innerHTML = ICONS.pause;
|
||||
return;
|
||||
}
|
||||
dom.playIcon.innerHTML = ICONS.play;
|
||||
if (!state.selectedLandform && state.step >= 2) {
|
||||
dom.playLabel.textContent = "重新实验";
|
||||
return;
|
||||
}
|
||||
if (finished) dom.playLabel.textContent = "重新实验";
|
||||
else if (dom.experimentVideo.currentTime > 0.12) dom.playLabel.textContent = "继续实验";
|
||||
else dom.playLabel.textContent = "开始实验";
|
||||
}
|
||||
|
||||
function updateMediaLabel(view) {
|
||||
if (view) {
|
||||
dom.mediaLabelKicker.textContent = state.viewMode === "top" ? "典型地貌 · 真实俯视图" : "典型地貌 · 立体示意";
|
||||
dom.mediaLabelTitle.textContent = view.name;
|
||||
dom.mediaLabelCopy.textContent = state.viewMode === "top" ? view.subtitle + "|" + view.summary : view.summary;
|
||||
return;
|
||||
}
|
||||
dom.mediaLabelKicker.textContent = "实验流程";
|
||||
dom.mediaLabelTitle.textContent = "形成交线与垂直投影";
|
||||
dom.mediaLabelCopy.textContent = dom.experimentVideo.paused
|
||||
? "点击“开始实验”,直接在当前画面播放形成交线视频"
|
||||
: STEP_COPY[state.step].description;
|
||||
}
|
||||
|
||||
function updateViewToggle() {
|
||||
const view = LANDFORMS[state.selectedLandform];
|
||||
const hasLandform = Boolean(view);
|
||||
const isTopView = hasLandform && state.viewMode === "top";
|
||||
dom.topViewToggle.disabled = !hasLandform;
|
||||
dom.topViewToggle.classList.toggle("is-active", isTopView);
|
||||
dom.topViewToggle.setAttribute("aria-pressed", String(isTopView));
|
||||
dom.topViewToggleLabel.textContent = isTopView ? "立体图" : "俯视图";
|
||||
dom.topViewToggleHint.textContent = hasLandform ? "点击切换" : "选择地貌后切换";
|
||||
dom.topViewToggle.setAttribute(
|
||||
"aria-label",
|
||||
hasLandform ? "切换为" + (isTopView ? "立体图" : "俯视图") : "请先选择一种典型地貌"
|
||||
);
|
||||
|
||||
if (!view) {
|
||||
dom.topViewThumbnail.hidden = true;
|
||||
dom.topViewThumbnail.removeAttribute("src");
|
||||
dom.topViewThumbnail.alt = "";
|
||||
return;
|
||||
}
|
||||
dom.topViewThumbnail.src = isTopView ? view.image : view.topImage;
|
||||
dom.topViewThumbnail.alt = isTopView ? view.name + "立体图预览" : view.name + "真实俯视图预览";
|
||||
dom.topViewThumbnail.hidden = false;
|
||||
}
|
||||
|
||||
function triggerScan(targetImage) {
|
||||
window.clearTimeout(state.scanTimer);
|
||||
dom.app.classList.remove("is-scanning");
|
||||
dom.densityBackground.classList.remove("is-revealing");
|
||||
dom.landformImage.classList.remove("is-revealing");
|
||||
dom.landformTopImage.classList.remove("is-revealing");
|
||||
void dom.app.offsetWidth;
|
||||
dom.app.classList.add("is-scanning");
|
||||
(targetImage || (state.viewMode === "top" ? dom.landformTopImage : dom.landformImage)).classList.add("is-revealing");
|
||||
state.scanTimer = window.setTimeout(function () {
|
||||
dom.app.classList.remove("is-scanning");
|
||||
dom.densityBackground.classList.remove("is-revealing");
|
||||
dom.landformImage.classList.remove("is-revealing");
|
||||
dom.landformTopImage.classList.remove("is-revealing");
|
||||
}, 1220);
|
||||
}
|
||||
|
||||
async function decodeImage(image) {
|
||||
if (typeof image.decode === "function") {
|
||||
await image.decode();
|
||||
return;
|
||||
}
|
||||
if (!image.complete) {
|
||||
await new Promise(function (resolve, reject) {
|
||||
image.addEventListener("load", resolve, { once: true });
|
||||
image.addEventListener("error", reject, { once: true });
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function hideTerrainAnnotation() {
|
||||
window.clearTimeout(state.annotationTimer);
|
||||
dom.app.classList.remove("is-landform");
|
||||
if (window.TerrainAnnotation) window.TerrainAnnotation.hide();
|
||||
}
|
||||
|
||||
function clearTerrainAnnotationNow() {
|
||||
window.clearTimeout(state.annotationTimer);
|
||||
state.annotationTimer = 0;
|
||||
if (window.TerrainAnnotation) window.TerrainAnnotation.hide(true);
|
||||
}
|
||||
|
||||
function scheduleTerrainAnnotation(withScan) {
|
||||
window.clearTimeout(state.annotationTimer);
|
||||
dom.app.classList.add("is-landform");
|
||||
state.annotationTimer = window.setTimeout(function () {
|
||||
if (!state.selectedLandform || !window.TerrainAnnotation) return;
|
||||
window.TerrainAnnotation.show(state.selectedLandform, state.viewMode);
|
||||
}, withScan ? 420 : 0);
|
||||
}
|
||||
|
||||
function applyLandformView(view, withScan) {
|
||||
const isTopView = state.viewMode === "top";
|
||||
hideWorkflowVisuals();
|
||||
dom.experimentVideo.classList.remove("is-visible");
|
||||
dom.landformImage.classList.toggle("is-visible", !isTopView);
|
||||
dom.landformTopImage.classList.toggle("is-visible", isTopView);
|
||||
updateMediaLabel(view);
|
||||
updateViewToggle();
|
||||
dom.hintText.textContent = isTopView
|
||||
? view.name + "俯视图:" + view.hint.replace(view.name + ":", "")
|
||||
: view.hint;
|
||||
if (withScan) triggerScan();
|
||||
scheduleTerrainAnnotation(withScan);
|
||||
}
|
||||
|
||||
function collapsePanelForCompactView() {
|
||||
if (!window.matchMedia("(max-width: 680px)").matches) return;
|
||||
dom.controlPanel.classList.add("is-collapsed");
|
||||
dom.panelOpen.hidden = false;
|
||||
}
|
||||
|
||||
async function selectLandform(key) {
|
||||
const view = LANDFORMS[key];
|
||||
if (!view) return;
|
||||
const token = ++state.imageToken;
|
||||
cancelWorkflowSequence();
|
||||
state.pendingLandform = key;
|
||||
clearTerrainAnnotationNow();
|
||||
hideWorkflowVisuals();
|
||||
const nextMode = state.selectedLandform ? state.viewMode : "perspective";
|
||||
dom.experimentVideo.pause();
|
||||
const perspectiveProbe = new Image();
|
||||
const topProbe = new Image();
|
||||
perspectiveProbe.src = view.image;
|
||||
topProbe.src = view.topImage;
|
||||
|
||||
try {
|
||||
await Promise.all([decodeImage(perspectiveProbe), decodeImage(topProbe)]);
|
||||
} catch (error) {
|
||||
if (token === state.imageToken) {
|
||||
state.pendingLandform = null;
|
||||
syncWorkflowPresentation(state.step);
|
||||
showToast("地貌图片加载失败,请检查对应资源文件");
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (token !== state.imageToken) return;
|
||||
|
||||
state.pendingLandform = null;
|
||||
state.selectedLandform = key;
|
||||
state.viewMode = nextMode;
|
||||
dom.landformImage.src = view.image;
|
||||
dom.landformImage.alt = view.alt;
|
||||
dom.landformTopImage.src = view.topImage;
|
||||
dom.landformTopImage.alt = view.topAlt;
|
||||
|
||||
dom.terrainTabs.forEach(function (button) {
|
||||
const active = button.dataset.landform === key;
|
||||
button.classList.toggle("is-active", active);
|
||||
button.setAttribute("aria-pressed", String(active));
|
||||
});
|
||||
dom.returnExperiment.hidden = false;
|
||||
renderObservation(view);
|
||||
applyLandformView(view, true);
|
||||
collapsePanelForCompactView();
|
||||
setPlayButton();
|
||||
}
|
||||
|
||||
async function toggleTopView() {
|
||||
const view = LANDFORMS[state.selectedLandform];
|
||||
if (!view) return;
|
||||
const previousMode = state.viewMode;
|
||||
const token = ++state.imageToken;
|
||||
state.pendingLandform = null;
|
||||
clearTerrainAnnotationNow();
|
||||
state.viewMode = previousMode === "top" ? "perspective" : "top";
|
||||
try {
|
||||
await decodeImage(state.viewMode === "top" ? dom.landformTopImage : dom.landformImage);
|
||||
} catch (error) {
|
||||
state.viewMode = previousMode;
|
||||
showToast("对应视图加载失败,请检查图片资源");
|
||||
return;
|
||||
}
|
||||
if (token !== state.imageToken) return;
|
||||
applyLandformView(view, true);
|
||||
collapsePanelForCompactView();
|
||||
}
|
||||
|
||||
function showExperiment() {
|
||||
cancelWorkflowSequence();
|
||||
state.imageToken += 1;
|
||||
state.pendingLandform = null;
|
||||
state.selectedLandform = null;
|
||||
state.viewMode = "perspective";
|
||||
dom.app.classList.remove("is-scanning");
|
||||
hideWorkflowVisuals();
|
||||
hideTerrainAnnotation();
|
||||
dom.landformImage.classList.remove("is-visible", "is-revealing");
|
||||
dom.landformTopImage.classList.remove("is-visible", "is-revealing");
|
||||
dom.experimentVideo.classList.add("is-visible");
|
||||
dom.terrainTabs.forEach(function (button) {
|
||||
button.classList.remove("is-active");
|
||||
button.setAttribute("aria-pressed", "false");
|
||||
});
|
||||
dom.returnExperiment.hidden = true;
|
||||
renderObservation(DEFAULT_VIEW);
|
||||
updateViewToggle();
|
||||
updateMediaLabel(null);
|
||||
}
|
||||
|
||||
function playVideo() {
|
||||
dom.experimentVideo.play().then(function () {
|
||||
setPlayButton();
|
||||
updateMediaLabel(null);
|
||||
dom.hintText.textContent = "实验播放中:" + STEP_COPY[state.step].description;
|
||||
}).catch(function (error) {
|
||||
if (error && error.name === "AbortError") return;
|
||||
showToast("视频暂时无法播放,请检查浏览器媒体权限");
|
||||
});
|
||||
}
|
||||
|
||||
function toggleExperimentPlayback() {
|
||||
if (state.selectedLandform || state.pendingLandform || state.step >= 2) {
|
||||
showExperiment();
|
||||
if (Number.isFinite(dom.experimentVideo.duration) && dom.experimentVideo.duration > 0) {
|
||||
dom.experimentVideo.currentTime = 0;
|
||||
} else {
|
||||
state.pendingStep = 0;
|
||||
}
|
||||
renderStep(0);
|
||||
playVideo();
|
||||
return;
|
||||
}
|
||||
if (!dom.experimentVideo.paused) {
|
||||
dom.experimentVideo.pause();
|
||||
return;
|
||||
}
|
||||
const duration = dom.experimentVideo.duration;
|
||||
if (dom.experimentVideo.ended || (Number.isFinite(duration) && dom.experimentVideo.currentTime >= duration - 0.08)) {
|
||||
dom.experimentVideo.currentTime = 0;
|
||||
renderStep(0);
|
||||
}
|
||||
playVideo();
|
||||
}
|
||||
|
||||
function playFromBeginning() {
|
||||
showExperiment();
|
||||
renderStep(0);
|
||||
if (Number.isFinite(dom.experimentVideo.duration) && dom.experimentVideo.duration > 0) {
|
||||
dom.experimentVideo.currentTime = 0;
|
||||
} else {
|
||||
state.pendingStep = 0;
|
||||
}
|
||||
playVideo();
|
||||
}
|
||||
|
||||
function playStep(index) {
|
||||
const safeIndex = Math.max(0, Math.min(3, Number(index) || 0));
|
||||
showExperiment();
|
||||
renderStep(safeIndex);
|
||||
if (safeIndex <= 1) {
|
||||
if (Number.isFinite(dom.experimentVideo.duration) && dom.experimentVideo.duration > 0) {
|
||||
dom.experimentVideo.currentTime = safeIndex === 0 ? 0 : dom.experimentVideo.duration / 2;
|
||||
} else {
|
||||
state.pendingStep = safeIndex;
|
||||
}
|
||||
playVideo();
|
||||
return;
|
||||
}
|
||||
state.pendingStep = null;
|
||||
dom.experimentVideo.pause();
|
||||
setPlayButton();
|
||||
updateMediaLabel(null);
|
||||
dom.hintText.textContent = STEP_COPY[safeIndex].title + ":" + STEP_COPY[safeIndex].description;
|
||||
}
|
||||
|
||||
function resetExperience() {
|
||||
state.pendingStep = null;
|
||||
dom.experimentVideo.pause();
|
||||
showExperiment();
|
||||
renderStep(0);
|
||||
if (Number.isFinite(dom.experimentVideo.duration) && dom.experimentVideo.duration > 0) {
|
||||
dom.experimentVideo.currentTime = 0;
|
||||
} else {
|
||||
state.pendingStep = 0;
|
||||
}
|
||||
dom.progress.style.width = "0%";
|
||||
dom.hintText.textContent = DEFAULT_VIEW.hint;
|
||||
setPlayButton();
|
||||
showToast("已重置到视频首帧");
|
||||
}
|
||||
|
||||
function toggleFullscreen() {
|
||||
if (!document.fullscreenElement) {
|
||||
if (!dom.app.requestFullscreen) {
|
||||
showToast("当前浏览器不支持全屏");
|
||||
return;
|
||||
}
|
||||
dom.app.requestFullscreen().catch(function () { showToast("当前浏览器未允许进入全屏"); });
|
||||
return;
|
||||
}
|
||||
if (document.exitFullscreen) document.exitFullscreen().catch(function () {});
|
||||
}
|
||||
|
||||
dom.experimentVideo.addEventListener("loadeddata", hideLoading, { once: true });
|
||||
dom.experimentVideo.addEventListener("canplay", hideLoading, { once: true });
|
||||
dom.experimentVideo.addEventListener("loadedmetadata", function () {
|
||||
if (state.pendingStep === null) return;
|
||||
const pending = state.pendingStep;
|
||||
state.pendingStep = null;
|
||||
const duration = dom.experimentVideo.duration;
|
||||
if (Number.isFinite(duration) && duration > 0) {
|
||||
dom.experimentVideo.currentTime = pending === 0 ? 0 : duration / 2;
|
||||
renderStep(pending);
|
||||
}
|
||||
});
|
||||
dom.experimentVideo.addEventListener("error", function () {
|
||||
hideLoading();
|
||||
showToast("形成交线视频加载失败,请确认“contour-formation.mp4”在当前目录");
|
||||
});
|
||||
dom.experimentVideo.addEventListener("play", function () {
|
||||
setPlayButton();
|
||||
updateMediaLabel(null);
|
||||
dom.hintText.textContent = "实验播放中:" + STEP_COPY[state.step].description;
|
||||
});
|
||||
dom.experimentVideo.addEventListener("pause", function () {
|
||||
setPlayButton();
|
||||
updateMediaLabel(null);
|
||||
if (!state.selectedLandform && state.step >= 2) {
|
||||
dom.hintText.textContent = STEP_COPY[state.step].title + ":" + STEP_COPY[state.step].description;
|
||||
return;
|
||||
}
|
||||
if (!dom.experimentVideo.ended && dom.experimentVideo.currentTime > 0.12 && !state.selectedLandform) {
|
||||
dom.hintText.textContent = "实验已暂停 · 点击“继续实验”恢复播放";
|
||||
}
|
||||
});
|
||||
dom.experimentVideo.addEventListener("ended", function () {
|
||||
if (
|
||||
state.selectedLandform ||
|
||||
state.pendingLandform ||
|
||||
state.step > 1 ||
|
||||
!dom.experimentVideo.ended
|
||||
) return;
|
||||
dom.progress.style.width = "100%";
|
||||
beginStaticWorkflowSequence();
|
||||
});
|
||||
dom.experimentVideo.addEventListener("timeupdate", function () {
|
||||
const duration = dom.experimentVideo.duration;
|
||||
const ratio = Number.isFinite(duration) && duration > 0 ? dom.experimentVideo.currentTime / duration : 0;
|
||||
dom.progress.style.width = Math.max(0, Math.min(100, ratio * 100)) + "%";
|
||||
if (!state.selectedLandform && state.step === 0 && ratio >= 0.5) {
|
||||
renderStep(1);
|
||||
dom.hintText.textContent = "实验播放中:" + STEP_COPY[1].description;
|
||||
}
|
||||
if (!dom.experimentVideo.paused) updateMediaLabel(null);
|
||||
});
|
||||
|
||||
dom.playButton.addEventListener("click", toggleExperimentPlayback);
|
||||
dom.workflowOpen.addEventListener("click", playFromBeginning);
|
||||
dom.resetButton.addEventListener("click", resetExperience);
|
||||
dom.returnExperiment.addEventListener("click", resetExperience);
|
||||
dom.topViewToggle.addEventListener("click", toggleTopView);
|
||||
dom.terrainTabs.forEach(function (button) {
|
||||
button.addEventListener("click", function () { selectLandform(button.dataset.landform); });
|
||||
});
|
||||
dom.flowSteps.forEach(function (button) {
|
||||
button.addEventListener("click", function () { playStep(Number(button.dataset.step)); });
|
||||
});
|
||||
|
||||
dom.fullscreenButton.addEventListener("click", toggleFullscreen);
|
||||
document.addEventListener("fullscreenchange", function () {
|
||||
dom.fullscreenLabel.textContent = document.fullscreenElement ? "退出全屏" : "全屏";
|
||||
});
|
||||
dom.panelClose.addEventListener("click", function () {
|
||||
dom.controlPanel.classList.add("is-collapsed");
|
||||
dom.panelOpen.hidden = false;
|
||||
});
|
||||
dom.panelOpen.addEventListener("click", function () {
|
||||
dom.controlPanel.classList.remove("is-collapsed");
|
||||
dom.panelOpen.hidden = true;
|
||||
});
|
||||
|
||||
document.addEventListener("keydown", function (event) {
|
||||
if (event.code === "Space" && !/BUTTON|INPUT|VIDEO/.test(document.activeElement.tagName)) {
|
||||
event.preventDefault();
|
||||
toggleExperimentPlayback();
|
||||
}
|
||||
if (/^[1-5]$/.test(event.key) && !event.metaKey && !event.ctrlKey && !event.altKey) {
|
||||
const keys = ["peak", "ridge", "valley", "saddle", "cliff"];
|
||||
selectLandform(keys[Number(event.key) - 1]);
|
||||
}
|
||||
});
|
||||
|
||||
window.setTimeout(hideLoading, 7000);
|
||||
renderStep(0);
|
||||
renderObservation(DEFAULT_VIEW);
|
||||
updateViewToggle();
|
||||
updateMediaLabel(null);
|
||||
setPlayButton();
|
||||
|
||||
window.__GEO_LAB_TEST__ = {
|
||||
getState: function () {
|
||||
return {
|
||||
selectedLandform: state.selectedLandform,
|
||||
pendingLandform: state.pendingLandform,
|
||||
viewMode: state.viewMode,
|
||||
step: state.step,
|
||||
videoPlaying: !dom.experimentVideo.paused,
|
||||
videoTime: dom.experimentVideo.currentTime,
|
||||
videoSource: dom.experimentVideo.currentSrc || dom.experimentVideo.src,
|
||||
workflowDiagram: !dom.projectionDiagram.hasAttribute("hidden") ? "projection" : !dom.densityDiagram.hasAttribute("hidden") ? "density" : null,
|
||||
workflowAutoPlaying: state.workflowAutoPlaying,
|
||||
densityBackground: dom.densityBackground.classList.contains("is-visible"),
|
||||
scanning: dom.app.classList.contains("is-scanning"),
|
||||
terrainAnnotation: window.TerrainAnnotation ? window.TerrainAnnotation.getState() : null,
|
||||
fullscreen: Boolean(document.fullscreenElement)
|
||||
};
|
||||
},
|
||||
selectLandform: selectLandform,
|
||||
toggleTopView: toggleTopView,
|
||||
showExperiment: showExperiment,
|
||||
playStep: playStep,
|
||||
reset: resetExperience
|
||||
};
|
||||
})();
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 2.6 MiB |
Loaded 100 of 139 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user