Merge pull request #1 from Morris-morris-cloud/feat/github-source-and-ci
feat: 全面迁移到 Flutter + 新增 GitHub 源与 CI 流水线
No files matched your search
@@ -0,0 +1,63 @@
|
||||
# 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`** 预发布 |
|
||||
| `pr-review.yml` | 向 main 提 PR(新建 / 有新提交 / 重新打开) | 检查能否编译、是否有错、是否冲突、是否落后 main |
|
||||
|
||||
两个预发布用**不同的 tag**,互不覆盖:夜间构建发 `nightly`,手动触发的发 `ip-prerelease`。
|
||||
|
||||
## 每夜构建
|
||||
|
||||
时区用 `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 产物是 **未签名** 的(`GC_NO_CODESIGN=1`)。下载后首次打开需右键 →「打开」,
|
||||
或在「系统设置 → 隐私与安全性」里放行。
|
||||
@@ -0,0 +1,240 @@
|
||||
name: build-bot
|
||||
|
||||
# 在 Issue / PR 里评论触发编译:
|
||||
# @build-bot build mac 编译 macOS
|
||||
# @build-bot build win-amd 编译 Windows amd64
|
||||
# @build-bot build win-arm 编译 Windows arm64
|
||||
# @build-bot build all 三个平台全编
|
||||
# 产物发布到 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=$(sed -n 's:.*<Version>\(.*\)</Version>.*:\1:p' Directory.Build.props | head -1)
|
||||
[ -n "$VERSION" ] || VERSION=1.0.0
|
||||
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
|
||||
REF=$(gh api "repos/${{ github.repository }}/pulls/${ISSUE_NUMBER}" --jq '.head.sha')
|
||||
else
|
||||
REF="${{ github.event.repository.default_branch }}"
|
||||
fi
|
||||
echo "ref=$REF" >> "$GITHUB_OUTPUT"
|
||||
echo "目标=$TARGET 提交=$REF 是否PR=$IS_PR"
|
||||
|
||||
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 }}
|
||||
|
||||
- uses: subosito/flutter-action@v2
|
||||
with:
|
||||
flutter-version: ${{ env.FLUTTER_VERSION }}
|
||||
channel: stable
|
||||
cache: true
|
||||
|
||||
- name: 编译 macOS
|
||||
env:
|
||||
GC_NO_CODESIGN: '1'
|
||||
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: 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
|
||||
|
||||
- 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}\`)。
|
||||
|
||||
触发人:@${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"
|
||||
|
||||
- name: 回帖
|
||||
if: always()
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
TARGET: ${{ needs.prepare.outputs.target }}
|
||||
ISSUE: ${{ github.event.issue.number }}
|
||||
STATE: ${{ steps.publish_step.outcome }}
|
||||
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
|
||||
run: |
|
||||
if [ "$STATE" = "success" ]; then
|
||||
MSG="已编译 **${TARGET}** 并发布到预发布:https://github.com/${{ github.repository }}/releases/tag/ip-prerelease"
|
||||
else
|
||||
MSG="编译 **${TARGET}** 失败,见日志:${RUN_URL}"
|
||||
fi
|
||||
gh issue comment "$ISSUE" --body "$MSG"
|
||||
@@ -0,0 +1,145 @@
|
||||
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-14
|
||||
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_CODESIGN: '1'
|
||||
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,185 @@
|
||||
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,重试几次
|
||||
STATE="unknown"
|
||||
CONFLICT="unknown"
|
||||
for i in 1 2 3 4 5; do
|
||||
INFO=$(gh api "repos/${{ github.repository }}/pulls/${PR}" --jq '.mergeable, .mergeable_state' 2>/dev/null || true)
|
||||
CONFLICT=$(printf '%s\n' "$INFO" | sed -n '1p')
|
||||
STATE=$(printf '%s\n' "$INFO" | sed -n '2p')
|
||||
if [ "$CONFLICT" = "true" ] || [ "$CONFLICT" = "false" ]; then break; fi
|
||||
sleep 3
|
||||
done
|
||||
|
||||
case "$CONFLICT" in
|
||||
false) echo "conflict=ok" >> "$GITHUB_OUTPUT" ;;
|
||||
true) 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 > dotnet-restore.log 2>&1
|
||||
dotnet build GC.sln -c Release --no-restore 2>&1 | tee 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 ../flutter-pubget.log
|
||||
flutter analyze 2>&1 | tee ../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
|
||||
|
||||
case "$DOTNET_OUTCOME" in
|
||||
success) DOTNET_LINE="✅ .NET 编译通过" ;;
|
||||
*) DOTNET_LINE="❌ .NET 编译失败"; bad=1 ;;
|
||||
esac
|
||||
case "$FLUTTER_OUTCOME" in
|
||||
success) FLUTTER_LINE="✅ Flutter 静态分析通过" ;;
|
||||
*) FLUTTER_LINE="❌ Flutter 静态分析有问题"; 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 行)=="
|
||||
tail -40 flutter-analyze.log 2>/dev/null || echo "(无日志)"
|
||||
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
|
||||
@@ -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,202 @@
|
||||
- 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 互不覆盖。
|
||||
@@ -13,16 +13,8 @@
|
||||
<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>
|
||||
<Version>1.1.2</Version>
|
||||
<Company>Morris</Company>
|
||||
<Product>GC</Product>
|
||||
<NeutralLanguage>zh-Hans</NeutralLanguage>
|
||||
|
||||
@@ -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 的身份校验。
|
||||
// 允许外部预设(自动化测试 / 高级部署固定令牌),未预设才现场生成随机值。
|
||||
@@ -46,7 +54,6 @@ internal static class FlutterShell
|
||||
Environment.SetEnvironmentVariable(Services.GcUiContract.TokenEnvVar, token);
|
||||
|
||||
var port = Port;
|
||||
AvaloniaHost? uiHost = null;
|
||||
|
||||
// 用户可能重复启动:只有当端口上已有一个「持有同一令牌」的后端时才复用。
|
||||
// 同机其他程序即便占端口并返回 200,也没有令牌,会被 IsHealthy 拒绝,
|
||||
@@ -60,14 +67,13 @@ internal static class FlutterShell
|
||||
|
||||
for (var candidate = start; candidate < start + Services.GcUiContract.PortScanRange; candidate++)
|
||||
{
|
||||
var app = TryStartBackend(args, candidate, out var host);
|
||||
var app = TryStartBackend(args, candidate);
|
||||
if (app == null) continue;
|
||||
|
||||
if (WaitHealthy(candidate, token, TimeSpan.FromSeconds(25)))
|
||||
{
|
||||
port = candidate;
|
||||
_backend = app;
|
||||
uiHost = host;
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -87,27 +93,9 @@ internal static class FlutterShell
|
||||
return false;
|
||||
}
|
||||
|
||||
// 前端窗口已拉起。模型窗口由 Avalonia 承载,而 macOS 的 AppKit 要求
|
||||
// NSApplication 必须在**主线程**——所以事件循环要跑在这里(当前正是主线程),
|
||||
// 不能再丢到副线程,否则一点「启动模型」就会把整个后端带崩。
|
||||
// 前端窗口已拉起。这里不再需要 AppKit 事件循环:模型已经全部在 Flutter 里渲染,
|
||||
// 后端只是纯 HTTP 服务,主线程阻塞等它退出即可。
|
||||
ui.EnableRaisingEvents = true;
|
||||
var closed = 0;
|
||||
void RequestClose()
|
||||
{
|
||||
if (Interlocked.Exchange(ref closed, 1) == 1) return;
|
||||
uiHost?.Shutdown();
|
||||
}
|
||||
|
||||
ui.Exited += (_, _) => RequestClose();
|
||||
if (ui.HasExited) RequestClose();
|
||||
|
||||
if (!ui.HasExited && uiHost != null)
|
||||
{
|
||||
// 阻塞直到界面退出(或图形环境初始化失败)。
|
||||
uiHost.RunOnCurrentThread();
|
||||
}
|
||||
|
||||
// Avalonia 起不来(无桌面会话)时仍要等界面退出,避免后端被提前收掉。
|
||||
if (!ui.HasExited) ui.WaitForExit();
|
||||
|
||||
StopBackend(_backend);
|
||||
@@ -115,6 +103,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>
|
||||
@@ -141,14 +158,11 @@ internal static class FlutterShell
|
||||
// ---------------------------------------------------------------- 进程管理
|
||||
|
||||
/// <summary>在本进程内启动后端;端口被占用等失败情况返回 null。</summary>
|
||||
/// <param name="uiHost">成功时交出模型窗口宿主,由调用方在主线程跑事件循环。</param>
|
||||
private static WebApplication? TryStartBackend(string[] args, int port, out AvaloniaHost? uiHost)
|
||||
private static WebApplication? TryStartBackend(string[] args, int port)
|
||||
{
|
||||
uiHost = null;
|
||||
try
|
||||
{
|
||||
var app = BackendServer.Start(args, port, out var host);
|
||||
uiHost = host;
|
||||
var app = BackendServer.Start(args, port);
|
||||
app.StartAsync().GetAwaiter().GetResult();
|
||||
return app;
|
||||
}
|
||||
|
||||
@@ -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 图标,不影响功能。
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -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}")
|
||||
};
|
||||
}
|
||||
@@ -1,642 +0,0 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using Avalonia;
|
||||
using Avalonia.Animation;
|
||||
using Avalonia.Animation.Easings;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Input;
|
||||
using Avalonia.Layout;
|
||||
using Avalonia.Media;
|
||||
using Shapes = Avalonia.Controls.Shapes;
|
||||
using Avalonia.VisualTree;
|
||||
using GC.Models;
|
||||
using GC.Services;
|
||||
|
||||
namespace GC.Views;
|
||||
|
||||
/// <summary>
|
||||
/// 模型窗口:**只做窗口宿主**。
|
||||
/// 内容完全来自模型程序集(<see cref="LoadedModel.View"/>),启动器不渲染任何东西。
|
||||
/// 快捷键:Esc 关闭窗口,F11 全屏。
|
||||
/// </summary>
|
||||
public sealed class PlayerWindow : Window
|
||||
{
|
||||
private LoadedModel? _model;
|
||||
private bool _closing;
|
||||
private Button? _maximizeButton;
|
||||
private Border? _frame;
|
||||
private TextBlock? _titleText;
|
||||
private Border? _titleBar;
|
||||
private readonly List<Button> _titleButtons = new();
|
||||
private readonly List<Shapes.Path> _titleGlyphs = new();
|
||||
private Shapes.Path? _maximizeGlyph;
|
||||
private Shapes.Path? _restoreGlyph;
|
||||
private string _maxMaxPath = "";
|
||||
private string _maxRestorePath = "";
|
||||
private Button? _helpButton;
|
||||
/// <summary>基准尺寸(1240×820 时的标题栏高度与按钮尺寸)。</summary>
|
||||
private const double BaseWidth = 1240;
|
||||
private const double BaseTitleBarHeight = 34;
|
||||
private const double BaseButtonWidth = 38;
|
||||
private const double BaseButtonHeight = 28;
|
||||
private const double BaseTitleFont = 11.5;
|
||||
private const double BaseHelpFont = 11.5;
|
||||
|
||||
public PlayerWindow(ModelPackage package, LoadedModel model)
|
||||
{
|
||||
_model = model;
|
||||
Title = package.LocalizedName;
|
||||
Width = 1240;
|
||||
Height = 820;
|
||||
MinWidth = 1000;
|
||||
MinHeight = 680;
|
||||
Background = Brushes.Transparent;
|
||||
TransparencyLevelHint = new[] { WindowTransparencyLevel.Transparent };
|
||||
WindowStartupLocation = WindowStartupLocation.CenterOwner;
|
||||
// 与启动器一致:去掉系统标题栏,自己做一个极简顶栏(否则 Esc 之外无法关闭)
|
||||
SystemDecorations = Avalonia.Controls.SystemDecorations.None;
|
||||
|
||||
// 标题栏配色来自模型清单,跟随模型自己的界面风格:
|
||||
// 地球模型是深色舞台,比例尺计算器是浅色卡片,两者不能共用一套深色。
|
||||
var chrome = package.Manifest.Chrome;
|
||||
var barBg = ParseColor(chrome?.TitleBar, "#0C1828");
|
||||
var barBorder = ParseColor(chrome?.TitleBorder, "#1B2740");
|
||||
var barText = ParseColor(chrome?.TitleText, "#EAF2FF");
|
||||
var btnText = ParseColor(chrome?.Button, "#9FB4D4");
|
||||
var frameBg = ParseColor(chrome?.Frame, "#0A1524");
|
||||
|
||||
var titleText = new TextBlock
|
||||
{
|
||||
Text = package.LocalizedName,
|
||||
Foreground = new SolidColorBrush(barText),
|
||||
FontSize = 11.5,
|
||||
Margin = new Thickness(14, 0, 0, 0),
|
||||
VerticalAlignment = VerticalAlignment.Center,
|
||||
[Grid.ColumnProperty] = 0
|
||||
};
|
||||
_titleText = titleText;
|
||||
|
||||
var helpButton = new Button
|
||||
{
|
||||
Content = IsEnglish() ? "How to use?" : "如何使用?",
|
||||
Height = 26,
|
||||
Padding = new Thickness(12, 0),
|
||||
Background = Brushes.Transparent,
|
||||
Foreground = new SolidColorBrush(btnText),
|
||||
BorderThickness = new Thickness(0),
|
||||
FontSize = 11.5,
|
||||
CornerRadius = new CornerRadius(7),
|
||||
Margin = new Thickness(0, 0, 6, 0),
|
||||
HorizontalContentAlignment = HorizontalAlignment.Center,
|
||||
VerticalContentAlignment = VerticalAlignment.Center,
|
||||
Cursor = new Cursor(StandardCursorType.Hand),
|
||||
[Grid.ColumnProperty] = 1
|
||||
};
|
||||
helpButton.Click += (_, _) => ShowHelp(package, barBg, barBorder, barText, btnText, frameBg);
|
||||
|
||||
// 标题栏三键:最小化 / 最大化 / 关闭 —— 卡通画风。
|
||||
// 每颗按钮 = 彩色实心圆底 + 粗圆头描边图标,像一颗小糖豆。
|
||||
(Button Btn, Shapes.Path Icon) MakeBadge(int column, string iconPath)
|
||||
{
|
||||
// 纯矢量图标,没有彩色圆圈
|
||||
var icon = new Shapes.Path
|
||||
{
|
||||
Data = Geometry.Parse(iconPath),
|
||||
Stroke = new SolidColorBrush(btnText),
|
||||
StrokeThickness = 1.5,
|
||||
StrokeLineCap = PenLineCap.Round,
|
||||
StrokeJoin = PenLineJoin.Round,
|
||||
Fill = null,
|
||||
Stretch = Stretch.None,
|
||||
Width = 10,
|
||||
Height = 10,
|
||||
HorizontalAlignment = HorizontalAlignment.Center,
|
||||
VerticalAlignment = VerticalAlignment.Center
|
||||
};
|
||||
var layer = new Grid
|
||||
{
|
||||
HorizontalAlignment = HorizontalAlignment.Center,
|
||||
VerticalAlignment = VerticalAlignment.Center
|
||||
};
|
||||
layer.Children.Add(icon);
|
||||
|
||||
var b = new Button
|
||||
{
|
||||
Width = 38,
|
||||
Height = 28,
|
||||
Background = Brushes.Transparent,
|
||||
BorderThickness = new Thickness(0),
|
||||
CornerRadius = new CornerRadius(9),
|
||||
Padding = new Thickness(0),
|
||||
Margin = new Thickness(2, 0, 0, 0),
|
||||
Content = layer,
|
||||
HorizontalContentAlignment = HorizontalAlignment.Center,
|
||||
VerticalContentAlignment = VerticalAlignment.Center,
|
||||
Cursor = new Cursor(StandardCursorType.Hand),
|
||||
[Grid.ColumnProperty] = column
|
||||
};
|
||||
var hoverBg = IsLight(barBg)
|
||||
? new SolidColorBrush(Color.Parse("#EEF1F7"))
|
||||
: new SolidColorBrush(Color.Parse("#1E2C46"));
|
||||
var isCloseBtn = column == 4;
|
||||
b.PointerEntered += (_, _) =>
|
||||
{
|
||||
b.Background = hoverBg;
|
||||
icon.Stroke = new SolidColorBrush(isCloseBtn ? Colors.White
|
||||
: IsLight(barBg) ? Color.Parse("#111A2E") : Colors.White);
|
||||
};
|
||||
b.PointerExited += (_, _) =>
|
||||
{
|
||||
b.Background = Brushes.Transparent;
|
||||
icon.Stroke = new SolidColorBrush(btnText);
|
||||
};
|
||||
b.Classes.Add("model-titlebtn");
|
||||
_titleButtons.Add(b);
|
||||
_titleGlyphs.Add(icon);
|
||||
return (b, icon);
|
||||
}
|
||||
|
||||
// 卡通配色:暖黄 / 薄荷绿 / 珊瑚红
|
||||
var minBadge = MakeBadge(2, "M1.5,5 L8.5,5");
|
||||
var maxBadge = MakeBadge(3, "M2.2,2.2 L7.8,2.2 L7.8,7.8 L2.2,7.8 Z");
|
||||
var closeBadge = MakeBadge(4, "M2,2 L8,8 M8,2 L2,8");
|
||||
|
||||
var minimizeButton = minBadge.Btn;
|
||||
var maximizeButton = maxBadge.Btn;
|
||||
var closeButton = closeBadge.Btn;
|
||||
|
||||
minimizeButton.Click += (_, _) => WindowState = WindowState.Minimized;
|
||||
maximizeButton.Click += (_, _) => ToggleMaximize();
|
||||
closeButton.Click += (_, _) => _ = CloseWithAnimationAsync();
|
||||
_maximizeGlyph = maxBadge.Icon;
|
||||
_restoreGlyph = maxBadge.Icon;
|
||||
_maxRestorePath = "M2.6,3.6 L7.4,3.6 L7.4,8.4 L2.6,8.4 Z M2.6,3.6 L2.6,1.6 L7.4,1.6 L7.4,6.4";
|
||||
_maxMaxPath = "M2.2,2.2 L7.8,2.2 L7.8,7.8 L2.2,7.8 Z";
|
||||
|
||||
var titleBar = new Border
|
||||
{
|
||||
Height = 34,
|
||||
Background = new SolidColorBrush(barBg),
|
||||
BorderBrush = new SolidColorBrush(barBorder),
|
||||
BorderThickness = new Thickness(0, 0, 0, 1),
|
||||
Child = new Grid
|
||||
{
|
||||
ColumnDefinitions = new ColumnDefinitions("*,Auto,Auto,Auto,Auto,Auto"),
|
||||
Margin = new Thickness(0, 0, 10, 0),
|
||||
Children = { titleText, helpButton, minimizeButton, maximizeButton, closeButton }
|
||||
}
|
||||
};
|
||||
titleBar.PointerPressed += OnTitleBarPointerPressed;
|
||||
// 双击标题栏 = 最大化 / 还原(与系统标题栏一致)
|
||||
titleBar.DoubleTapped += (_, e) =>
|
||||
{
|
||||
if (e.Source is Button) return;
|
||||
ToggleMaximize();
|
||||
};
|
||||
_maximizeButton = maximizeButton;
|
||||
_titleBar = titleBar;
|
||||
_helpButton = helpButton;
|
||||
_titleButtons.Add(minimizeButton);
|
||||
_titleButtons.Add(maximizeButton);
|
||||
_titleButtons.Add(closeButton);
|
||||
|
||||
var dock = new DockPanel { LastChildFill = true };
|
||||
DockPanel.SetDock(titleBar, Dock.Top);
|
||||
dock.Children.Add(titleBar);
|
||||
dock.Children.Add(model.View);
|
||||
|
||||
Content = new Border
|
||||
{
|
||||
CornerRadius = new CornerRadius(16),
|
||||
Background = new SolidColorBrush(frameBg),
|
||||
ClipToBounds = true,
|
||||
Child = dock
|
||||
};
|
||||
_frame = (Border)Content;
|
||||
|
||||
// 最大化 / 还原时同步圆角与按钮图标
|
||||
PropertyChanged += (_, e) =>
|
||||
{
|
||||
if (e.Property == WindowStateProperty) UpdateMaximizeVisual();
|
||||
};
|
||||
|
||||
// 窗口随心拉大 / 拉小时,标题栏文字与按钮同比缩放。
|
||||
// 同时监听 Bounds 属性(不只是 SizeChanged),保证最大化/还原也立刻生效。
|
||||
SizeChanged += (_, _) => ApplyChromeScale();
|
||||
PropertyChanged += (_, e) =>
|
||||
{
|
||||
if (e.Property == BoundsProperty) ApplyChromeScale();
|
||||
};
|
||||
ApplyChromeScale();
|
||||
|
||||
KeyDown += OnKeyDown;
|
||||
Closed += OnClosed;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 让标题栏的文字与按钮尺寸跟随窗口大小。
|
||||
/// 以 1240px 宽为基准线性缩放,限制在 0.85–1.9 倍,
|
||||
/// 避免最大化到 4K 时按钮大得离谱、缩到最小又点不中。
|
||||
/// </summary>
|
||||
private void ApplyChromeScale()
|
||||
{
|
||||
if (Bounds.Width < 100) return;
|
||||
var scale = Math.Clamp(Bounds.Width / BaseWidth, 0.85, 1.9);
|
||||
|
||||
if (_titleBar != null) _titleBar.Height = Math.Round(BaseTitleBarHeight * scale);
|
||||
foreach (var b in _titleButtons)
|
||||
{
|
||||
b.Width = Math.Round(BaseButtonWidth * scale);
|
||||
b.Height = Math.Round(BaseButtonHeight * scale);
|
||||
b.FontSize = Math.Round(13 * scale, 1);
|
||||
b.CornerRadius = new CornerRadius(Math.Round(7 * scale, 1));
|
||||
}
|
||||
if (_helpButton != null)
|
||||
{
|
||||
_helpButton.Height = Math.Round(26 * scale);
|
||||
_helpButton.FontSize = Math.Round(BaseHelpFont * scale, 1);
|
||||
_helpButton.Padding = new Thickness(Math.Round(12 * scale), 0);
|
||||
_helpButton.CornerRadius = new CornerRadius(Math.Round(7 * scale, 1));
|
||||
}
|
||||
foreach (var g in _titleGlyphs)
|
||||
{
|
||||
g.Width = Math.Round(10 * scale, 1);
|
||||
g.Height = Math.Round(10 * scale, 1);
|
||||
g.StrokeThickness = Math.Round(1.5 * scale, 2);
|
||||
}
|
||||
if (_titleText != null)
|
||||
{
|
||||
_titleText.FontSize = Math.Round(BaseTitleFont * scale, 1);
|
||||
_titleText.Margin = new Thickness(Math.Round(14 * scale), 0, 0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>判断颜色是否属于浅色系(用于决定悬停用深色还是浅色)。</summary>
|
||||
private static bool IsLight(Color c)
|
||||
{
|
||||
// 相对亮度(sRGB 近似)
|
||||
var lum = (0.299 * c.R + 0.587 * c.G + 0.114 * c.B) / 255.0;
|
||||
return lum > 0.6;
|
||||
}
|
||||
|
||||
private void ToggleMaximize()
|
||||
{
|
||||
WindowState = WindowState == WindowState.Maximized
|
||||
? WindowState.Normal
|
||||
: WindowState.Maximized;
|
||||
}
|
||||
|
||||
private void UpdateMaximizeVisual()
|
||||
{
|
||||
var max = WindowState == WindowState.Maximized || WindowState == WindowState.FullScreen;
|
||||
if (_maximizeGlyph != null)
|
||||
{
|
||||
// 只换 Data,不换控件对象(换对象会触发 "already has a parent")
|
||||
_maximizeGlyph.Data = Geometry.Parse(max ? _maxRestorePath : _maxMaxPath);
|
||||
}
|
||||
if (_maximizeButton != null)
|
||||
{
|
||||
Avalonia.Controls.ToolTip.SetTip(_maximizeButton, max
|
||||
? (IsEnglish() ? "Restore" : "还原")
|
||||
: (IsEnglish() ? "Maximize" : "最大化"));
|
||||
}
|
||||
// 最大化后同样保留圆角(用户要求:任何状态都要圆角)
|
||||
if (_frame != null) _frame.CornerRadius = new CornerRadius(16);
|
||||
}
|
||||
|
||||
private static Color ParseColor(string? hex, string fallback)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(hex))
|
||||
{
|
||||
try { return Color.Parse(hex!); }
|
||||
catch { /* 模型写错颜色时退回默认 */ }
|
||||
}
|
||||
return Color.Parse(fallback);
|
||||
}
|
||||
|
||||
private static bool IsEnglish() => L.I.Language.StartsWith("en", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>
|
||||
/// 「如何使用?」:读取模型自带数据目录里的 help.json(中英双语),
|
||||
/// 用与标题栏一致的配色弹出一个独立小窗。说明内容完全由模型提供,启动器不内置文案。
|
||||
/// </summary>
|
||||
private void ShowHelp(ModelPackage package, Color barBg, Color barBorder, Color barText,
|
||||
Color btnText, Color frameBg)
|
||||
{
|
||||
var lang = IsEnglish() ? "en" : "zh-CN";
|
||||
var file = Path.Combine(package.DataDirectory, "help.json");
|
||||
string title = IsEnglish() ? "How to use" : "如何使用";
|
||||
// 分节内容:每节一个标题 + 若干条说明;兼容旧的扁平 lines 格式
|
||||
var sections = new List<(string Heading, List<string> Lines)>();
|
||||
|
||||
if (File.Exists(file))
|
||||
{
|
||||
try
|
||||
{
|
||||
using var doc = JsonDocument.Parse(File.ReadAllText(file));
|
||||
var root = doc.RootElement;
|
||||
var node = root.TryGetProperty(lang, out var exact) ? exact
|
||||
: root.TryGetProperty("zh-CN", out var zh) ? zh : root;
|
||||
if (node.TryGetProperty("title", out var t)) title = t.GetString() ?? title;
|
||||
|
||||
if (node.TryGetProperty("sections", out var arr) && arr.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
foreach (var sec in arr.EnumerateArray())
|
||||
{
|
||||
var heading = sec.TryGetProperty("h", out var h) ? h.GetString() ?? "" : "";
|
||||
var items = new List<string>();
|
||||
if (sec.TryGetProperty("lines", out var ls) && ls.ValueKind == JsonValueKind.Array)
|
||||
foreach (var item in ls.EnumerateArray())
|
||||
if (item.ValueKind == JsonValueKind.String) items.Add(item.GetString() ?? "");
|
||||
if (items.Count > 0) sections.Add((heading, items));
|
||||
}
|
||||
}
|
||||
else if (node.TryGetProperty("lines", out var flat) && flat.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
var items = new List<string>();
|
||||
foreach (var item in flat.EnumerateArray())
|
||||
if (item.ValueKind == JsonValueKind.String) items.Add(item.GetString() ?? "");
|
||||
if (items.Count > 0) sections.Add(("", items));
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"读取模型帮助失败 {file}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
if (sections.Count == 0)
|
||||
sections.Add(("", new List<string>
|
||||
{
|
||||
IsEnglish() ? "This model has no usage notes yet." : "该模型暂未提供使用说明。"
|
||||
}));
|
||||
|
||||
var body = new StackPanel { Spacing = 6 };
|
||||
foreach (var (heading, items) in sections)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(heading))
|
||||
body.Children.Add(new TextBlock
|
||||
{
|
||||
Text = heading,
|
||||
Foreground = new SolidColorBrush(barText),
|
||||
FontSize = 13.5,
|
||||
FontWeight = FontWeight.SemiBold,
|
||||
Margin = new Thickness(0, 12, 0, 2)
|
||||
});
|
||||
foreach (var line in items)
|
||||
body.Children.Add(new TextBlock
|
||||
{
|
||||
Text = "• " + line,
|
||||
Foreground = new SolidColorBrush(btnText),
|
||||
FontSize = 12.5,
|
||||
TextWrapping = TextWrapping.Wrap,
|
||||
LineHeight = 19
|
||||
});
|
||||
}
|
||||
|
||||
// ── 帮助窗口自建标题栏(带 ✕),与模型窗口同款配色 ──
|
||||
// 纯矢量图标,无彩色圆底(与三个窗口按钮保持一致)
|
||||
var helpCross = new Shapes.Path
|
||||
{
|
||||
Data = Geometry.Parse("M2,2 L8,8 M8,2 L2,8"),
|
||||
Stroke = new SolidColorBrush(btnText),
|
||||
StrokeThickness = 1.5,
|
||||
StrokeLineCap = PenLineCap.Round,
|
||||
Fill = null,
|
||||
Stretch = Stretch.None,
|
||||
Width = 10, Height = 10,
|
||||
HorizontalAlignment = HorizontalAlignment.Center,
|
||||
VerticalAlignment = VerticalAlignment.Center
|
||||
};
|
||||
|
||||
var helpClose = new Button
|
||||
{
|
||||
Content = helpCross,
|
||||
Width = 34,
|
||||
Height = 26,
|
||||
Background = Brushes.Transparent,
|
||||
BorderThickness = new Thickness(0),
|
||||
CornerRadius = new CornerRadius(9),
|
||||
Padding = new Thickness(0),
|
||||
Margin = new Thickness(6, 0, 0, 0),
|
||||
HorizontalContentAlignment = HorizontalAlignment.Center,
|
||||
VerticalContentAlignment = VerticalAlignment.Center,
|
||||
Cursor = new Cursor(StandardCursorType.Hand)
|
||||
};
|
||||
helpClose.PointerEntered += (_, _) =>
|
||||
{
|
||||
helpClose.Background = new SolidColorBrush(IsLight(frameBg)
|
||||
? Color.Parse("#EEF1F7") : Color.Parse("#1E2C46"));
|
||||
helpCross.Stroke = new SolidColorBrush(Colors.White);
|
||||
};
|
||||
helpClose.PointerExited += (_, _) =>
|
||||
{
|
||||
helpClose.Background = Brushes.Transparent;
|
||||
helpCross.Stroke = new SolidColorBrush(btnText);
|
||||
};
|
||||
|
||||
var helpTitle = new TextBlock
|
||||
{
|
||||
Text = title,
|
||||
Foreground = new SolidColorBrush(barText),
|
||||
FontSize = 16,
|
||||
FontWeight = FontWeight.SemiBold,
|
||||
VerticalAlignment = VerticalAlignment.Center
|
||||
};
|
||||
|
||||
var helpBarGrid = new Grid
|
||||
{
|
||||
ColumnDefinitions = new ColumnDefinitions("*,Auto"),
|
||||
Margin = new Thickness(22, 0, 14, 0)
|
||||
};
|
||||
helpBarGrid.Children.Add(helpTitle);
|
||||
Grid.SetColumn(helpClose, 1);
|
||||
helpBarGrid.Children.Add(helpClose);
|
||||
|
||||
var helpTitleBar = new Border
|
||||
{
|
||||
Height = 48,
|
||||
Background = new SolidColorBrush(barBg),
|
||||
BorderBrush = new SolidColorBrush(barBorder),
|
||||
BorderThickness = new Thickness(0, 0, 0, 1),
|
||||
Child = helpBarGrid
|
||||
};
|
||||
helpTitleBar.PointerPressed += (_, e) =>
|
||||
{
|
||||
if (e.GetCurrentPoint(helpTitleBar).Properties.IsLeftButtonPressed)
|
||||
helpClose.FindAncestorOfType<Window>()?.BeginMoveDrag(e);
|
||||
};
|
||||
|
||||
// ── 底部固定操作条:无论正文多长,「知道了」始终可见 ──
|
||||
var ok = new Button
|
||||
{
|
||||
Content = IsEnglish() ? "Got it" : "知道了",
|
||||
HorizontalAlignment = HorizontalAlignment.Right,
|
||||
Padding = new Thickness(20, 8),
|
||||
Background = new SolidColorBrush(Color.Parse("#2F6BFF")),
|
||||
Foreground = new SolidColorBrush(Colors.White),
|
||||
BorderThickness = new Thickness(0),
|
||||
CornerRadius = new CornerRadius(8),
|
||||
Cursor = new Cursor(StandardCursorType.Hand)
|
||||
};
|
||||
var footer = new Border
|
||||
{
|
||||
Padding = new Thickness(24, 10, 24, 14),
|
||||
BorderBrush = new SolidColorBrush(barBorder),
|
||||
BorderThickness = new Thickness(0, 1, 0, 0),
|
||||
Child = ok
|
||||
};
|
||||
|
||||
// 标题栏(顶) + 正文(中,滚动) + 操作条(底,固定)
|
||||
var rootPanel = new DockPanel { LastChildFill = true };
|
||||
DockPanel.SetDock(helpTitleBar, Dock.Top);
|
||||
rootPanel.Children.Add(helpTitleBar);
|
||||
DockPanel.SetDock(footer, Dock.Bottom);
|
||||
rootPanel.Children.Add(footer);
|
||||
var scroll = new ScrollViewer
|
||||
{
|
||||
Content = new Border
|
||||
{
|
||||
Margin = new Thickness(24, 14, 24, 10),
|
||||
Child = body
|
||||
},
|
||||
VerticalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto,
|
||||
HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Disabled
|
||||
};
|
||||
rootPanel.Children.Add(scroll);
|
||||
|
||||
var win = new Window
|
||||
{
|
||||
Title = title,
|
||||
Width = 660,
|
||||
Height = Math.Min(760, 230 + sections.Sum(s => s.Lines.Count * 24 + 40)),
|
||||
MinWidth = 480,
|
||||
MinHeight = 320,
|
||||
Background = Brushes.Transparent,
|
||||
TransparencyLevelHint = new[] { WindowTransparencyLevel.Transparent },
|
||||
SystemDecorations = SystemDecorations.None,
|
||||
WindowStartupLocation = WindowStartupLocation.CenterOwner,
|
||||
Content = new Border
|
||||
{
|
||||
CornerRadius = new CornerRadius(16),
|
||||
Background = new SolidColorBrush(frameBg),
|
||||
BorderBrush = new SolidColorBrush(barBorder),
|
||||
BorderThickness = new Thickness(1),
|
||||
ClipToBounds = true,
|
||||
Child = rootPanel
|
||||
}
|
||||
};
|
||||
ok.Click += (_, _) => win.Close();
|
||||
helpClose.Click += (_, _) => win.Close();
|
||||
win.Show(this);
|
||||
}
|
||||
|
||||
private void OnTitleBarPointerPressed(object? sender, PointerPressedEventArgs e)
|
||||
{
|
||||
if (e.GetCurrentPoint(this).Properties.IsLeftButtonPressed)
|
||||
BeginMoveDrag(e);
|
||||
}
|
||||
|
||||
private void OnKeyDown(object? sender, KeyEventArgs e)
|
||||
{
|
||||
switch (e.Key)
|
||||
{
|
||||
case Key.Escape:
|
||||
_ = CloseWithAnimationAsync();
|
||||
e.Handled = true;
|
||||
break;
|
||||
case Key.F11:
|
||||
WindowState = WindowState == WindowState.FullScreen
|
||||
? WindowState.Normal
|
||||
: WindowState.FullScreen;
|
||||
e.Handled = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 关闭动画:淡出 + 轻微缩小,动画结束后再真正关闭窗口。
|
||||
/// 与主窗口的关闭动画保持同一节奏(180ms)。
|
||||
/// </summary>
|
||||
private async Task CloseWithAnimationAsync()
|
||||
{
|
||||
if (_closing) return;
|
||||
_closing = true;
|
||||
|
||||
Transitions = new Transitions
|
||||
{
|
||||
new DoubleTransition
|
||||
{
|
||||
Property = OpacityProperty,
|
||||
Duration = TimeSpan.FromMilliseconds(180),
|
||||
Easing = new CubicEaseIn()
|
||||
}
|
||||
};
|
||||
Opacity = 0;
|
||||
|
||||
await Task.Delay(190);
|
||||
Close();
|
||||
}
|
||||
|
||||
private void OnClosed(object? sender, EventArgs e)
|
||||
{
|
||||
Content = null;
|
||||
_model?.Dispose();
|
||||
_model = null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>模型加载失败时显示的提示窗口(不含任何渲染逻辑)。</summary>
|
||||
public sealed class ModelErrorWindow : Window
|
||||
{
|
||||
public ModelErrorWindow(string title, string message)
|
||||
{
|
||||
Title = title;
|
||||
Width = 560;
|
||||
Height = 340;
|
||||
Background = Brushes.Transparent;
|
||||
TransparencyLevelHint = new[] { WindowTransparencyLevel.Transparent };
|
||||
WindowStartupLocation = WindowStartupLocation.CenterOwner;
|
||||
|
||||
var lines = new List<Control>
|
||||
{
|
||||
new TextBlock
|
||||
{
|
||||
Text = title,
|
||||
Foreground = new SolidColorBrush(Color.Parse("#F2F6FF")),
|
||||
FontSize = 16,
|
||||
FontWeight = FontWeight.SemiBold
|
||||
},
|
||||
new TextBlock
|
||||
{
|
||||
Text = message,
|
||||
Foreground = new SolidColorBrush(Color.Parse("#8CA0C4")),
|
||||
FontSize = 12,
|
||||
TextWrapping = TextWrapping.Wrap
|
||||
},
|
||||
new Button
|
||||
{
|
||||
Content = "确定",
|
||||
HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Right,
|
||||
Padding = new Thickness(18, 6)
|
||||
}
|
||||
};
|
||||
|
||||
var panel = new StackPanel
|
||||
{
|
||||
Margin = new Thickness(24),
|
||||
Spacing = 14
|
||||
};
|
||||
foreach (var line in lines) panel.Children.Add(line);
|
||||
if (lines[^1] is Button ok) ok.Click += (_, _) => Close();
|
||||
Content = new Border
|
||||
{
|
||||
CornerRadius = new CornerRadius(12),
|
||||
Background = new SolidColorBrush(Color.Parse("#0B1226")),
|
||||
Child = panel
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -123,6 +123,19 @@ public sealed record UpdateCheckDto(
|
||||
|
||||
public sealed record ContributorDto(string Name, int Contributions, string? AvatarUrl);
|
||||
|
||||
// ---- 用户 API DTO ----
|
||||
public sealed record RegisterRequest(string Username, string Password);
|
||||
public sealed record LoginRequest(string Username, string Password);
|
||||
public sealed record ThemeRequest(string Color, int Cost);
|
||||
|
||||
|
||||
/// <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,
|
||||
|
||||
@@ -1,180 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Controls.ApplicationLifetimes;
|
||||
using Avalonia.Threading;
|
||||
using GC.Models;
|
||||
using GC.Services;
|
||||
using GC.Views;
|
||||
|
||||
namespace GC.UI.Server;
|
||||
|
||||
/// <summary>
|
||||
/// 模型窗口宿主。
|
||||
///
|
||||
/// 为什么渲染这一层留在 .NET:模型 dll 通过 <c>IModelRuntime.CreateView</c> 返回的是
|
||||
/// Avalonia <see cref="Control"/>,这是模型契约的一部分。把渲染栈换成 Flutter 等于换掉契约,
|
||||
/// 所有已发布模型都会失效。所以前后端分离的切法是:
|
||||
/// · 界面(首页 / 下载 / 设置 / 关于)→ Flutter 前端
|
||||
/// · 模型窗口(模型自带界面)→ 仍由 .NET 承载,前端只发一条「启动模型」的指令
|
||||
///
|
||||
/// 这里惰性启动一个没有主窗口的 Avalonia 桌面生命周期,之后所有模型窗口都在它的 UI 线程上创建。
|
||||
/// 无桌面会话(CI / 无头环境)时启动会失败,此时只有「启动模型」不可用,其余接口照常工作。
|
||||
/// </summary>
|
||||
public sealed class AvaloniaHost
|
||||
{
|
||||
private readonly AppServices _services;
|
||||
private readonly object _gate = new();
|
||||
private readonly Dictionary<string, PlayerWindow> _windows = new(StringComparer.OrdinalIgnoreCase);
|
||||
private readonly TaskCompletionSource<bool> _ready =
|
||||
new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
private int _started;
|
||||
|
||||
public AvaloniaHost(AppServices services) => _services = services;
|
||||
|
||||
public bool IsAvailable { get; private set; }
|
||||
|
||||
public string? LastError { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// 后端线程调用:等待「主线程已把 Avalonia 事件循环跑起来」。
|
||||
///
|
||||
/// 关键点:macOS 的 AppKit 要求 NSApplication 在**主线程**。以前这里把
|
||||
/// <c>StartWithClassicDesktopLifetime</c> 丢到一个新建的后台线程里跑,在 macOS 上
|
||||
/// 会直接崩掉整个后端进程(表现为点「启动模型」界面无反应、随后后端消失)。
|
||||
/// 现在改为由启动器在主线程调用 <see cref="RunOnCurrentThread"/>,
|
||||
/// 这里只等待就绪信号。
|
||||
/// </summary>
|
||||
public Task<bool> EnsureStartedAsync() => _ready.Task;
|
||||
|
||||
/// <summary>
|
||||
/// 必须在 UI 主线程调用。启动 Avalonia 桌面生命周期并阻塞,直到 <see cref="Shutdown"/>。
|
||||
/// 返回后(或初始化失败后)调用方负责收尾。
|
||||
/// </summary>
|
||||
public void RunOnCurrentThread()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _started, 1) == 1) return;
|
||||
|
||||
try
|
||||
{
|
||||
AppBuilder.Configure<HostApp>()
|
||||
.UsePlatformDetect()
|
||||
.AfterSetup(_ =>
|
||||
{
|
||||
IsAvailable = true;
|
||||
_ready.TrySetResult(true);
|
||||
})
|
||||
.StartWithClassicDesktopLifetime(Array.Empty<string>());
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// 无桌面会话(CI / 无头环境):模型窗口不可用,但后端其余接口照常。
|
||||
LastError = ex.Message;
|
||||
_ready.TrySetResult(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>从任意线程请求结束事件循环,使 <see cref="RunOnCurrentThread"/> 返回。</summary>
|
||||
public void Shutdown()
|
||||
{
|
||||
if (_started == 0) return;
|
||||
try
|
||||
{
|
||||
Dispatcher.UIThread.Post(() =>
|
||||
{
|
||||
if (Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
|
||||
desktop.Shutdown();
|
||||
});
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 事件循环尚未建立或已退出:无需处理
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>在 Avalonia UI 线程上加载模型并打开它自己的窗口。</summary>
|
||||
public async Task<string> LaunchAsync(ModelPackage package)
|
||||
{
|
||||
if (!await EnsureStartedAsync().ConfigureAwait(false))
|
||||
throw new InvalidOperationException(
|
||||
LastError ?? "无法初始化图形环境(当前会话没有桌面?)");
|
||||
|
||||
return await Dispatcher.UIThread.InvokeAsync<string>(async () =>
|
||||
{
|
||||
// 同一个模型已经在运行:把已有窗口提到前台,不再加载第二份实例
|
||||
// (连点「启动模型」会各占一份内存与显存,低配机器直接卡死)。
|
||||
lock (_gate)
|
||||
{
|
||||
if (_windows.TryGetValue(package.Id, out var existing))
|
||||
{
|
||||
try
|
||||
{
|
||||
if (existing.WindowState == WindowState.Minimized)
|
||||
existing.WindowState = WindowState.Normal;
|
||||
existing.Activate();
|
||||
return $"模型 {package.Id} 已在运行";
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 窗口已失效:清掉记录,按新窗口重新打开
|
||||
_windows.Remove(package.Id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
PlayerWindow? window = null;
|
||||
LoadedModel? loaded = null;
|
||||
try
|
||||
{
|
||||
Action requestClose = () => Dispatcher.UIThread.Post(() =>
|
||||
{
|
||||
try { window?.Close(); } catch { /* 已关闭 */ }
|
||||
});
|
||||
|
||||
loaded = await _services.ModelHost.LoadAsync(package, requestClose, null);
|
||||
|
||||
window = new PlayerWindow(package, loaded);
|
||||
var captured = loaded;
|
||||
var id = package.Id;
|
||||
window.Closed += (_, _) =>
|
||||
{
|
||||
try { captured.Dispose(); } catch { /* 释放失败不影响退出 */ }
|
||||
lock (_gate)
|
||||
{
|
||||
if (_windows.TryGetValue(id, out var current) && ReferenceEquals(current, window))
|
||||
_windows.Remove(id);
|
||||
}
|
||||
};
|
||||
|
||||
lock (_gate) _windows[id] = window;
|
||||
window.Show();
|
||||
return $"已启动模型 {package.Id}";
|
||||
}
|
||||
catch
|
||||
{
|
||||
try { loaded?.Dispose(); } catch { /* 忽略 */ }
|
||||
throw;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>后端自己的 Avalonia 应用:没有主窗口,只用来承载模型窗口。</summary>
|
||||
internal sealed class HostApp : Application
|
||||
{
|
||||
public override void Initialize() { }
|
||||
|
||||
public override void OnFrameworkInitializationCompleted()
|
||||
{
|
||||
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
|
||||
{
|
||||
desktop.ShutdownMode = ShutdownMode.OnExplicitShutdown;
|
||||
desktop.MainWindow = null;
|
||||
}
|
||||
|
||||
base.OnFrameworkInitializationCompleted();
|
||||
}
|
||||
}
|
||||
@@ -30,33 +30,21 @@ 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,本进程只提供 HTTP API,不再有窗口宿主。
|
||||
/// </summary>
|
||||
public static WebApplication Start(string[] args, int port)
|
||||
=> Start(args, port, out _);
|
||||
|
||||
/// <summary>
|
||||
/// 构建后端,并通过 <paramref name="uiHost"/> 交出模型窗口宿主。
|
||||
///
|
||||
/// 调用方(启动器)必须在**主线程**调用 <see cref="AvaloniaHost.RunOnCurrentThread"/>:
|
||||
/// macOS 的 AppKit 要求 NSApplication 运行在主线程,否则打开模型窗口时整个进程会崩溃。
|
||||
/// </summary>
|
||||
public static WebApplication Start(string[] args, int port, out AvaloniaHost uiHost)
|
||||
{
|
||||
// 下载模块(GC-DOWNLOAD)通过宿主钩子注入,和 GC-BOOT 的做法一致。
|
||||
DownloadModuleHost.Factory = new DownloadModuleFactory();
|
||||
|
||||
var services = AppServices.Create();
|
||||
var host = new AvaloniaHost(services);
|
||||
uiHost = host;
|
||||
var userService = new UserService(services.Paths.HomeRoot);
|
||||
|
||||
var builder = WebApplication.CreateBuilder(new WebApplicationOptions { Args = args });
|
||||
builder.Logging.ClearProviders();
|
||||
@@ -200,12 +188,106 @@ 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 提取当前用户
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
await next();
|
||||
});
|
||||
|
||||
app.MapPost("/api/user/register", (RegisterRequest? req) => {
|
||||
if (req == null) return Results.BadRequest(new { error = "请求体为空" });
|
||||
if (string.IsNullOrWhiteSpace(req.Username)) return Results.BadRequest(new { error = "用户名不能为空" });
|
||||
if (string.IsNullOrWhiteSpace(req.Password)) return Results.BadRequest(new { error = "密码不能为空" });
|
||||
var ok = userService.Register(req.Username, req.Password, out var err);
|
||||
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.ToLower()] = 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.MapGet("/api/user/me", (HttpContext ctx) =>
|
||||
{
|
||||
var username = ctx.Items["user"] as string;
|
||||
if (string.IsNullOrEmpty(username) || !userService.TryGetUser(username, out var rec))
|
||||
return Results.Json(new { error = "未登录" }, statusCode: 401);
|
||||
return Results.Ok(new {
|
||||
username = rec.Username,
|
||||
points = rec.Points,
|
||||
consecutive_days = rec.ConsecutiveDays,
|
||||
last_sign_in = rec.LastSignIn?.ToString("yyyy-MM-dd") ?? "",
|
||||
theme_color = rec.ThemeColor ?? ""
|
||||
});
|
||||
});
|
||||
|
||||
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);
|
||||
if (!ok)
|
||||
{
|
||||
if (err == "今日已签到")
|
||||
return Results.Ok(new { message = err, points = rec.Points, consecutive_days = rec.ConsecutiveDays });
|
||||
return Results.BadRequest(new { error = err });
|
||||
}
|
||||
return Results.Ok(new {
|
||||
points = rec.Points,
|
||||
consecutive_days = rec.ConsecutiveDays,
|
||||
reward = userService.GetSignInReward(rec.ConsecutiveDays),
|
||||
last_sign_in = rec.LastSignIn?.ToString("yyyy-MM-dd") ?? ""
|
||||
});
|
||||
});
|
||||
|
||||
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, req.Cost, out var err);
|
||||
return ok ? Results.Ok(new { message = "主题已更新", points = rec.Points, theme_color = rec.ThemeColor }) : Results.BadRequest(new { error = err });
|
||||
});
|
||||
|
||||
app.MapGet("/api/health", () => Results.Ok(new HealthDto(
|
||||
true,
|
||||
LauncherRuntimeInfo.CurrentLauncherVersion,
|
||||
LauncherRuntimeInfo.CurrentRid,
|
||||
host.IsAvailable,
|
||||
host.LastError,
|
||||
// 界面在客户端内渲染,后端不存在「窗口宿主不可用」的状态
|
||||
true,
|
||||
(string?)null,
|
||||
GcUiContract.DeriveSessionProof(sessionToken))));
|
||||
|
||||
// ---- 已安装模型 -----------------------------------------------------------
|
||||
@@ -225,24 +307,15 @@ public static class BackendServer
|
||||
return Results.File(package.PreviewPath, GuessImageContentType(package.PreviewPath));
|
||||
});
|
||||
|
||||
app.MapPost("/api/models/{id}/launch", async (string id) =>
|
||||
// 模型改为客户端内渲染(Flutter):这里只确认模型存在并把 id 交回去,
|
||||
// 不再拉起 Avalonia 窗口。保留接口是为了老客户端不至于 404。
|
||||
app.MapPost("/api/models/{id}/launch", (string id) =>
|
||||
{
|
||||
if (!IsSafeId(id)) return Results.BadRequest(new LaunchResultDto(false, "模型标识无效"));
|
||||
var package = services.Models.Find(id);
|
||||
if (package == null) return Results.NotFound(new LaunchResultDto(false, $"没有找到模型 {id}"));
|
||||
|
||||
try
|
||||
{
|
||||
services.Memory.Refresh();
|
||||
var message = await host.LaunchAsync(package);
|
||||
return Results.Ok(new LaunchResultDto(true, message));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// 细节只写日志,不回显给调用方,避免泄漏本机路径等内部信息。
|
||||
Console.Error.WriteLine($"[launch] 启动模型 {id} 失败: {ex}");
|
||||
return Results.Json(new LaunchResultDto(false, "模型启动失败,请查看后端日志"), statusCode: 503);
|
||||
}
|
||||
return Results.Ok(new LaunchResultDto(true, $"在应用内打开 {package.Manifest.Name}"));
|
||||
});
|
||||
|
||||
app.MapDelete("/api/models/{id}", (string id) =>
|
||||
@@ -435,6 +508,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 +609,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 +621,7 @@ public static class BackendServer
|
||||
|
||||
|
||||
|
||||
static void WriteEndpointFile(AppServices services, int port)
|
||||
static void WriteEndpointFile(AppServices services, int port, string? token)
|
||||
{
|
||||
try
|
||||
{
|
||||
@@ -521,10 +633,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,261 @@
|
||||
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/ 目录。
|
||||
/// </summary>
|
||||
public sealed class UserService
|
||||
{
|
||||
private readonly string _userDir;
|
||||
public readonly ConcurrentDictionary<string, UserRecord> _users = new();
|
||||
|
||||
public UserService(string homeRoot)
|
||||
{
|
||||
_userDir = Path.Combine(homeRoot, "user");
|
||||
Directory.CreateDirectory(_userDir);
|
||||
LoadAll();
|
||||
}
|
||||
|
||||
private void LoadAll()
|
||||
{
|
||||
foreach (var file in Directory.GetFiles(_userDir, "*.yaml"))
|
||||
{
|
||||
try
|
||||
{
|
||||
var username = Path.GetFileNameWithoutExtension(file);
|
||||
var content = File.ReadAllText(file);
|
||||
var rec = DeserializeUser(username, content);
|
||||
if (rec != null) _users[username] = rec;
|
||||
}
|
||||
catch { /* 忽略损坏文件 */ }
|
||||
}
|
||||
}
|
||||
|
||||
private UserRecord? DeserializeUser(string username, string yaml)
|
||||
{
|
||||
var lines = yaml.Split('\n', StringSplitOptions.RemoveEmptyEntries);
|
||||
string? pwHash = null, pwSalt = null;
|
||||
int points = 0;
|
||||
DateTime? lastSignIn = null;
|
||||
int consecutiveDays = 0;
|
||||
string? themeColor = 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 "pw_hash": pwHash = val; break;
|
||||
case "pw_salt": pwSalt = val; break;
|
||||
case "points": points = int.TryParse(val, out var p) ? p : 0; break;
|
||||
case "last_sign_in":
|
||||
if (DateTime.TryParse(val, out var ls)) lastSignIn = ls;
|
||||
break;
|
||||
case "consecutive_days": consecutiveDays = int.TryParse(val, out var d) ? d : 0; break;
|
||||
case "theme_color": themeColor = val; break;
|
||||
}
|
||||
}
|
||||
|
||||
if (pwHash == null || pwSalt == null) return null;
|
||||
return new UserRecord(username, pwHash, pwSalt, points, lastSignIn, consecutiveDays, themeColor);
|
||||
}
|
||||
|
||||
public bool Register(string username, string password, out string error)
|
||||
{
|
||||
error = "";
|
||||
if (string.IsNullOrWhiteSpace(username) || username.Length > 20)
|
||||
{
|
||||
error = "用户名无效";
|
||||
return false;
|
||||
}
|
||||
if (string.IsNullOrWhiteSpace(password) || password.Length < 6)
|
||||
{
|
||||
error = "密码至少6位";
|
||||
return false;
|
||||
}
|
||||
if (_users.ContainsKey(username.ToLower()))
|
||||
{
|
||||
error = "用户名已存在";
|
||||
return false;
|
||||
}
|
||||
|
||||
var salt = GenerateSalt();
|
||||
var hash = HashPassword(password, salt);
|
||||
var rec = new UserRecord(username, hash, salt, 0, null, 0, null);
|
||||
_users[username.ToLower()] = 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.ToLower(), out var rec))
|
||||
{
|
||||
error = "用户名或密码错误";
|
||||
return false;
|
||||
}
|
||||
var hash = HashPassword(password, rec.PwSalt);
|
||||
if (hash != rec.PwHash)
|
||||
{
|
||||
error = "用户名或密码错误";
|
||||
return false;
|
||||
}
|
||||
record = rec;
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool UpdatePoints(string username, int deltaPoints, out string error)
|
||||
{
|
||||
error = "";
|
||||
if (!_users.TryGetValue(username, out var rec))
|
||||
{
|
||||
error = "用户不存在";
|
||||
return false;
|
||||
}
|
||||
rec.Points = Math.Max(0, rec.Points + deltaPoints);
|
||||
_users[username] = rec;
|
||||
SaveUser(rec);
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool UpdateSignIn(string username, out string error)
|
||||
{
|
||||
error = "";
|
||||
if (!_users.TryGetValue(username, out var rec))
|
||||
{
|
||||
error = "用户不存在";
|
||||
return false;
|
||||
}
|
||||
|
||||
var today = DateTime.UtcNow.Date;
|
||||
if (rec.LastSignIn.HasValue)
|
||||
{
|
||||
var last = rec.LastSignIn.Value.Date;
|
||||
var diff = (today - last).Days;
|
||||
if (diff == 0)
|
||||
{
|
||||
error = "今日已签到";
|
||||
return false;
|
||||
}
|
||||
if (diff == 1)
|
||||
{
|
||||
rec.ConsecutiveDays++;
|
||||
}
|
||||
else
|
||||
{
|
||||
rec.ConsecutiveDays = 1;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
rec.ConsecutiveDays = 1;
|
||||
}
|
||||
rec.LastSignIn = today;
|
||||
|
||||
var cycleDay = (rec.ConsecutiveDays - 1) % 30 + 1;
|
||||
int reward = GetSignInReward(cycleDay);
|
||||
rec.Points += reward;
|
||||
|
||||
_users[username] = rec;
|
||||
SaveUser(rec);
|
||||
return true;
|
||||
}
|
||||
|
||||
public int GetSignInReward(int day)
|
||||
{
|
||||
if (day <= 7) return 10;
|
||||
if (day <= 15) return 20;
|
||||
return 30;
|
||||
}
|
||||
|
||||
public UserRecord? GetFirstUser()
|
||||
{
|
||||
return _users.Values.FirstOrDefault();
|
||||
}
|
||||
|
||||
public bool TryGetUser(string username, out UserRecord? record)
|
||||
{
|
||||
return _users.TryGetValue(username.ToLower(), out record);
|
||||
}
|
||||
|
||||
public bool ChangeThemeColor(string username, string colorHex, int cost, out string error)
|
||||
{
|
||||
error = "";
|
||||
if (!_users.TryGetValue(username, out var rec))
|
||||
{
|
||||
error = "用户不存在";
|
||||
return false;
|
||||
}
|
||||
if (rec.Points < cost)
|
||||
{
|
||||
error = "积分不足";
|
||||
return false;
|
||||
}
|
||||
rec.Points -= cost;
|
||||
rec.ThemeColor = colorHex;
|
||||
_users[username] = rec;
|
||||
SaveUser(rec);
|
||||
return true;
|
||||
}
|
||||
|
||||
private void SaveUser(UserRecord rec)
|
||||
{
|
||||
try
|
||||
{
|
||||
var file = Path.Combine(_userDir, $"{rec.Username.ToLower()}.yaml");
|
||||
var yaml = $"username: {rec.Username}\npw_hash: {rec.PwHash}\npw_salt: {rec.PwSalt}\npoints: {rec.Points}\nlast_sign_in: {rec.LastSignIn?.ToString("yyyy-MM-dd") ?? ""}\nconsecutive_days: {rec.ConsecutiveDays}\ntheme_color: {rec.ThemeColor ?? ""}\n";
|
||||
File.WriteAllText(file, yaml);
|
||||
}
|
||||
catch { /* 忽略写入失败 */ }
|
||||
}
|
||||
|
||||
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 combined = Encoding.UTF8.GetBytes(password + ":" + salt);
|
||||
var hash = sha512.ComputeHash(combined);
|
||||
return Convert.ToBase64String(hash);
|
||||
}
|
||||
}
|
||||
|
||||
public class UserRecord
|
||||
{
|
||||
public string Username { get; init; } = "";
|
||||
public string PwHash { get; init; } = "";
|
||||
public string PwSalt { get; init; } = "";
|
||||
public int Points { get; set; }
|
||||
public DateTime? LastSignIn { get; set; }
|
||||
public int ConsecutiveDays { get; set; }
|
||||
public string? ThemeColor { get; set; }
|
||||
|
||||
public UserRecord(string username, string pwHash, string pwSalt, int points, DateTime? lastSignIn, int consecutiveDays, string? themeColor = null)
|
||||
{
|
||||
Username = username;
|
||||
PwHash = pwHash;
|
||||
PwSalt = pwSalt;
|
||||
Points = points;
|
||||
LastSignIn = lastSignIn;
|
||||
ConsecutiveDays = consecutiveDays;
|
||||
ThemeColor = themeColor;
|
||||
}
|
||||
}
|
||||
@@ -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,180 @@ 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)
|
||||
static String? _userToken;
|
||||
static String? _username;
|
||||
|
||||
static String? get userToken => _userToken;
|
||||
static String? get username => _username;
|
||||
|
||||
static Future<void> _loadUserToken() async {
|
||||
try {
|
||||
final dir = Directory('${Platform.environment['HOME'] ?? '.'}/.GC/user');
|
||||
if (!dir.existsSync()) return;
|
||||
final file = File('${dir.path}/user.yaml');
|
||||
if (!file.existsSync()) return;
|
||||
final lines = file.readAsLinesSync();
|
||||
for (var line in lines) {
|
||||
if (line.startsWith('username:')) _username = line.split(':').skip(1).join(':').trim();
|
||||
if (line.startsWith('session_token:')) _userToken = line.split(':').skip(1).join(':').trim();
|
||||
}
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
static Future<void> _saveUserToken(String username, String token) async {
|
||||
try {
|
||||
final dir = Directory('${Platform.environment['HOME'] ?? '.'}/.GC/user');
|
||||
dir.createSync(recursive: true);
|
||||
final file = File('${dir.path}/user.yaml');
|
||||
file.writeAsStringSync('username: $username\nsession_token: $token\n');
|
||||
_username = username;
|
||||
_userToken = token;
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
static Future<void> clearUserToken() async {
|
||||
_username = null;
|
||||
_userToken = null;
|
||||
try {
|
||||
final file = File('${Platform.environment['HOME'] ?? '.'}/.GC/user/user.yaml');
|
||||
if (file.existsSync()) file.deleteSync();
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
/// 带会话令牌的请求头;没有令牌时返回 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 {
|
||||
final uri = _uri(path, query);
|
||||
final auth = _authHeaders;
|
||||
late http.Response response;
|
||||
@@ -427,18 +575,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 +650,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 +702,56 @@ class GcApi {
|
||||
'X-GC-UI-Token': _sessionToken!,
|
||||
}).toString();
|
||||
}
|
||||
|
||||
// ==================== 用户系统 ====================
|
||||
|
||||
/// 初始化:加载本地保存的用户token
|
||||
Future<void> initUserSession() async {
|
||||
await _loadUserToken();
|
||||
}
|
||||
|
||||
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) {
|
||||
await clearUserToken();
|
||||
return null;
|
||||
}
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
Future<Map<String, dynamic>> register(String username, String password) async {
|
||||
final r = await _send('POST', '/api/user/register',
|
||||
body: {'username': username, 'password': password});
|
||||
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>;
|
||||
// 保存 session token
|
||||
if (result.containsKey('session_token')) {
|
||||
await _saveUserToken(username, result['session_token'] as String);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
Future<void> logout() async {
|
||||
await clearUserToken();
|
||||
}
|
||||
|
||||
Future<Map<String, dynamic>> signin() async {
|
||||
final r = await _send('POST', '/api/user/signin');
|
||||
return r as Map<String, dynamic>;
|
||||
}
|
||||
|
||||
Future<Map<String, dynamic>> changeTheme(String color, int cost) async {
|
||||
final r = await _send('POST', '/api/user/theme',
|
||||
body: {'color': color, 'cost': cost});
|
||||
return r as Map<String, dynamic>;
|
||||
}
|
||||
}
|
||||
@@ -87,7 +87,11 @@ class ShellController extends ChangeNotifier {
|
||||
_retryAttempt++;
|
||||
_retryTimer?.cancel();
|
||||
_retryTimer = Timer(Duration(seconds: seconds), () {
|
||||
if (settings == null) bootstrap();
|
||||
if (settings == null) {
|
||||
// 后端可能刚换端口(端口占用)或刚写好握手文件:重试前重新解析一次
|
||||
api.rediscover();
|
||||
bootstrap();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -100,6 +104,25 @@ class ShellController extends ChangeNotifier {
|
||||
void goTo(int value) {
|
||||
if (index == value) return;
|
||||
index = value;
|
||||
activeModelId = null; // 切页时收起模型视图
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
/// 当前在壳内打开的模型(null 表示在看普通页面)。
|
||||
///
|
||||
/// 模型全部由 Flutter 自绘,不再由后端开 Avalonia 窗口:
|
||||
/// 点「启动模型」只是把内容区换成模型视图,标题栏与侧栏保持可用。
|
||||
String? activeModelId;
|
||||
|
||||
void openModel(String id) {
|
||||
if (activeModelId == id) return;
|
||||
activeModelId = id;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void closeModel() {
|
||||
if (activeModelId == null) return;
|
||||
activeModelId = null;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
|
||||
@@ -17,6 +17,8 @@ class I18n {
|
||||
'nav.download': '下载',
|
||||
'nav.settings': '设置',
|
||||
'nav.about': '关于',
|
||||
'nav.treasure': '百宝箱',
|
||||
'nav.user': '用户',
|
||||
'home.title': '模型库',
|
||||
'home.subtitle': '选择模型,用可交互的三维演示讲清自转、公转与四季成因。',
|
||||
'home.launch': '启动模型',
|
||||
@@ -35,7 +37,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': '模型源',
|
||||
@@ -133,6 +139,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 +154,27 @@ class I18n {
|
||||
'about.thanksHint': '特别感谢以下朋友的支持',
|
||||
'about.thanksGit': 'Git 服务与部署支持',
|
||||
'about.thanksGeo': '地理学科内容指导',
|
||||
'user.points': '积分',
|
||||
'user.days': '连续签到',
|
||||
'user.signin': '签到',
|
||||
'user.login': '登录',
|
||||
'user.register': '注册',
|
||||
'user.pick': '二选一',
|
||||
'user.theme': '主题颜色',
|
||||
'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': '请先登录',
|
||||
},
|
||||
'en': <String, String>{
|
||||
'app.name': 'Morris GC',
|
||||
@@ -153,6 +184,8 @@ class I18n {
|
||||
'nav.download': 'Download',
|
||||
'nav.settings': 'Settings',
|
||||
'nav.about': 'About',
|
||||
'nav.treasure': 'Treasure',
|
||||
'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 +204,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',
|
||||
@@ -269,6 +306,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 +321,27 @@ 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.theme': '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',
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import 'base.dart';
|
||||
import 'contour_flutter.dart';
|
||||
import 'geography_flutter.dart';
|
||||
import 'revolution_flutter.dart';
|
||||
import 'rotation_flutter.dart';
|
||||
import 'scale_flutter.dart';
|
||||
|
||||
/// 后端模型 id → Flutter 实现。
|
||||
///
|
||||
/// 后端(`/api/models`)用的是模型包目录名(contour-map、earth-rotation…),
|
||||
/// Flutter 实现自己的 id 带 `-flutter` 后缀,这里做一次映射。
|
||||
/// Avalonia 版模型窗口已移除,所有模型统一在客户端内用 Flutter 渲染。
|
||||
final Map<String, GcModel Function()> _factories = <String, GcModel Function()>{
|
||||
'contour-map': () => ContourModelFlutter(),
|
||||
'earth-geography': () => GeographyModelFlutter(),
|
||||
'earth-rotation': () => RotationModelFlutter(),
|
||||
'earth-revolution': () => RevolutionModelFlutter(),
|
||||
'scale-calculator': () => ScaleCalculatorModelFlutter(),
|
||||
};
|
||||
|
||||
/// 按模型 id 取 Flutter 实现;没有对应实现时返回 null。
|
||||
GcModel? flutterModelFor(String id) {
|
||||
final factory = _factories[id] ?? _factories[id.replaceAll('-flutter', '')];
|
||||
return factory?.call();
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
/// 用户记录
|
||||
class UserRecord {
|
||||
const UserRecord({
|
||||
required this.username,
|
||||
required this.points,
|
||||
required this.consecutiveDays,
|
||||
this.lastSignIn,
|
||||
this.themeColor,
|
||||
});
|
||||
|
||||
final String username;
|
||||
final int points;
|
||||
final int consecutiveDays;
|
||||
final String? lastSignIn;
|
||||
final String? themeColor;
|
||||
|
||||
factory UserRecord.fromJson(Map<String, dynamic> json) {
|
||||
return UserRecord(
|
||||
username: json['username'] as String? ?? '',
|
||||
points: json['points'] as int? ?? 0,
|
||||
consecutiveDays: json['consecutive_days'] as int? ?? 0,
|
||||
lastSignIn: json['last_sign_in'] as String?,
|
||||
themeColor: json['theme_color'] as String?,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 签到奖励配置(30天周期)
|
||||
class SignInRewards {
|
||||
static const List<int> rewards = [
|
||||
10, 10, 10, 10, 10, 10, 10, // 第1-7天:每天+10
|
||||
20, 20, 20, 20, 20, 20, 20, // 第8-15天:每天+20
|
||||
30, 30, 30, 30, 30, 30, 30, // 第16-23天:每天+30
|
||||
30, 30, 30, 30, 30, 30, 30, // 第24-30天:每天+30
|
||||
];
|
||||
|
||||
static int getReward(int day) {
|
||||
if (day < 1) day = 1;
|
||||
if (day > 30) day = ((day - 1) % 30) + 1;
|
||||
return rewards[day - 1];
|
||||
}
|
||||
}
|
||||
|
||||
/// 主题颜色
|
||||
class ThemeColor {
|
||||
const ThemeColor({required this.name, required this.hex, required this.cost});
|
||||
|
||||
final String name;
|
||||
final String hex;
|
||||
final int cost;
|
||||
|
||||
static const List<ThemeColor> predefined = [
|
||||
ThemeColor(name: '蓝色', hex: '4A90D9', cost: 0),
|
||||
ThemeColor(name: '红色', hex: 'E74C3C', cost: 50),
|
||||
ThemeColor(name: '绿色', hex: '27AE60', cost: 50),
|
||||
ThemeColor(name: '紫色', hex: '9B59B6', cost: 50),
|
||||
ThemeColor(name: '橙色', hex: 'F39C12', cost: 50),
|
||||
ThemeColor(name: '青色', hex: '1ABC9C', cost: 50),
|
||||
ThemeColor(name: '粉色', hex: 'E91E63', cost: 50),
|
||||
ThemeColor(name: '深蓝', hex: '2C3E50', cost: 50),
|
||||
];
|
||||
}
|
||||
@@ -6,3 +6,5 @@ export 'pages/courseware.dart';
|
||||
export 'pages/download.dart';
|
||||
export 'pages/settings.dart';
|
||||
export 'pages/about.dart';
|
||||
export 'pages/treasure.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,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../i18n.dart';
|
||||
import '../models/base.dart';
|
||||
import '../models/lookup.dart';
|
||||
import '../theme.dart';
|
||||
|
||||
/// 模型视图:在壳内直接渲染 Flutter 模型。
|
||||
///
|
||||
/// 以前「启动模型」是让后端另开一个 Avalonia 窗口;现在模型全部是 Flutter 实现,
|
||||
/// 直接换掉内容区即可 —— 不会多出一个窗口,也不用跨进程传状态。
|
||||
class ModelViewPage extends StatelessWidget {
|
||||
const ModelViewPage({
|
||||
super.key,
|
||||
required this.modelId,
|
||||
required this.onClose,
|
||||
});
|
||||
|
||||
final String modelId;
|
||||
final VoidCallback onClose;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final model = flutterModelFor(modelId);
|
||||
|
||||
if (model == null) {
|
||||
return Center(
|
||||
child: GcCard(
|
||||
padding: const EdgeInsets.all(GcSpace.xxl),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
Text(
|
||||
T('model.missing'),
|
||||
style: TextStyle(
|
||||
fontSize: 15,
|
||||
height: 1.35,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: GcColors.ink,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: GcSpace.sm),
|
||||
GcHint(T('model.missingHint')),
|
||||
const SizedBox(height: GcSpace.lg),
|
||||
OutlinedButton(
|
||||
onPressed: onClose,
|
||||
child: Text(T('model.back')),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: <Widget>[
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(
|
||||
GcSpace.xxl,
|
||||
GcSpace.lg,
|
||||
GcSpace.xxl,
|
||||
GcSpace.sm,
|
||||
),
|
||||
child: Row(
|
||||
children: <Widget>[
|
||||
OutlinedButton.icon(
|
||||
onPressed: onClose,
|
||||
icon: const Icon(Icons.arrow_back_rounded, size: 16),
|
||||
label: Text(T('model.back')),
|
||||
),
|
||||
const SizedBox(width: GcSpace.lg),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: <Widget>[
|
||||
Text(
|
||||
model.name(),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyle(
|
||||
fontSize: 16,
|
||||
height: 1.3,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: GcColors.ink,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 2),
|
||||
Text(
|
||||
model.description(),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
height: 1.4,
|
||||
color: GcColors.faint,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Expanded(child: ClipRect(child: _body(model))),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _body(GcModel model) {
|
||||
// 模型视图自己管状态(动画、视角),换 id 时必须重建,不能复用 State
|
||||
return KeyedSubtree(
|
||||
key: ValueKey<String>(model.id),
|
||||
child: Builder(builder: (context) => model.buildView(context)),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../controller.dart';
|
||||
import '../theme.dart';
|
||||
import '../i18n.dart';
|
||||
|
||||
/// 百宝箱页:今日人品、随机运势等小玩意。
|
||||
class TreasurePage extends StatefulWidget {
|
||||
const TreasurePage({super.key, required this.controller});
|
||||
|
||||
final ShellController controller;
|
||||
|
||||
@override
|
||||
State<TreasurePage> createState() => _TreasurePageState();
|
||||
}
|
||||
|
||||
class _TreasurePageState extends State<TreasurePage> {
|
||||
String _fortune = '';
|
||||
String _luckyColor = '';
|
||||
String _luckyNumber = '';
|
||||
bool _loading = false;
|
||||
final Random _rand = Random();
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_refresh();
|
||||
}
|
||||
|
||||
void _refresh() {
|
||||
setState(() => _loading = true);
|
||||
// 模拟计算延迟
|
||||
Future.delayed(const Duration(milliseconds: 400), () {
|
||||
if (!mounted) return;
|
||||
final fortunes = <String>[
|
||||
'今日宜:尝试新事物,突破舒适区。',
|
||||
'运气不错,适合做重要的决定。',
|
||||
'财运旺盛,可能会有意外收获。',
|
||||
'人际和谐,适合合作与沟通。',
|
||||
'专注当下,好运自然来。',
|
||||
'保持乐观,今天会有好消息。',
|
||||
'灵感涌现,适合创作和思考。',
|
||||
'脚踏实地,一步一个脚印。',
|
||||
'贵人运旺,多与他人交流。',
|
||||
'健康第一,注意休息和锻炼。',
|
||||
];
|
||||
final colors = <String>[
|
||||
'红色', '蓝色', '绿色', '金色', '紫色', '橙色', '粉色', '青色',
|
||||
];
|
||||
setState(() {
|
||||
_fortune = fortunes[_rand.nextInt(fortunes.length)];
|
||||
_luckyColor = colors[_rand.nextInt(colors.length)];
|
||||
_luckyNumber = '${(_rand.nextInt(99)) + 1}';
|
||||
_loading = false;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
backgroundColor: GcColors.appBg,
|
||||
body: _loading
|
||||
? const Center(child: CircularProgressIndicator())
|
||||
: Center(
|
||||
child: ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxWidth: 480),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: <Widget>[
|
||||
// 今日人品卡片
|
||||
GcCard(
|
||||
padding: const EdgeInsets.all(GcSpace.xxl),
|
||||
child: Column(
|
||||
children: <Widget>[
|
||||
Icon(
|
||||
Icons.star_rounded,
|
||||
size: 48,
|
||||
color: GcColors.accent,
|
||||
),
|
||||
const SizedBox(height: GcSpace.lg),
|
||||
Text(
|
||||
T('treasure.fortuneTitle'),
|
||||
style: const TextStyle(
|
||||
fontSize: 20,
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: GcSpace.md),
|
||||
Text(
|
||||
_fortune,
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(
|
||||
fontSize: 15,
|
||||
height: 1.5,
|
||||
color: GcColors.muted,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: GcSpace.lg),
|
||||
// 幸运信息
|
||||
Wrap(
|
||||
spacing: GcSpace.md,
|
||||
runSpacing: GcSpace.md,
|
||||
children: <Widget>[
|
||||
_buildStatCard(
|
||||
icon: Icons.check_circle_outline_rounded,
|
||||
label: T('treasure.luckyColor'),
|
||||
value: _luckyColor,
|
||||
),
|
||||
_buildStatCard(
|
||||
icon: Icons.numbers_rounded,
|
||||
label: T('treasure.luckyNumber'),
|
||||
value: _luckyNumber,
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: GcSpace.xl),
|
||||
// 刷新按钮
|
||||
FilledButton.icon(
|
||||
onPressed: _refresh,
|
||||
icon: const Icon(Icons.refresh_rounded, size: 18),
|
||||
label: Text(T('treasure.refresh')),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildStatCard({
|
||||
required IconData icon,
|
||||
required String label,
|
||||
required String value,
|
||||
}) {
|
||||
return GcCard(
|
||||
padding: const EdgeInsets.all(GcSpace.lg),
|
||||
child: Column(
|
||||
children: <Widget>[
|
||||
Icon(icon, size: 28, color: GcColors.accent),
|
||||
const SizedBox(height: GcSpace.sm),
|
||||
Text(
|
||||
label,
|
||||
style: TextStyle(fontSize: 12, color: GcColors.muted),
|
||||
),
|
||||
const SizedBox(height: GcSpace.xs),
|
||||
Text(
|
||||
value,
|
||||
style: const TextStyle(
|
||||
fontSize: 20,
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,404 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'dart:math';
|
||||
import '../controller.dart';
|
||||
import '../theme.dart';
|
||||
import '../i18n.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();
|
||||
bool _isLogin = true;
|
||||
|
||||
// 二选一
|
||||
final _option1Ctrl = TextEditingController();
|
||||
final _option2Ctrl = TextEditingController();
|
||||
String? _randomResult;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_loadUser();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_usernameCtrl.dispose();
|
||||
_passwordCtrl.dispose();
|
||||
_option1Ctrl.dispose();
|
||||
_option2Ctrl.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _loadUser() async {
|
||||
setState(() {
|
||||
_loading = true;
|
||||
_error = null;
|
||||
});
|
||||
try {
|
||||
await widget.controller.api.initUserSession();
|
||||
final resp = await widget.controller.api.me();
|
||||
if (!mounted) return;
|
||||
if (resp != null) {
|
||||
setState(() {
|
||||
_user = UserRecord.fromJson(resp);
|
||||
_loading = false;
|
||||
});
|
||||
} else {
|
||||
setState(() {
|
||||
_loading = false;
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_loading = false;
|
||||
_error = e.toString();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _loginOrRegister() async {
|
||||
final username = _usernameCtrl.text.trim();
|
||||
final password = _passwordCtrl.text;
|
||||
if (username.isEmpty || password.isEmpty) {
|
||||
_showError(T('user.fillAll'));
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
Map<String, dynamic> resp;
|
||||
if (_isLogin) {
|
||||
resp = await widget.controller.api.login(username, password);
|
||||
} else {
|
||||
resp = await widget.controller.api.register(username, password);
|
||||
if (!mounted) return;
|
||||
// 注册成功后自动登录
|
||||
resp = await widget.controller.api.login(username, password);
|
||||
}
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_user = UserRecord.fromJson(resp);
|
||||
_usernameCtrl.clear();
|
||||
_passwordCtrl.clear();
|
||||
});
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text(_isLogin ? T('user.loginSuccess') : T('user.registerSuccess'))),
|
||||
);
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
_showError(e.toString());
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _signin() async {
|
||||
try {
|
||||
final resp = await widget.controller.api.signin();
|
||||
if (!mounted) return;
|
||||
if (resp.containsKey('message') && resp['message'] == '今日已签到') {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text(T('user.alreadySigned'))),
|
||||
);
|
||||
return;
|
||||
}
|
||||
setState(() {
|
||||
_user = UserRecord.fromJson({
|
||||
...resp,
|
||||
'username': _user?.username ?? '',
|
||||
});
|
||||
});
|
||||
final reward = resp['reward'] as int? ?? 0;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('${T('user.signinSuccess')} +$reward ${T('user.points')}')),
|
||||
);
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
_showError(e.toString());
|
||||
}
|
||||
}
|
||||
|
||||
void _pickRandom() {
|
||||
final opt1 = _option1Ctrl.text.trim();
|
||||
final opt2 = _option2Ctrl.text.trim();
|
||||
if (opt1.isEmpty || opt2.isEmpty) {
|
||||
_showError(T('user.fillOptions'));
|
||||
return;
|
||||
}
|
||||
final result = Random().nextBool() ? opt1 : opt2;
|
||||
setState(() => _randomResult = result);
|
||||
}
|
||||
|
||||
Future<void> _changeTheme(String hex, int cost) async {
|
||||
if (_user == null) {
|
||||
_showError(T('user.loginFirst'));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
final resp = await widget.controller.api.changeTheme(hex, cost);
|
||||
if (!mounted) return;
|
||||
if (resp.containsKey('message')) {
|
||||
setState(() {
|
||||
_user = UserRecord(
|
||||
username: _user!.username,
|
||||
points: resp['points'] as int? ?? _user!.points,
|
||||
consecutiveDays: _user!.consecutiveDays,
|
||||
lastSignIn: _user!.lastSignIn,
|
||||
themeColor: '0x${resp['theme_color'] ?? hex}',
|
||||
);
|
||||
});
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('主题已更新')),
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
_showError(e.toString());
|
||||
}
|
||||
}
|
||||
|
||||
void _showError(String msg) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text(msg)),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
backgroundColor: GcColors.appBg,
|
||||
body: _loading
|
||||
? const Center(child: CircularProgressIndicator())
|
||||
: SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(GcSpace.xxl),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: <Widget>[
|
||||
// 用户信息卡片
|
||||
if (_user != null) ...[
|
||||
GcCard(
|
||||
padding: const EdgeInsets.all(GcSpace.lg),
|
||||
child: Row(
|
||||
children: <Widget>[
|
||||
Icon(Icons.person_rounded, size: 40, color: GcColors.accent),
|
||||
const SizedBox(width: GcSpace.md),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
Text(
|
||||
_user!.username,
|
||||
style: const TextStyle(
|
||||
fontSize: 18,
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
'${T('user.points')}: ${_user!.points}',
|
||||
style: TextStyle(color: GcColors.muted),
|
||||
),
|
||||
Text(
|
||||
'${T('user.days')}: ${_user!.consecutiveDays}',
|
||||
style: TextStyle(color: GcColors.muted),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: _signin,
|
||||
child: Text(T('user.signin')),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: GcSpace.lg),
|
||||
],
|
||||
|
||||
// 登录/注册表单
|
||||
GcCard(
|
||||
padding: const EdgeInsets.all(GcSpace.lg),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
Text(
|
||||
_isLogin ? T('user.login') : T('user.register'),
|
||||
style: const TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: GcSpace.md),
|
||||
TextField(
|
||||
controller: _usernameCtrl,
|
||||
decoration: InputDecoration(
|
||||
labelText: T('user.username'),
|
||||
border: const OutlineInputBorder(),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: GcSpace.md),
|
||||
TextField(
|
||||
controller: _passwordCtrl,
|
||||
decoration: InputDecoration(
|
||||
labelText: T('user.password'),
|
||||
border: const OutlineInputBorder(),
|
||||
),
|
||||
obscureText: true,
|
||||
),
|
||||
const SizedBox(height: GcSpace.md),
|
||||
FilledButton(
|
||||
onPressed: _loginOrRegister,
|
||||
child: Text(_isLogin ? T('user.login') : T('user.register')),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () => setState(() => _isLogin = !_isLogin),
|
||||
child: Text(_isLogin ? T('user.switchToRegister') : T('user.switchToLogin')),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: GcSpace.lg),
|
||||
|
||||
// 二选一
|
||||
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: GcSpace.md),
|
||||
TextField(
|
||||
controller: _option1Ctrl,
|
||||
decoration: InputDecoration(
|
||||
labelText: T('user.option1'),
|
||||
border: const OutlineInputBorder(),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: GcSpace.md),
|
||||
TextField(
|
||||
controller: _option2Ctrl,
|
||||
decoration: InputDecoration(
|
||||
labelText: T('user.option2'),
|
||||
border: const OutlineInputBorder(),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: GcSpace.md),
|
||||
FilledButton(
|
||||
onPressed: _pickRandom,
|
||||
child: Text(T('user.pickRandom')),
|
||||
),
|
||||
if (_randomResult != null) ...[
|
||||
const SizedBox(height: GcSpace.md),
|
||||
GcCard(
|
||||
child: Text(
|
||||
_randomResult!,
|
||||
textAlign: TextAlign.center,
|
||||
style: const TextStyle(fontSize: 18, fontWeight: FontWeight.w600),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: GcSpace.lg),
|
||||
|
||||
// 主题颜色
|
||||
GcCard(
|
||||
padding: const EdgeInsets.all(GcSpace.lg),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
Text(
|
||||
T('user.theme'),
|
||||
style: const TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: GcSpace.md),
|
||||
Wrap(
|
||||
spacing: GcSpace.md,
|
||||
runSpacing: GcSpace.md,
|
||||
children: ThemeColor.predefined.map((c) {
|
||||
final canAfford = _user == null || _user!.points >= c.cost;
|
||||
final isCurrent = _user?.themeColor == '0x$c.hex';
|
||||
return InkWell(
|
||||
onTap: canAfford ? () => _changeTheme(c.hex, c.cost) : null,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
child: Container(
|
||||
width: 60,
|
||||
height: 60,
|
||||
decoration: BoxDecoration(
|
||||
color: Color(int.parse('0xFF${c.hex}')),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
border: Border.all(
|
||||
color: isCurrent ? GcColors.accent : GcColors.line,
|
||||
width: isCurrent ? 2 : 1,
|
||||
),
|
||||
),
|
||||
child: Stack(
|
||||
children: <Widget>[
|
||||
if (c.cost > 0 && !_canAfford(c.cost))
|
||||
Container(
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.black.withOpacity(0.5),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Center(
|
||||
child: Text(
|
||||
'${c.cost}',
|
||||
style: const TextStyle(color: Colors.white, fontSize: 12),
|
||||
),
|
||||
),
|
||||
),
|
||||
if (isCurrent)
|
||||
const Positioned(
|
||||
bottom: 2,
|
||||
right: 2,
|
||||
child: Icon(Icons.check_rounded, size: 16, color: Colors.white),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}).toList(),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (_error != null) ...[
|
||||
const SizedBox(height: GcSpace.md),
|
||||
Text(_error!, style: const TextStyle(color: Colors.red)),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
bool _canAfford(int cost) {
|
||||
if (cost <= 0) return true;
|
||||
if (_user == null) return false;
|
||||
return _user!.points >= cost;
|
||||
}
|
||||
}
|
||||
@@ -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,8 @@ 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.auto_awesome_rounded, 'nav.treasure'),
|
||||
_NavItem(Icons.person_rounded, 'nav.user'),
|
||||
];
|
||||
|
||||
/// 桌面端滚动行为:去掉移动端的拉伸回弹和边缘光晕,滚轮更跟手。
|
||||
@@ -69,16 +72,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 +147,10 @@ class _ShellPageState extends State<ShellPage> {
|
||||
return SettingsPageView(controller: controller);
|
||||
case 4:
|
||||
return AboutPageView(controller: controller);
|
||||
case 5:
|
||||
return TreasurePage(controller: controller);
|
||||
case 6:
|
||||
return UserPage(controller: controller);
|
||||
default:
|
||||
return HomePageView(controller: controller);
|
||||
}
|
||||
@@ -445,7 +460,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()
|
||||
|
||||
@@ -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,25 +5,20 @@
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<RootNamespace>GC</RootNamespace>
|
||||
<AssemblyName>GC.Core</AssemblyName>
|
||||
<AvaloniaUseCompiledBindingsByDefault>false</AvaloniaUseCompiledBindingsByDefault>
|
||||
<InvariantGlobalization>false</InvariantGlobalization>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<AvaloniaResource Include="Assets\**" />
|
||||
<Compile Include="..\..\GC-DRAW\PlayerWindow.cs" />
|
||||
<!-- 界面与模型渲染都已迁到 Flutter,这里只剩纯服务代码:
|
||||
不再引用 Avalonia / MVVM / GC.ModelSdk -->
|
||||
<Compile Remove="test\**\*.cs" />
|
||||
<!-- 多语言表原先通过 Avalonia 的 avares:// 读取,改为嵌入资源 -->
|
||||
<EmbeddedResource Include="Assets\i18n\*.json"
|
||||
LogicalName="GC.Core.Assets.i18n.%(Filename)%(Extension)" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
|
||||
<PackageReference Include="Avalonia.Desktop" Version="$(AvaloniaVersion)" />
|
||||
<PackageReference Include="Avalonia.Themes.Fluent" Version="$(AvaloniaVersion)" />
|
||||
<PackageReference Include="CommunityToolkit.Mvvm" Version="$(MvvmVersion)" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\model\_sdk\GC.ModelSdk\GC.ModelSdk.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -13,8 +13,6 @@ public sealed class AppServices
|
||||
public IDownloadCenter Downloads { get; }
|
||||
public MemoryBudget Memory { get; }
|
||||
public IModelSourceClient Sources { get; }
|
||||
/// <summary>模型加载器:只负责把模型程序集跑起来,不渲染。</summary>
|
||||
public ModelHost ModelHost { get; }
|
||||
/// <summary>启动时检查模型 / 启动器更新。</summary>
|
||||
public IUpdateService Updates { get; }
|
||||
/// <summary>双源测速选择器(Xhmcl / GitCode 取最快)。</summary>
|
||||
@@ -34,7 +32,6 @@ public sealed class AppServices
|
||||
Sources = DownloadModule.Sources;
|
||||
Downloads = DownloadModule.Downloads;
|
||||
Memory = new MemoryBudget();
|
||||
ModelHost = new ModelHost(paths, Settings, Memory);
|
||||
Selector = DownloadModule.Selector;
|
||||
Updates = DownloadModule.Updates;
|
||||
LauncherUpdates = DownloadModule.LauncherUpdates;
|
||||
|
||||
@@ -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) };
|
||||
}
|
||||
@@ -1,300 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using System.Runtime.Loader;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia.Controls;
|
||||
using GC.Models;
|
||||
using GC.ModelSdk;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 模型宿主:按清单加载模型自己的程序集,拿到模型自带的界面。
|
||||
/// 启动器对“场景 / 行星 / 节气”一无所知,只认契约。
|
||||
/// </summary>
|
||||
public sealed class ModelHost
|
||||
{
|
||||
public const int SupportedApiVersion = 1;
|
||||
|
||||
private readonly AppPaths _paths;
|
||||
private readonly SettingsService _settings;
|
||||
private readonly MemoryBudget _memory;
|
||||
|
||||
public ModelHost(AppPaths paths, SettingsService settings, MemoryBudget memory)
|
||||
{
|
||||
_paths = paths;
|
||||
_settings = settings;
|
||||
_memory = memory;
|
||||
}
|
||||
|
||||
/// <summary>同步加载(全部在 UI 线程,用于自检 / 命令行)。</summary>
|
||||
public LoadedModel Load(ModelPackage package, Action requestClose, Action<double, string?>? progress = null)
|
||||
{
|
||||
var session = CreateSession(package, requestClose, progress);
|
||||
try
|
||||
{
|
||||
session.Runtime.Prepare(session.Context);
|
||||
var view = session.Runtime.CreateView(session.Context)
|
||||
?? throw new InvalidOperationException("模型没有返回界面");
|
||||
return session.Complete(view);
|
||||
}
|
||||
catch
|
||||
{
|
||||
session.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 异步加载:数据准备放在后台线程(<see cref="IModelRuntime.Prepare"/>),
|
||||
/// 界面构建回到 UI 线程,进度通过 <paramref name="progress"/> 实时汇报。
|
||||
/// </summary>
|
||||
public async Task<LoadedModel> LoadAsync(ModelPackage package, Action requestClose,
|
||||
Action<double, string?>? progress = null)
|
||||
{
|
||||
var session = CreateSession(package, requestClose, progress);
|
||||
try
|
||||
{
|
||||
await Task.Run(() => session.Runtime.Prepare(session.Context)).ConfigureAwait(true);
|
||||
var view = session.Runtime.CreateView(session.Context)
|
||||
?? throw new InvalidOperationException("模型没有返回界面");
|
||||
return session.Complete(view);
|
||||
}
|
||||
catch
|
||||
{
|
||||
session.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private Session CreateSession(ModelPackage package, Action requestClose, Action<double, string?>? progress)
|
||||
{
|
||||
// ---- 契约协商 -------------------------------------------------------
|
||||
// 先做廉价检查:不满足就直接拒绝,避免加载了才发现不兼容。
|
||||
var declaredApi = package.Manifest.ApiVersion;
|
||||
if (declaredApi < 1)
|
||||
throw new InvalidOperationException($"模型清单的 apiVersion 非法: {declaredApi}");
|
||||
|
||||
if (declaredApi > SupportedApiVersion)
|
||||
throw new InvalidOperationException(
|
||||
$"该模型需要更新的启动器(模型契约 v{declaredApi},当前支持 v{SupportedApiVersion})。" +
|
||||
"请先更新启动器,或让模型作者发布兼容版本。");
|
||||
|
||||
var minApp = package.Manifest.MinAppVersion;
|
||||
if (!string.IsNullOrWhiteSpace(minApp) &&
|
||||
CompareVersions(LauncherRuntimeInfo.CurrentLauncherVersion, minApp!) < 0)
|
||||
throw new InvalidOperationException(
|
||||
$"该模型要求启动器 ≥ v{minApp},当前为 v{LauncherRuntimeInfo.CurrentLauncherVersion}");
|
||||
|
||||
// ---- 完整性:dll 会被直接执行,加载前必须确认它没被改过 ----------------
|
||||
var integrity = ModelIntegrity.VerifyForLoad(package.Directory, package.Id);
|
||||
if (!integrity.Ok)
|
||||
{
|
||||
var message = $"模型完整性校验失败({package.Id}):{integrity.Message}。" +
|
||||
"请删除该模型目录让启动器重新下载。";
|
||||
if (Environment.GetEnvironmentVariable("GC_ALLOW_TAMPERED_MODELS") == "1")
|
||||
Console.Error.WriteLine("[warn] " + message + "(已按 GC_ALLOW_TAMPERED_MODELS 放行)");
|
||||
else
|
||||
throw new InvalidOperationException(message);
|
||||
}
|
||||
else if (!integrity.Present && Environment.GetEnvironmentVariable("GC_STRICT_MODELS") == "1")
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"模型缺少完整性记录({package.Id}),严格模式下拒绝加载");
|
||||
}
|
||||
|
||||
var assemblyPath = package.AssemblyPath;
|
||||
if (!File.Exists(assemblyPath))
|
||||
throw new FileNotFoundException($"模型缺少功能程序集:{assemblyPath}", assemblyPath);
|
||||
|
||||
var directory = Path.GetDirectoryName(assemblyPath)!;
|
||||
var context = new ModelLoadContext(directory);
|
||||
try
|
||||
{
|
||||
var assembly = context.LoadFromAssemblyPath(assemblyPath);
|
||||
var type = ResolveFactoryType(assembly, package.Manifest.Type);
|
||||
if (type == null)
|
||||
throw new InvalidOperationException("模型程序集里没有找到 IModelFactory 实现");
|
||||
|
||||
if (Activator.CreateInstance(type) is not IModelFactory factory)
|
||||
throw new InvalidOperationException($"无法创建模型入口:{type.FullName}");
|
||||
|
||||
if (factory.ApiVersion != SupportedApiVersion)
|
||||
throw new InvalidOperationException(
|
||||
$"模型程序集的契约版本为 v{factory.ApiVersion},启动器支持 v{SupportedApiVersion};" +
|
||||
"请更新到匹配的版本");
|
||||
|
||||
var runtime = factory.Create();
|
||||
var modelContext = new ModelContext(package, L.I.Language, _memory.BudgetMb, requestClose, progress);
|
||||
return new Session(context, runtime, modelContext);
|
||||
}
|
||||
catch
|
||||
{
|
||||
context.Unload();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private static Type? ResolveFactoryType(Assembly assembly, string? typeName)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(typeName))
|
||||
{
|
||||
var exact = assembly.GetType(typeName!, throwOnError: false);
|
||||
if (exact != null) return exact;
|
||||
}
|
||||
|
||||
foreach (var type in assembly.GetTypes())
|
||||
{
|
||||
if (type.IsAbstract || type.IsInterface) continue;
|
||||
if (typeof(IModelFactory).IsAssignableFrom(type)) return type;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>比较 1.0.10 与 1.0.9 这类版本号(按数字段比较,不按字符串)。</summary>
|
||||
private static int CompareVersions(string left, string right)
|
||||
{
|
||||
static int[] Parts(string value)
|
||||
{
|
||||
var text = value.Trim().TrimStart('v', 'V');
|
||||
var pieces = text.Split('.');
|
||||
var numbers = new int[Math.Max(4, pieces.Length)];
|
||||
for (var i = 0; i < pieces.Length; i++)
|
||||
{
|
||||
var digits = new string(Array.FindAll(pieces[i].ToCharArray(), char.IsDigit));
|
||||
if (digits.Length > 6) digits = digits[..6];
|
||||
numbers[i] = int.TryParse(digits, out var n) ? n : 0;
|
||||
}
|
||||
return numbers;
|
||||
}
|
||||
|
||||
var a = Parts(left);
|
||||
var b = Parts(right);
|
||||
for (var i = 0; i < Math.Max(a.Length, b.Length); i++)
|
||||
{
|
||||
var x = i < a.Length ? a[i] : 0;
|
||||
var y = i < b.Length ? b[i] : 0;
|
||||
if (x != y) return x < y ? -1 : 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
private sealed class Session : IDisposable
|
||||
{
|
||||
private readonly ModelLoadContext _context;
|
||||
|
||||
public Session(ModelLoadContext context, IModelRuntime runtime, ModelContext modelContext)
|
||||
{
|
||||
_context = context;
|
||||
Runtime = runtime;
|
||||
Context = modelContext;
|
||||
}
|
||||
|
||||
public IModelRuntime Runtime { get; }
|
||||
public ModelContext Context { get; }
|
||||
|
||||
public LoadedModel Complete(Control view) => new(_context, Runtime, view);
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
try { Runtime.Dispose(); } catch (Exception ex) { Console.Error.WriteLine($"释放模型失败: {ex.Message}"); }
|
||||
try { _context.Unload(); } catch (Exception ex) { Console.Error.WriteLine($"卸载模型程序集失败: {ex.Message}"); }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>一次性模型实例:窗口关闭后释放视图、卸载程序集。</summary>
|
||||
public sealed class LoadedModel : IDisposable
|
||||
{
|
||||
private readonly ModelLoadContext _context;
|
||||
private readonly IModelRuntime _runtime;
|
||||
private bool _disposed;
|
||||
|
||||
public LoadedModel(ModelLoadContext context, IModelRuntime runtime, Control view)
|
||||
{
|
||||
_context = context;
|
||||
_runtime = runtime;
|
||||
View = view;
|
||||
}
|
||||
|
||||
public Control View { get; }
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
// 顺序:先释放视图(停计时器/Dispose 位图),再释放运行时,最后卸载程序集。
|
||||
// 否则视图里的事件订阅会继续持有 ALC 内的类型,collectible 上下文无法回收。
|
||||
try { (View as IDisposable)?.Dispose(); }
|
||||
catch (Exception ex) { Console.Error.WriteLine($"释放模型视图失败: {ex.Message}"); }
|
||||
try { _runtime.Dispose(); } catch (Exception ex) { Console.Error.WriteLine($"释放模型失败: {ex.Message}"); }
|
||||
try { _context.Unload(); } catch (Exception ex) { Console.Error.WriteLine($"卸载模型程序集失败: {ex.Message}"); }
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>模型程序集加载上下文:契约与 Avalonia 一律回到默认上下文,保证类型一致。</summary>
|
||||
public sealed class ModelLoadContext : AssemblyLoadContext
|
||||
{
|
||||
private static readonly HashSet<string> Shared = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
"GC.ModelSdk",
|
||||
"Avalonia",
|
||||
"Avalonia.Base",
|
||||
"Avalonia.Controls",
|
||||
"Avalonia.Desktop",
|
||||
"Avalonia.Skia",
|
||||
"Avalonia.Themes.Fluent",
|
||||
"SkiaSharp",
|
||||
"HarfBuzzSharp"
|
||||
};
|
||||
|
||||
private readonly string _directory;
|
||||
|
||||
public ModelLoadContext(string directory) : base("model:" + Path.GetFileName(directory), isCollectible: true)
|
||||
=> _directory = directory;
|
||||
|
||||
protected override Assembly? Load(AssemblyName assemblyName)
|
||||
{
|
||||
var name = assemblyName.Name;
|
||||
if (string.IsNullOrEmpty(name)) return null;
|
||||
if (Shared.Contains(name)) return null; // 用启动器已加载的那份
|
||||
if (name.StartsWith("System.", StringComparison.OrdinalIgnoreCase)) return null;
|
||||
if (name is "System" or "netstandard" or "mscorlib") return null;
|
||||
|
||||
var candidate = Path.Combine(_directory, name + ".dll");
|
||||
return File.Exists(candidate) ? LoadFromAssemblyPath(candidate) : null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>启动器提供给模型的环境。</summary>
|
||||
public sealed class ModelContext : IModelContext
|
||||
{
|
||||
private readonly Action _requestClose;
|
||||
private readonly Action<double, string?>? _progress;
|
||||
|
||||
public ModelContext(ModelPackage package, string language, int memoryMb, Action requestClose,
|
||||
Action<double, string?>? progress)
|
||||
{
|
||||
_progress = progress;
|
||||
ModelId = package.Id;
|
||||
ModelDirectory = package.Directory;
|
||||
DataDirectory = package.DataDirectory;
|
||||
Language = language;
|
||||
MemoryBudgetMb = memoryMb;
|
||||
_requestClose = requestClose;
|
||||
}
|
||||
|
||||
public string ModelId { get; }
|
||||
public string ModelDirectory { get; }
|
||||
public string DataDirectory { get; }
|
||||
public string Language { get; }
|
||||
public int MemoryBudgetMb { get; }
|
||||
|
||||
public void RequestClose() => _requestClose();
|
||||
|
||||
public void ReportProgress(double value, string? message = null) => _progress?.Invoke(value, message);
|
||||
|
||||
public void Log(string message) => Console.WriteLine(message);
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -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
|
||||
}
|
||||
@@ -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")
|
||||
@@ -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,122 @@
|
||||
#!/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
|
||||
|
||||
# CI 上没有签名证书:GC_NO_CODESIGN=1 时给 macOS 加 --no-codesign,
|
||||
# 直接产出未签名的 .app(用户首次打开需右键「打开」或在系统设置里放行)。
|
||||
_flags="--release"
|
||||
if [ "${GC_NO_CODESIGN:-0}" = 1 ] && [ "$_plat" = macos ]; then
|
||||
_flags="$_flags --no-codesign"
|
||||
fi
|
||||
|
||||
run_logged "$GC_ROOT/build/logs/flutter-$_plat.log" "Flutter $_plat 构建 " \
|
||||
_flutter build "$_plat" $_flags || 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"))"
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
};
|
||||
})();
|
||||
|
Before Width: | Height: | Size: 2.6 MiB |
|
Before Width: | Height: | Size: 3.3 MiB |
|
Before Width: | Height: | Size: 2.4 MiB |
|
Before Width: | Height: | Size: 2.4 MiB |
|
Before Width: | Height: | Size: 3.2 MiB |
|
Before Width: | Height: | Size: 2.5 MiB |
|
Before Width: | Height: | Size: 3.3 MiB |
|
Before Width: | Height: | Size: 2.4 MiB |
|
Before Width: | Height: | Size: 3.3 MiB |