Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2cd18b4e5f | ||
|
|
023e9468db | ||
|
|
5e5d84856a | ||
|
|
b4724d7ca0 | ||
|
|
9a911089bf | ||
|
|
4bdfb49600 | ||
|
|
59a66c8fa8 | ||
|
|
a5fcaeb658 | ||
|
|
fcaacf3b33 | ||
|
|
0997de514e | ||
|
|
192f2a63e9 | ||
|
|
a1a14f106b | ||
|
|
e67cc63998 | ||
|
|
2ba4789c95 | ||
|
|
22baa6fda9 | ||
|
|
6ee2e8bead | ||
|
|
daf218ce71 | ||
|
|
631a90e862 | ||
|
|
40af11f78a | ||
|
|
4bcffa782d | ||
|
|
097bfd198e | ||
|
|
31b0c93b25 | ||
|
|
39dc23cb57 | ||
|
|
a361c889f8 | ||
|
|
461e79aa7f | ||
|
|
d7f6d8de9f | ||
|
|
7e34cb0467 | ||
|
|
e327a56421 | ||
|
|
40e72957e3 | ||
|
|
fdbf3160e8 | ||
|
|
2cc862a8da | ||
|
|
2c0c566c81 | ||
|
|
926a568dc0 | ||
|
|
cd44c7ecff | ||
|
|
aeab68d421 | ||
|
|
0b2f263dea | ||
|
|
a18d0ea1a8 | ||
|
|
06eb4875a1 | ||
|
|
2b4ffc7ce5 | ||
|
|
d379902a7a | ||
|
|
056d64a3bc | ||
|
|
ae73eca2c4 | ||
|
|
fa492bbb19 | ||
|
|
8904230a6f | ||
|
|
3480cbaa5f | ||
|
|
9ca99a1fe1 | ||
|
|
2f3a8682c9 | ||
|
|
791db4fe12 | ||
|
|
c95dfaf9f3 | ||
|
|
0ddee422ab | ||
|
|
a1211521eb | ||
|
|
512b1814e1 | ||
|
|
663efa5c75 | ||
|
|
8dcbd6f9d7 |
No files matched your search
@@ -0,0 +1,393 @@
|
|||||||
|
# GC-UI alpha 构建(Gitea Actions)
|
||||||
|
#
|
||||||
|
# 触发:**仅手动**。定时任务已取消(不再每天自动构建),需要时在 Actions 页面点
|
||||||
|
# Run workflow,或从命令行调
|
||||||
|
# POST /api/v1/repos/{owner}/{repo}/actions/workflows/{file}/dispatches。
|
||||||
|
# 产物:Windows 与 macOS 的 Flutter 前端,发布为一个「预览版(prerelease)」Release —— 不占用 latest。
|
||||||
|
#
|
||||||
|
# 为什么是 .gitea/workflows/:本仓库是自建 Gitea,不是 GitHub。Gitea Actions 语法与
|
||||||
|
# GitHub Actions 基本一致,但工作流目录是 .gitea/workflows/,API 前缀是 /api/v1,
|
||||||
|
# runner 标签必须与 act_runner 上注册的 label 一致(见 GC-UI/CI.md)。
|
||||||
|
#
|
||||||
|
# 为什么 alpha 不会变成 latest:Gitea 的 /releases/latest 按定义只返回「最近一个既非草稿
|
||||||
|
# 也非 prerelease」的发布,所以 prerelease=true 的版本永远不会被当成 latest。
|
||||||
|
# publish 任务最后还会主动断言一次,确认 latest 没有指向本次 tag。
|
||||||
|
|
||||||
|
name: GC-UI Alpha
|
||||||
|
|
||||||
|
on:
|
||||||
|
# 定时触发已取消:夜间构建会绕开 build.sh,产出不含后端/前端的空壳包,
|
||||||
|
# 且 cron 的 TZ= 前缀在部分 Gitea 版本上非法。需要时手动 dispatch。
|
||||||
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
note:
|
||||||
|
description: '额外写进 Release 说明的备注(可留空)'
|
||||||
|
required: false
|
||||||
|
default: ''
|
||||||
|
|
||||||
|
# 用 github.token 往本仓库建 Release / 传附件,需要 contents 写权限
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
|
||||||
|
env:
|
||||||
|
GITEA_API: ${{ github.server_url }}/api/v1
|
||||||
|
REPO: ${{ github.repository }}
|
||||||
|
FRONTEND_DIR: GC-UI/frontend
|
||||||
|
# runner 上没预装 Flutter 时,按这个版本自举(需 >= 3.5.4,与 pubspec.yaml 的 sdk 约束对齐)
|
||||||
|
FLUTTER_VERSION: 3.24.5
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
# ---------------------------------------------------------------- 1. 版本与草稿
|
||||||
|
prepare:
|
||||||
|
name: 计算 alpha 版本并创建预览版草稿
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
outputs:
|
||||||
|
version: ${{ steps.meta.outputs.version }}
|
||||||
|
base_version: ${{ steps.meta.outputs.base_version }}
|
||||||
|
tag: ${{ steps.meta.outputs.tag }}
|
||||||
|
build_number: ${{ steps.meta.outputs.build_number }}
|
||||||
|
release_id: ${{ steps.release.outputs.release_id }}
|
||||||
|
steps:
|
||||||
|
- name: 检出代码
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: 计算版本号
|
||||||
|
id: meta
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
# 基础版本取自 version.json 的 launcher.version(例如 1.0.7),与启动器保持一致;
|
||||||
|
# alpha 后缀只表示构建通道,写在 tag / Release 标题里。
|
||||||
|
BASE=$(python3 -c "import json;print(json.load(open('version.json'))['launcher']['version'])")
|
||||||
|
if [ -z "${BASE:-}" ]; then
|
||||||
|
echo "::error::无法从 version.json 读取 launcher.version"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# 北京时间当天日期,让同一天的多次手动构建落在同一个日期前缀下
|
||||||
|
DATE=$(TZ=Asia/Shanghai date +%Y%m%d)
|
||||||
|
# 同一天重跑时用 run_number 区分,tag 不重复
|
||||||
|
VERSION="${BASE}-alpha.${DATE}.${{ github.run_number }}"
|
||||||
|
|
||||||
|
# 传给 flutter 的版本号必须是纯数字分段:
|
||||||
|
# --build-name → macOS CFBundleShortVersionString,只能是 a.b.c
|
||||||
|
# --build-number → CFBundleVersion / 文件版本号,只能是数字
|
||||||
|
# 所以 alpha 的日期与序号放在 build-number 里,不放进 build-name。
|
||||||
|
BUILD_NUMBER="${DATE}$(printf '%02d' "${{ github.run_number }}")"
|
||||||
|
|
||||||
|
{
|
||||||
|
echo "version=$VERSION"
|
||||||
|
echo "base_version=$BASE"
|
||||||
|
echo "tag=v$VERSION"
|
||||||
|
echo "build_number=$BUILD_NUMBER"
|
||||||
|
} >> "$GITHUB_OUTPUT"
|
||||||
|
echo "alpha 版本: $VERSION(build-name=$BASE, build-number=$BUILD_NUMBER)"
|
||||||
|
|
||||||
|
- name: 创建预览版草稿
|
||||||
|
id: release
|
||||||
|
env:
|
||||||
|
# 优先用仓库 Secrets 里的 RELEASE_TOKEN;没配就退回 Gitea 自动注入的 github.token。
|
||||||
|
# 某些实例上自动 token 没有 releases 写权限,那时只需在
|
||||||
|
# Settings → Actions → Secrets 加一个 RELEASE_TOKEN,不用改本文件。
|
||||||
|
TOKEN_OVERRIDE: ${{ secrets.RELEASE_TOKEN }}
|
||||||
|
TOKEN_DEFAULT: ${{ github.token }}
|
||||||
|
TAG: ${{ steps.meta.outputs.tag }}
|
||||||
|
VERSION: ${{ steps.meta.outputs.version }}
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
TOKEN="${TOKEN_OVERRIDE:-$TOKEN_DEFAULT}"
|
||||||
|
if [ -z "${TOKEN:-}" ]; then
|
||||||
|
echo "::error::拿不到 Gitea token,无法创建 Release"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
api="$GITEA_API/repos/$REPO"
|
||||||
|
auth=(-H "Authorization: token $TOKEN")
|
||||||
|
|
||||||
|
# 可重跑:同 tag 的旧发布先删掉(只会是同一天重跑留下的)
|
||||||
|
code=$(curl -sS -o /tmp/existing.json -w '%{http_code}' "${auth[@]}" "$api/releases/tags/$TAG")
|
||||||
|
if [ "$code" = "200" ]; then
|
||||||
|
old_id=$(python3 -c "import json;print(json.load(open('/tmp/existing.json'))['id'])")
|
||||||
|
echo "已存在同 tag 发布 id=$old_id,先删除"
|
||||||
|
curl -sS -X DELETE "${auth[@]}" "$api/releases/$old_id" >/dev/null
|
||||||
|
fi
|
||||||
|
|
||||||
|
# draft=true + prerelease=true:
|
||||||
|
# prerelease → 永不成为 latest
|
||||||
|
# draft → 两个平台都构建成功前不对外可见,由 publish 任务翻成 false
|
||||||
|
payload=$(python3 - "$TAG" "$VERSION" "${{ github.sha }}" "${{ github.server_url }}" <<'PY'
|
||||||
|
import json, sys
|
||||||
|
tag, version, sha, server = sys.argv[1:5]
|
||||||
|
short = sha[:7]
|
||||||
|
body = (
|
||||||
|
"GC-UI alpha 构建(手动触发,**预览版 / prerelease**)。\n\n"
|
||||||
|
"- 版本:`%s`\n"
|
||||||
|
"- 提交:`%s`\n"
|
||||||
|
"- 构建来源:%s/commit/%s\n"
|
||||||
|
"- 通道:alpha —— 手动触发(定时任务已取消)\n\n"
|
||||||
|
"产物说明:\n\n"
|
||||||
|
"| 文件 | 平台 | 内容 |\n"
|
||||||
|
"|---|---|---|\n"
|
||||||
|
"| `gc-ui-alpha-windows-x64.zip` | Windows x64 | Flutter 前端 release 目录 |\n"
|
||||||
|
"| `gc-ui-alpha-macos-<arch>.zip` | macOS | `gc_ui.app` 应用包 |\n\n"
|
||||||
|
"这是前端产物,运行时需要配合 `GC-UI/backend/GC.UI.Server` 后端(默认 `127.0.0.1:17890`)。\n"
|
||||||
|
"未做代码签名,首次运行系统可能会提示。\n\n"
|
||||||
|
"> 本发布不是 latest:prerelease 的版本不会出现在「最新版本」里。\n"
|
||||||
|
) % (version, short, server, sha)
|
||||||
|
print(json.dumps({
|
||||||
|
"tag_name": tag,
|
||||||
|
"target_commitish": sha,
|
||||||
|
"name": "GC-UI Alpha " + version,
|
||||||
|
"body": body,
|
||||||
|
"draft": True,
|
||||||
|
"prerelease": True,
|
||||||
|
}))
|
||||||
|
PY
|
||||||
|
)
|
||||||
|
|
||||||
|
resp=$(curl -sS -X POST "${auth[@]}" -H 'Content-Type: application/json' -d "$payload" "$api/releases")
|
||||||
|
rid=$(printf '%s' "$resp" | python3 -c "import json,sys;print(json.load(sys.stdin).get('id',''))" 2>/dev/null || true)
|
||||||
|
if [ -z "$rid" ]; then
|
||||||
|
echo "::error::创建 Release 失败: $resp"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo "release_id=$rid" >> "$GITHUB_OUTPUT"
|
||||||
|
echo "已创建预览版草稿 id=$rid tag=$TAG"
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- 2. Windows
|
||||||
|
windows:
|
||||||
|
name: 构建 Windows 前端
|
||||||
|
needs: prepare
|
||||||
|
runs-on: windows-latest
|
||||||
|
steps:
|
||||||
|
- name: 检出代码
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: 准备 Flutter SDK
|
||||||
|
shell: pwsh
|
||||||
|
run: |
|
||||||
|
$ErrorActionPreference = 'Stop'
|
||||||
|
if (Get-Command flutter -ErrorAction SilentlyContinue) {
|
||||||
|
Write-Host 'runner 已自带 Flutter:'
|
||||||
|
flutter --version
|
||||||
|
} else {
|
||||||
|
Write-Host "runner 上没有 Flutter,按官方 SDK $env:FLUTTER_VERSION 自举"
|
||||||
|
$url = "https://storage.googleapis.com/flutter_infra_release/releases/stable/windows/flutter_windows_$env:FLUTTER_VERSION-stable.zip"
|
||||||
|
$zip = Join-Path $env:RUNNER_TEMP 'flutter.zip'
|
||||||
|
curl.exe -sSL --retry 3 -o $zip $url
|
||||||
|
if ($LASTEXITCODE -ne 0) { Write-Error "下载 Flutter SDK 失败: $url"; exit 1 }
|
||||||
|
Expand-Archive -Path $zip -DestinationPath $env:RUNNER_TEMP -Force
|
||||||
|
$flutterBin = Join-Path $env:RUNNER_TEMP 'flutter\bin'
|
||||||
|
$flutterBin | Out-File -FilePath $env:GITHUB_PATH -Append -Encoding utf8
|
||||||
|
$env:PATH = "$flutterBin;$env:PATH"
|
||||||
|
flutter --version
|
||||||
|
}
|
||||||
|
# Windows 桌面构建依赖 VS Build Tools 的「使用 C++ 的桌面开发」工作负载
|
||||||
|
$doctor = flutter doctor -v 2>&1 | Out-String
|
||||||
|
if ($doctor -notmatch 'Visual Studio') {
|
||||||
|
Write-Host '::warning::flutter doctor 没看到 Visual Studio,Windows 构建很可能失败'
|
||||||
|
}
|
||||||
|
Write-Host "PROCESSOR_ARCHITECTURE=$env:PROCESSOR_ARCHITECTURE"
|
||||||
|
|
||||||
|
- name: 构建前端(release)
|
||||||
|
shell: pwsh
|
||||||
|
env:
|
||||||
|
VERSION: ${{ needs.prepare.outputs.base_version }}
|
||||||
|
BUILD_NUMBER: ${{ needs.prepare.outputs.build_number }}
|
||||||
|
run: |
|
||||||
|
$ErrorActionPreference = 'Stop'
|
||||||
|
flutter config --no-analytics 2>&1 | Out-Null
|
||||||
|
Set-Location $env:FRONTEND_DIR
|
||||||
|
flutter pub get
|
||||||
|
if ($LASTEXITCODE -ne 0) { exit 1 }
|
||||||
|
flutter build windows --release --build-name=$env:VERSION --build-number=$env:BUILD_NUMBER
|
||||||
|
if ($LASTEXITCODE -ne 0) { exit 1 }
|
||||||
|
|
||||||
|
- name: 打包
|
||||||
|
id: pack
|
||||||
|
shell: pwsh
|
||||||
|
run: |
|
||||||
|
$ErrorActionPreference = 'Stop'
|
||||||
|
# x64 / arm64 的产物都在 build\windows\<arch>\runner\Release,直接找实际存在的那个
|
||||||
|
$out = Get-ChildItem "$env:FRONTEND_DIR\build\windows" -Directory -ErrorAction SilentlyContinue |
|
||||||
|
ForEach-Object { Join-Path $_.FullName 'runner\Release' } |
|
||||||
|
Where-Object { Test-Path $_ } |
|
||||||
|
Select-Object -First 1
|
||||||
|
if (-not $out) {
|
||||||
|
Write-Error "没有找到 Windows 产物目录($env:FRONTEND_DIR\build\windows\*\runner\Release)"
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
$arch = if ($env:PROCESSOR_ARCHITECTURE -eq 'ARM64') { 'arm64' } else { 'x64' }
|
||||||
|
$name = "gc-ui-alpha-windows-$arch.zip"
|
||||||
|
New-Item -ItemType Directory -Force -Path dist | Out-Null
|
||||||
|
$zip = Join-Path (Get-Location) "dist\$name"
|
||||||
|
Compress-Archive -Path (Join-Path $out '*') -DestinationPath $zip -Force
|
||||||
|
Get-Item $zip | Format-List Name, Length
|
||||||
|
"asset=$zip" | Out-File -FilePath $env:GITHUB_OUTPUT -Append -Encoding utf8
|
||||||
|
"asset_name=$name" | Out-File -FilePath $env:GITHUB_OUTPUT -Append -Encoding utf8
|
||||||
|
|
||||||
|
- name: 上传到预览版
|
||||||
|
shell: pwsh
|
||||||
|
env:
|
||||||
|
TOKEN_OVERRIDE: ${{ secrets.RELEASE_TOKEN }}
|
||||||
|
TOKEN_DEFAULT: ${{ github.token }}
|
||||||
|
RELEASE_ID: ${{ needs.prepare.outputs.release_id }}
|
||||||
|
ASSET: ${{ steps.pack.outputs.asset }}
|
||||||
|
ASSET_NAME: ${{ steps.pack.outputs.asset_name }}
|
||||||
|
run: |
|
||||||
|
$ErrorActionPreference = 'Stop'
|
||||||
|
$token = if ($env:TOKEN_OVERRIDE) { $env:TOKEN_OVERRIDE } else { $env:TOKEN_DEFAULT }
|
||||||
|
if (-not $token) { Write-Error '拿不到 Gitea token'; exit 1 }
|
||||||
|
$url = "$env:GITEA_API/repos/$env:REPO/releases/$env:RELEASE_ID/assets?name=$env:ASSET_NAME"
|
||||||
|
curl.exe -sS -X POST -H "Authorization: token $token" -H "Content-Type: application/octet-stream" --data-binary "@$env:ASSET" $url
|
||||||
|
if ($LASTEXITCODE -ne 0) { exit 1 }
|
||||||
|
Write-Host "`n已上传 $env:ASSET_NAME"
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- 3. macOS
|
||||||
|
macos:
|
||||||
|
name: 构建 macOS 前端
|
||||||
|
needs: prepare
|
||||||
|
runs-on: macos-latest
|
||||||
|
steps:
|
||||||
|
- name: 检出代码
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: 准备 Flutter SDK
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
if command -v flutter >/dev/null 2>&1; then
|
||||||
|
echo "runner 已自带 Flutter:"
|
||||||
|
flutter --version
|
||||||
|
else
|
||||||
|
echo "runner 上没有 Flutter,按官方 SDK $FLUTTER_VERSION 自举"
|
||||||
|
case "$(uname -m)" in
|
||||||
|
arm64) SUFFIX="macos_arm64" ;;
|
||||||
|
*) SUFFIX="macos" ;;
|
||||||
|
esac
|
||||||
|
URL="https://storage.googleapis.com/flutter_infra_release/releases/stable/${SUFFIX}/flutter_${SUFFIX}_${FLUTTER_VERSION}-stable.zip"
|
||||||
|
ZIP="$RUNNER_TEMP/flutter.zip"
|
||||||
|
curl -sSL --retry 3 -o "$ZIP" "$URL"
|
||||||
|
rm -rf "$RUNNER_TEMP/flutter"
|
||||||
|
unzip -q "$ZIP" -d "$RUNNER_TEMP"
|
||||||
|
echo "$RUNNER_TEMP/flutter/bin" >> "$GITHUB_PATH"
|
||||||
|
export PATH="$RUNNER_TEMP/flutter/bin:$PATH"
|
||||||
|
flutter --version
|
||||||
|
fi
|
||||||
|
xcodebuild -version || echo "::warning::没找到 xcodebuild,macOS 构建很可能失败"
|
||||||
|
|
||||||
|
- name: 构建前端(release)
|
||||||
|
env:
|
||||||
|
VERSION: ${{ needs.prepare.outputs.base_version }}
|
||||||
|
BUILD_NUMBER: ${{ needs.prepare.outputs.build_number }}
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
flutter config --no-analytics || true
|
||||||
|
cd "$FRONTEND_DIR"
|
||||||
|
flutter pub get
|
||||||
|
flutter build macos --release --build-name="$VERSION" --build-number="$BUILD_NUMBER"
|
||||||
|
|
||||||
|
- name: 打包
|
||||||
|
id: pack
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
APP="$FRONTEND_DIR/build/macos/Build/Products/Release/gc_ui.app"
|
||||||
|
if [ ! -d "$APP" ]; then
|
||||||
|
echo "::error::没有找到 macOS 产物: $APP"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
case "$(uname -m)" in
|
||||||
|
arm64) ARCH=arm64 ;;
|
||||||
|
*) ARCH=x64 ;;
|
||||||
|
esac
|
||||||
|
NAME="gc-ui-alpha-macos-${ARCH}.zip"
|
||||||
|
mkdir -p dist
|
||||||
|
# 用 ditto 才能保真 .app 内的符号链接与权限,zip -r 会破坏 .app 结构
|
||||||
|
ditto -c -k --sequesterRsrc --keepParent "$APP" "dist/$NAME"
|
||||||
|
ls -lh "dist/$NAME"
|
||||||
|
{
|
||||||
|
echo "asset=dist/$NAME"
|
||||||
|
echo "asset_name=$NAME"
|
||||||
|
} >> "$GITHUB_OUTPUT"
|
||||||
|
|
||||||
|
- name: 上传到预览版
|
||||||
|
env:
|
||||||
|
TOKEN_OVERRIDE: ${{ secrets.RELEASE_TOKEN }}
|
||||||
|
TOKEN_DEFAULT: ${{ github.token }}
|
||||||
|
RELEASE_ID: ${{ needs.prepare.outputs.release_id }}
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
TOKEN="${TOKEN_OVERRIDE:-$TOKEN_DEFAULT}"
|
||||||
|
if [ -z "${TOKEN:-}" ]; then
|
||||||
|
echo "::error::拿不到 Gitea token"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
curl -sS -X POST \
|
||||||
|
-H "Authorization: token $TOKEN" \
|
||||||
|
-H "Content-Type: application/octet-stream" \
|
||||||
|
--data-binary "@${{ steps.pack.outputs.asset }}" \
|
||||||
|
"$GITEA_API/repos/$REPO/releases/$RELEASE_ID/assets?name=${{ steps.pack.outputs.asset_name }}"
|
||||||
|
echo
|
||||||
|
echo "已上传 ${{ steps.pack.outputs.asset_name }}"
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- 4. 发布预览版
|
||||||
|
publish:
|
||||||
|
name: 发布预览版(保持 prerelease,不占用 latest)
|
||||||
|
needs: [prepare, windows, macos]
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: 把草稿翻成正式预览版
|
||||||
|
env:
|
||||||
|
TOKEN_OVERRIDE: ${{ secrets.RELEASE_TOKEN }}
|
||||||
|
TOKEN_DEFAULT: ${{ github.token }}
|
||||||
|
RELEASE_ID: ${{ needs.prepare.outputs.release_id }}
|
||||||
|
TAG: ${{ needs.prepare.outputs.tag }}
|
||||||
|
NOTE: ${{ github.event.inputs.note }}
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
TOKEN="${TOKEN_OVERRIDE:-$TOKEN_DEFAULT}"
|
||||||
|
api="$GITEA_API/repos/$REPO"
|
||||||
|
auth=(-H "Authorization: token $TOKEN")
|
||||||
|
|
||||||
|
code=$(curl -sS -o /tmp/rel.json -w '%{http_code}' "${auth[@]}" "$api/releases/$RELEASE_ID")
|
||||||
|
if [ "$code" != "200" ]; then
|
||||||
|
echo "::error::读不到 Release $RELEASE_ID (HTTP $code)"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
payload=$(python3 - /tmp/rel.json "${NOTE:-}" <<'PY'
|
||||||
|
import json, sys
|
||||||
|
rel = json.load(open(sys.argv[1]))
|
||||||
|
note = (sys.argv[2] or "").strip()
|
||||||
|
body = rel.get("body") or ""
|
||||||
|
if note:
|
||||||
|
body += "\n---\n\n备注:" + note + "\n"
|
||||||
|
print(json.dumps({
|
||||||
|
"body": body,
|
||||||
|
"draft": False, # 可见
|
||||||
|
"prerelease": True, # 关键:永不成为 latest
|
||||||
|
}))
|
||||||
|
PY
|
||||||
|
)
|
||||||
|
|
||||||
|
patched=$(curl -sS -X PATCH "${auth[@]}" -H 'Content-Type: application/json' -d "$payload" "$api/releases/$RELEASE_ID")
|
||||||
|
printf '%s' "$patched" > /tmp/patched.json
|
||||||
|
python3 - <<'PY'
|
||||||
|
import json
|
||||||
|
d = json.load(open('/tmp/patched.json'))
|
||||||
|
print('发布成功:', d.get('html_url'), '| prerelease =', d.get('prerelease'), '| draft =', d.get('draft'))
|
||||||
|
assert d.get('prerelease') is True, 'Release 没有被标记成 prerelease,会顶掉 latest'
|
||||||
|
assert d.get('draft') is False, 'Release 仍是草稿'
|
||||||
|
PY
|
||||||
|
|
||||||
|
- name: 断言 latest 未被占用
|
||||||
|
env:
|
||||||
|
TAG: ${{ needs.prepare.outputs.tag }}
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
latest_tag=$(curl -sS "$GITEA_API/repos/$REPO/releases/latest" \
|
||||||
|
| python3 -c "import json,sys;print(json.load(sys.stdin).get('tag_name') or '')" || true)
|
||||||
|
echo "本次 tag: $TAG"
|
||||||
|
echo "latest 指向: ${latest_tag:-(空)}"
|
||||||
|
if [ "$latest_tag" = "$TAG" ]; then
|
||||||
|
echo "::error::本次 alpha 成了 latest,prerelease 标记失效"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo "OK:alpha 未占用 latest"
|
||||||
@@ -0,0 +1,143 @@
|
|||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# PR 审核流水线(Gitea Actions)
|
||||||
|
#
|
||||||
|
# 触发:向 main / gc-ui 提 PR(新建、追加提交、重新打开、取消草稿)时执行。
|
||||||
|
# 覆盖:后端编译、后端自检、前端静态分析 / 测试、依赖漏洞与硬编码密钥扫描,
|
||||||
|
# 最后用 review-gate 汇总,任意一项失败则整条流水线失败(阻止合并)。
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
name: PR 审核
|
||||||
|
|
||||||
|
on:
|
||||||
|
pull_request:
|
||||||
|
branches: [main, gc-ui]
|
||||||
|
types: [opened, synchronize, reopened, ready_for_review]
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: pr-check-${{ github.event.pull_request.number }}
|
||||||
|
cancel-in-progress: true
|
||||||
|
|
||||||
|
env:
|
||||||
|
# Avalonia 遥测任务在 CI 只读目录会写日志失败并中断编译(MSB4018)
|
||||||
|
AVALONIA_TELEMETRY_OPTOUT: '1'
|
||||||
|
DOTNET_NOLOGO: '1'
|
||||||
|
DOTNET_CLI_TELEMETRY_OPTOUT: '1'
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
backend-build:
|
||||||
|
name: 后端编译
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: 检出代码
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: 安装 .NET 8
|
||||||
|
uses: actions/setup-dotnet@v4
|
||||||
|
with:
|
||||||
|
dotnet-version: '8.0.x'
|
||||||
|
|
||||||
|
- name: 还原依赖
|
||||||
|
run: dotnet restore GC.sln
|
||||||
|
|
||||||
|
- name: 编译整个解决方案(Release)
|
||||||
|
run: dotnet build GC.sln -c Release --no-restore
|
||||||
|
|
||||||
|
- name: 编译 GC-UI 后端(前后端契约变更时单独验证)
|
||||||
|
run: dotnet build GC-UI/backend/GC.UI.Server/GC.UI.Server.csproj -c Release --no-restore
|
||||||
|
|
||||||
|
backend-test:
|
||||||
|
name: 后端自检
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs: backend-build
|
||||||
|
steps:
|
||||||
|
- name: 检出代码
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: 安装 .NET 8
|
||||||
|
uses: actions/setup-dotnet@v4
|
||||||
|
with:
|
||||||
|
dotnet-version: '8.0.x'
|
||||||
|
|
||||||
|
- name: 运行 GC.Tests(含离屏渲染 / 清单校验 / 日志用例)
|
||||||
|
run: dotnet run --project GC/src/test/dotnet/GC.Tests/GC.Tests.csproj -c Release
|
||||||
|
|
||||||
|
- name: 运行应用器测试(整目录替换 / .GC/bin 合并 / 回滚)
|
||||||
|
run: dotnet run --project GC/src/test/dotnet/GC.Savedog.Tests/GC.Savedog.Tests.csproj -c Release
|
||||||
|
|
||||||
|
frontend:
|
||||||
|
name: 前端检查(Flutter)
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: 检出代码
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: 安装 Flutter
|
||||||
|
uses: subosito/flutter-action@v2
|
||||||
|
with:
|
||||||
|
channel: stable
|
||||||
|
cache: true
|
||||||
|
|
||||||
|
- name: 拉取依赖
|
||||||
|
working-directory: GC-UI/frontend
|
||||||
|
run: flutter pub get
|
||||||
|
|
||||||
|
- name: 静态分析
|
||||||
|
working-directory: GC-UI/frontend
|
||||||
|
run: flutter analyze --no-fatal-infos --no-fatal-warnings
|
||||||
|
|
||||||
|
- name: 单元 / 组件测试
|
||||||
|
working-directory: GC-UI/frontend
|
||||||
|
run: flutter test
|
||||||
|
|
||||||
|
security:
|
||||||
|
name: 安全扫描
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: 检出代码
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: 安装 .NET 8
|
||||||
|
uses: actions/setup-dotnet@v4
|
||||||
|
with:
|
||||||
|
dotnet-version: '8.0.x'
|
||||||
|
|
||||||
|
- name: 依赖漏洞扫描(含传递依赖)
|
||||||
|
run: |
|
||||||
|
dotnet restore GC.sln
|
||||||
|
dotnet list GC.sln package --vulnerable --include-transitive
|
||||||
|
|
||||||
|
- name: 硬编码密钥 / 口令扫描
|
||||||
|
run: |
|
||||||
|
set +e
|
||||||
|
echo "扫描源码中的疑似明文口令 / 令牌…"
|
||||||
|
MATCHES=$(grep -rInE \
|
||||||
|
--include='*.cs' --include='*.dart' --include='*.yml' --include='*.yaml' \
|
||||||
|
--include='*.sh' --include='*.ps1' --include='*.json' \
|
||||||
|
'(password|passwd|secret|api[_-]?key|access[_-]?token)[[:space:]]*[:=][[:space:]]*["'\''][^"'\''[:space:]]{6,}' \
|
||||||
|
. 2>/dev/null | grep -vE 'example|placeholder|dummy|CHANGEME|YOUR_|\$\{\{')
|
||||||
|
if [ -n "$MATCHES" ]; then
|
||||||
|
echo "$MATCHES"
|
||||||
|
echo "::error::发现疑似硬编码凭据,请改用 Secrets 或环境变量"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo "未发现硬编码凭据"
|
||||||
|
|
||||||
|
review-gate:
|
||||||
|
name: 审核汇总
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs: [backend-build, backend-test, frontend, security]
|
||||||
|
if: always()
|
||||||
|
steps:
|
||||||
|
- name: 检查各阶段结果
|
||||||
|
run: |
|
||||||
|
echo "后端编译: ${{ needs.backend-build.result }}"
|
||||||
|
echo "后端自检: ${{ needs.backend-test.result }}"
|
||||||
|
echo "前端检查: ${{ needs.frontend.result }}"
|
||||||
|
echo "安全扫描: ${{ needs.security.result }}"
|
||||||
|
if [ "${{ needs.backend-build.result }}" != "success" ] || \
|
||||||
|
[ "${{ needs.backend-test.result }}" != "success" ] || \
|
||||||
|
[ "${{ needs.frontend.result }}" != "success" ] || \
|
||||||
|
[ "${{ needs.security.result }}" != "success" ]; then
|
||||||
|
echo "::error::审核未通过:存在失败阶段,请修复后重新提交"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo "审核通过:可以合并"
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# 发布一致性核对(Gitea Actions)
|
||||||
|
#
|
||||||
|
# 触发:仅手动。发布前跑一次确认「tag / 清单 / 资产」互相对得上,发布后再跑一次
|
||||||
|
# 确认线上资产就是清单里那两份。
|
||||||
|
#
|
||||||
|
# 为什么不用 pull_request 触发:这里要下载几百 MB 的发布包,PR 阶段跑太贵;
|
||||||
|
# 需要时点 Run workflow 即可,本地也有等价命令:./build.sh release-verify <tag>
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
name: 发布核对
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
tag:
|
||||||
|
description: '要核对的 tag(如 1.1.0)'
|
||||||
|
required: true
|
||||||
|
skip_download:
|
||||||
|
description: '只比对体积、不下载校验 sha256(快,输入 1 开启)'
|
||||||
|
required: false
|
||||||
|
default: ''
|
||||||
|
|
||||||
|
env:
|
||||||
|
DOTNET_NOLOGO: '1'
|
||||||
|
DOTNET_CLI_TELEMETRY_OPTOUT: '1'
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
verify:
|
||||||
|
name: 核对 Release 与清单
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: 检出代码
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: 安装 .NET 8
|
||||||
|
uses: actions/setup-dotnet@v4
|
||||||
|
with:
|
||||||
|
dotnet-version: '8.0.x'
|
||||||
|
|
||||||
|
- name: 核对
|
||||||
|
env:
|
||||||
|
GC_GITEA_TOKEN: ${{ secrets.GC_GITEA_TOKEN }}
|
||||||
|
run: |
|
||||||
|
set -eu
|
||||||
|
EXTRA=""
|
||||||
|
if [ -n "${{ github.event.inputs.skip_download }}" ]; then
|
||||||
|
EXTRA="--skip-download"
|
||||||
|
fi
|
||||||
|
chmod +x buildsh/lib/verify_release.py
|
||||||
|
./build.sh release-verify "${{ github.event.inputs.tag }}" $EXTRA
|
||||||
@@ -1,6 +1,9 @@
|
|||||||
# 运行数据目录(settings/model/cache/update),绝不入库
|
# 运行数据目录(settings/model/cache/update),绝不入库
|
||||||
.GC/
|
.GC/
|
||||||
|
|
||||||
|
# 签名私钥:绝对不入库(公钥写在 GC/src/Security/SignatureKeyring.cs 里)
|
||||||
|
.signing/
|
||||||
|
|
||||||
# .NET 构建中间产物(已跟踪的历史文件不动,只防新增)
|
# .NET 构建中间产物(已跟踪的历史文件不动,只防新增)
|
||||||
bin/
|
bin/
|
||||||
obj/
|
obj/
|
||||||
@@ -20,3 +23,34 @@ dist/
|
|||||||
build/
|
build/
|
||||||
.pytest_cache/
|
.pytest_cache/
|
||||||
.mypy_cache/
|
.mypy_cache/
|
||||||
|
|
||||||
|
# ---- GC-UI(Flutter 前端)----
|
||||||
|
# Flutter / Dart 构建产物与本地工具状态
|
||||||
|
GC-UI/frontend/.dart_tool/
|
||||||
|
GC-UI/frontend/.flutter-plugins
|
||||||
|
GC-UI/frontend/.flutter-plugins-dependencies
|
||||||
|
GC-UI/frontend/.packages
|
||||||
|
GC-UI/frontend/build/
|
||||||
|
GC-UI/frontend/**/Flutter/ephemeral/
|
||||||
|
GC-UI/frontend/**/GeneratedPluginRegistrant.*
|
||||||
|
GC-UI/frontend/**/generated_plugin_registrant.*
|
||||||
|
GC-UI/frontend/**/generated_plugins.cmake
|
||||||
|
GC-UI/frontend/**/generated_plugins.h
|
||||||
|
GC-UI/frontend/**/generated_plugin_registrant.h
|
||||||
|
GC-UI/frontend/**/generated_plugin_registrant.cc
|
||||||
|
GC-UI/frontend/**/generated_plugin_registrant.swift
|
||||||
|
GC-UI/frontend/**/flutter_export_environment.sh
|
||||||
|
GC-UI/frontend/**/xcschemes/xcschememanagement.plist
|
||||||
|
GC-UI/frontend/**/Pods/
|
||||||
|
GC-UI/frontend/**/Podfile.lock
|
||||||
|
GC-UI/frontend/**/.symlinks/
|
||||||
|
GC-UI/frontend/**/Runner.xcworkspace/xcuserdata/
|
||||||
|
GC-UI/frontend/**/Runner.xcodeproj/xcuserdata/
|
||||||
|
GC-UI/frontend/**/Runner.xcodeproj/project.xcworkspace/xcuserdata/
|
||||||
|
GC-UI/frontend/**/DebugProfile.entitlements.bak
|
||||||
|
GC-UI/frontend/**/*.iml
|
||||||
|
GC-UI/frontend/test/shots/
|
||||||
|
|
||||||
|
# GC.Tests 离屏渲染输出(dotnet run ... GC.Tests 默认写到仓库根 screenshots/)
|
||||||
|
screenshots/
|
||||||
|
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
# 2026-11-14
|
||||||
|
|
||||||
|
## GC 启动器安全加固(补完)
|
||||||
|
|
||||||
|
- **GC-SAVEDOG 裁剪发布**:`PublishTrimmed=true` + `TrimMode=full` +
|
||||||
|
`JsonSerializerIsReflectionEnabledByDefault=false`(已写进 csproj 与两套构建脚本)。
|
||||||
|
体积 70MB → 14MB。裁剪后反射式 JSON 会失效,因此新增
|
||||||
|
`GC-SAVEDOG/SavedogJson.cs`(`JsonSerializerContext` 源生成)并通过
|
||||||
|
`Json.TypeInfoProvider` 钩子接进共享的 `GC.Download/GC.Services.Json`。
|
||||||
|
→ 新增 JSON 类型必须登记到 `SavedogJsonContext`,否则只有发布产物会炸。
|
||||||
|
- **构建产物布局改为 `dist/<系统>-<架构>/`**(mac-arm64 / win-amd64 / win-arm64),
|
||||||
|
更新包路径 `dist/<平台>/GC-<版本>-<平台>.zip`;`pack_launcher` 之后调
|
||||||
|
`VersionStamp --launcher-only` 把 `path/dir/name/sha256/size` 写进清单并重新签名。
|
||||||
|
原始 `.app`/`.exe` 移到 `build/trash/`(避免递归删除几百个文件)。
|
||||||
|
- **启动器更新支持「只发产物、不发 Release」**:新增 `GC-DOWNLOAD/LauncherArtifacts.cs`
|
||||||
|
(平台标签/别名、候选目录与文件名推导,构建端 VersionStamp 也链接同一份)。
|
||||||
|
`GitCodeRemote/GiteaRemote/DirectoryRemote.DownloadPackageAsync` 改成
|
||||||
|
多候选尝试:url → 清单 path → `dist/<系统>-<架构>/` 目录扫描 → dist 根目录命名,
|
||||||
|
每个候选都必须匹配已签名清单的 sha256。
|
||||||
|
`GitCodeReleaseRemote` 在「没有 Release」时不再清空 launcher 字段(清单已签名)。
|
||||||
|
- **测试**:`--update-test` 新增两条用例(dist 目录能找到并下载 / dist 目录里哈希不符被拒绝),
|
||||||
|
当前 33 项全部通过。
|
||||||
|
- 触发过的坑:`rm -rf` 大批文件被沙箱批量删除保护拦截 → 构建脚本改用 `mv` 到 `build/trash`。
|
||||||
|
- **收尾验证(19:35–19:37)**:`./build.sh pack-launcher` 24s 完成三平台打包,
|
||||||
|
清单已写入真实 `sha256/size`(win-amd64 44MB / win-arm64 42MB / mac-arm64 8.7MB,
|
||||||
|
osx-x64 与 linux-amd64 无产物故留空,下载端会跳过)。根 `version.json` 与
|
||||||
|
`model/version.json` 字节一致、签名 `gc-2026-11` 校验 Verified。
|
||||||
|
从 mac 包里解出的 GC-SAVEDOG(14MB 裁剪版)实跑 `verify` / `status` 正常;
|
||||||
|
`./build.sh check` 全流程通过。
|
||||||
@@ -1,8 +1,9 @@
|
|||||||
<Project>
|
<Project>
|
||||||
<!--
|
<!--
|
||||||
多目录结构公共属性:
|
多目录结构公共属性:
|
||||||
src/main/dotnet/<module> 生产代码
|
GC-BOOT 启动入口
|
||||||
src/test/dotnet/<module> 测试 / 离屏渲染校验
|
GC/src/ 启动器核心代码
|
||||||
|
GC/src/test/dotnet/<module> 测试 / 离屏渲染校验
|
||||||
TargetFramework 可由命令行覆盖:dotnet build -p:TargetFramework=net10.0
|
TargetFramework 可由命令行覆盖:dotnet build -p:TargetFramework=net10.0
|
||||||
-->
|
-->
|
||||||
<PropertyGroup Condition="'$(TargetFramework)' == ''">
|
<PropertyGroup Condition="'$(TargetFramework)' == ''">
|
||||||
@@ -21,9 +22,9 @@
|
|||||||
-->
|
-->
|
||||||
<AvaloniaVersion>11.3.9</AvaloniaVersion>
|
<AvaloniaVersion>11.3.9</AvaloniaVersion>
|
||||||
<MvvmVersion>8.2.2</MvvmVersion>
|
<MvvmVersion>8.2.2</MvvmVersion>
|
||||||
<Version>1.0.6</Version>
|
<Version>1.1.0</Version>
|
||||||
<Company>NeoRF</Company>
|
<Company>Morris</Company>
|
||||||
<Product>Earth Model Studio</Product>
|
<Product>GC</Product>
|
||||||
<NeutralLanguage>zh-Hans</NeutralLanguage>
|
<NeutralLanguage>zh-Hans</NeutralLanguage>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
</Project>
|
</Project>
|
||||||
@@ -0,0 +1,187 @@
|
|||||||
|
using System;
|
||||||
|
using System.Diagnostics;
|
||||||
|
using System.IO;
|
||||||
|
using System.Net.Http;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using GC.UI.Server;
|
||||||
|
using Microsoft.AspNetCore.Builder;
|
||||||
|
|
||||||
|
namespace GC;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 新界面启动壳。
|
||||||
|
///
|
||||||
|
/// 发布包带 <c>GC-UI</c>(Flutter 前端)时,启动器只做三件事:
|
||||||
|
/// 1. 在自己的进程里起后端(本地 HTTP API + 模型窗口宿主),等 <c>/api/health</c> 就绪;
|
||||||
|
/// 2. 拉起 Flutter 窗口;
|
||||||
|
/// 3. 界面退出后关掉后端。
|
||||||
|
///
|
||||||
|
/// 后端跑在进程内而不是单独一个 exe:两者用的是同一套 .NET 运行时,
|
||||||
|
/// 拆成两个自包含进程等于把 60MB 运行时复制两份,发布包会白白大一倍。
|
||||||
|
///
|
||||||
|
/// 缺 Flutter 前端时返回 <c>false</c>,由调用方回退到内置 Avalonia 界面——
|
||||||
|
/// 这样 `dotnet run`、只编了启动器的开发场景都能正常打开。
|
||||||
|
/// </summary>
|
||||||
|
internal static class FlutterShell
|
||||||
|
{
|
||||||
|
/// <summary>与前端、后端共用的默认端口(定义在 GC.Services.GcUiContract)。</summary>
|
||||||
|
private const int Port = Services.GcUiContract.DefaultPort;
|
||||||
|
|
||||||
|
private static readonly HttpClient Http = new() { Timeout = TimeSpan.FromSeconds(1.5) };
|
||||||
|
|
||||||
|
private static WebApplication? _backend;
|
||||||
|
|
||||||
|
public static bool TryRun(string[] args)
|
||||||
|
{
|
||||||
|
var dir = AppContext.BaseDirectory;
|
||||||
|
var uiPath = FindUi(dir);
|
||||||
|
if (uiPath == null) return false;
|
||||||
|
|
||||||
|
var port = Port;
|
||||||
|
|
||||||
|
// 用户可能重复启动:已有后端在跑就直接复用,退出时也不要关掉别人的进程。
|
||||||
|
if (!IsHealthy(port))
|
||||||
|
{
|
||||||
|
// 端口可能被别的程序占用:17890 起向后试几个,选第一个能起来且健康的。
|
||||||
|
var start = Environment.GetEnvironmentVariable(Services.GcUiContract.PortEnvVar) is { Length: > 0 }
|
||||||
|
? Services.GcUiContract.PortFromEnvironment()
|
||||||
|
: Port;
|
||||||
|
|
||||||
|
for (var candidate = start; candidate < start + Services.GcUiContract.PortScanRange; candidate++)
|
||||||
|
{
|
||||||
|
var app = TryStartBackend(args, candidate);
|
||||||
|
if (app == null) continue;
|
||||||
|
|
||||||
|
if (WaitHealthy(candidate, TimeSpan.FromSeconds(25)))
|
||||||
|
{
|
||||||
|
port = candidate;
|
||||||
|
_backend = app;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
StopBackend(app);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_backend == null) return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
AppDomain.CurrentDomain.ProcessExit += (_, _) => StopBackend(_backend);
|
||||||
|
|
||||||
|
var ui = Start(uiPath, dir, port);
|
||||||
|
if (ui == null)
|
||||||
|
{
|
||||||
|
StopBackend(_backend);
|
||||||
|
_backend = null;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
ui.WaitForExit();
|
||||||
|
StopBackend(_backend);
|
||||||
|
_backend = null;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- 产物定位
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Flutter 桌面产物。
|
||||||
|
/// macOS 是 <c>GC-UI.app/Contents/MacOS/GC-UI</c>;Windows 是 <c>GC-UI.exe</c>;
|
||||||
|
/// Linux 是 <c>GC-UI</c>。
|
||||||
|
/// </summary>
|
||||||
|
private static string? FindUi(string dir)
|
||||||
|
{
|
||||||
|
if (OperatingSystem.IsMacOS())
|
||||||
|
{
|
||||||
|
var exe = Path.Combine(dir, "GC-UI.app", "Contents", "MacOS", "GC-UI");
|
||||||
|
if (File.Exists(exe)) return exe;
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var name in OperatingSystem.IsWindows() ? new[] { "GC-UI.exe" } : new[] { "GC-UI" })
|
||||||
|
{
|
||||||
|
var path = Path.Combine(dir, name);
|
||||||
|
if (File.Exists(path)) return path;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- 进程管理
|
||||||
|
|
||||||
|
/// <summary>在本进程内启动后端;端口被占用等失败情况返回 null。</summary>
|
||||||
|
private static WebApplication? TryStartBackend(string[] args, int port)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var app = BackendServer.Start(args, port);
|
||||||
|
app.StartAsync().GetAwaiter().GetResult();
|
||||||
|
return app;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Console.Error.WriteLine($"[shell] 后端启动失败(端口 {port}): {ex.Message}");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void StopBackend(WebApplication? app)
|
||||||
|
{
|
||||||
|
if (app == null) return;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(3));
|
||||||
|
app.StopAsync(cts.Token).GetAwaiter().GetResult();
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Console.Error.WriteLine($"[shell] 关闭后端失败: {ex.Message}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Process Start(string fileName, string workingDirectory, int port)
|
||||||
|
{
|
||||||
|
var info = new ProcessStartInfo(fileName)
|
||||||
|
{
|
||||||
|
WorkingDirectory = workingDirectory,
|
||||||
|
UseShellExecute = false,
|
||||||
|
};
|
||||||
|
|
||||||
|
// 把实际端口传给前端:它读这个环境变量拼 baseUrl,换端口不需要重新编译界面。
|
||||||
|
info.Environment[Services.GcUiContract.PortEnvVar] = port.ToString();
|
||||||
|
|
||||||
|
// macOS .app 内的二进制也需要可执行位;发布包由 zip 解开时可能丢失。
|
||||||
|
if (!OperatingSystem.IsWindows())
|
||||||
|
{
|
||||||
|
try { File.SetUnixFileMode(fileName, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); }
|
||||||
|
catch { /* 权限不足时交给系统判断 */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
return Process.Start(info)!;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- 健康检查
|
||||||
|
|
||||||
|
private static bool IsHealthy(int port)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var response = Http.GetAsync($"http://127.0.0.1:{port}/api/health")
|
||||||
|
.GetAwaiter().GetResult();
|
||||||
|
return response.IsSuccessStatusCode;
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool WaitHealthy(int port, TimeSpan timeout)
|
||||||
|
{
|
||||||
|
var deadline = DateTime.UtcNow + timeout;
|
||||||
|
while (DateTime.UtcNow < deadline)
|
||||||
|
{
|
||||||
|
if (IsHealthy(port)) return true;
|
||||||
|
Thread.Sleep(250);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<OutputType>WinExe</OutputType>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||||
|
<RootNamespace>GC.Boot</RootNamespace>
|
||||||
|
<AssemblyName>GC</AssemblyName>
|
||||||
|
<ApplicationManifest>app.manifest</ApplicationManifest>
|
||||||
|
<!-- 应用图标(Windows exe / 任务栏) -->
|
||||||
|
<ApplicationIcon>..\GC\src\Assets\icon.ico</ApplicationIcon>
|
||||||
|
<BuiltInComInteropSupport>true</BuiltInComInteropSupport>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
|
||||||
|
<PackageReference Include="Avalonia.Desktop" Version="$(AvaloniaVersion)" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<!-- 后端以库的方式编进启动器:发布包只需要一个 exe,不用再带一份运行时 -->
|
||||||
|
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\GC\src\GC.Core.csproj" />
|
||||||
|
<ProjectReference Include="..\GC-DOWNLOAD\GC-DOWNLOAD.csproj" />
|
||||||
|
<ProjectReference Include="..\GC-UI\backend\GC.UI.Server\GC.UI.Server.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -1,20 +1,28 @@
|
|||||||
using System;
|
using System;
|
||||||
using Avalonia;
|
using Avalonia;
|
||||||
using EarthModelStudio.Services;
|
using GC.Services;
|
||||||
|
using GC.Download;
|
||||||
|
|
||||||
namespace EarthModelStudio;
|
namespace GC;
|
||||||
|
|
||||||
internal static class Program
|
internal static class Program
|
||||||
{
|
{
|
||||||
[STAThread]
|
[STAThread]
|
||||||
public static void Main(string[] args)
|
public static void Main(string[] args)
|
||||||
{
|
{
|
||||||
|
DownloadModuleHost.Factory = new DownloadModuleFactory();
|
||||||
// 运行目录:可执行文件旁 .GC/(settings.json + model/ + cache/ + update/)
|
// 运行目录:可执行文件旁 .GC/(settings.json + model/ + cache/ + update/)
|
||||||
var paths = AppPaths.Discover();
|
var paths = AppPaths.Discover();
|
||||||
paths.EnsureCreated();
|
paths.EnsureCreated();
|
||||||
|
|
||||||
|
// 目录约定 + 双语日志 + 把包里的守护进程落到 .GC/safedog
|
||||||
|
RuntimeLayout.Ensure(paths);
|
||||||
|
|
||||||
// 上次下载的启动器新版,到这次启动才应用
|
// 上次下载的启动器新版,到这次启动才应用
|
||||||
if (LauncherUpdater.TryApplyPending(paths)) return;
|
if (DownloadModuleHost.Factory.TryApplyPending(paths)) return;
|
||||||
|
|
||||||
|
// 发布包带 Flutter 前端时,界面交给它;没带则回退到内置 Avalonia 界面。
|
||||||
|
if (FlutterShell.TryRun(args)) return;
|
||||||
|
|
||||||
BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
|
BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
|
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
|
||||||
<assemblyIdentity version="1.0.0.0" name="EarthModelStudio.Desktop" />
|
<assemblyIdentity version="1.0.0.0" name="GC.Desktop" />
|
||||||
<application xmlns="urn:schemas-microsoft-com:asm.v3">
|
<application xmlns="urn:schemas-microsoft-com:asm.v3">
|
||||||
<windowsSettings>
|
<windowsSettings>
|
||||||
<dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true/pm</dpiAware>
|
<dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true/pm</dpiAware>
|
||||||
@@ -5,7 +5,7 @@ using System.Net.Http;
|
|||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
namespace EarthModelStudio.Services;
|
namespace GC.Services;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 本地目录源:用于离线教学(U 盘 / 共享盘里的仓库副本)与自动化测试。
|
/// 本地目录源:用于离线教学(U 盘 / 共享盘里的仓库副本)与自动化测试。
|
||||||
@@ -15,6 +15,8 @@ public sealed class DirectoryRemote : IModelRemote
|
|||||||
{
|
{
|
||||||
private readonly string _root;
|
private readonly string _root;
|
||||||
private static readonly HttpClient Http = new() { Timeout = TimeSpan.FromMinutes(5) };
|
private static readonly HttpClient Http = new() { Timeout = TimeSpan.FromMinutes(5) };
|
||||||
|
private string? _rawManifest;
|
||||||
|
private string _launcherVersion = "";
|
||||||
|
|
||||||
public DirectoryRemote(string root) => _root = Path.GetFullPath(root);
|
public DirectoryRemote(string root) => _root = Path.GetFullPath(root);
|
||||||
|
|
||||||
@@ -26,9 +28,20 @@ public sealed class DirectoryRemote : IModelRemote
|
|||||||
var fallback = SafePath(Path.Combine("model", "version.json"));
|
var fallback = SafePath(Path.Combine("model", "version.json"));
|
||||||
var file = File.Exists(primary) ? primary : fallback;
|
var file = File.Exists(primary) ? primary : fallback;
|
||||||
if (!File.Exists(file)) return Task.FromResult<RepoVersion?>(null);
|
if (!File.Exists(file)) return Task.FromResult<RepoVersion?>(null);
|
||||||
return Task.FromResult(Json.Read<RepoVersion>(file));
|
|
||||||
|
// 离线目录同样验签:U 盘 / 共享盘里的清单也可能是被替换过的
|
||||||
|
var text = File.ReadAllText(file);
|
||||||
|
_rawManifest = text;
|
||||||
|
var version = ManifestLoader.Parse(text, out _);
|
||||||
|
if (version != null && !string.IsNullOrWhiteSpace(version.Launcher.Version))
|
||||||
|
_launcherVersion = version.Launcher.Version.Trim();
|
||||||
|
return Task.FromResult(version);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>最近一次读到的清单原文(SAVEDOG 二次验签用)。</summary>
|
||||||
|
public Task<string?> GetRawVersionTextAsync(CancellationToken ct)
|
||||||
|
=> Task.FromResult(_rawManifest);
|
||||||
|
|
||||||
public Task<IReadOnlyList<RepoEntry>> ListTreeAsync(string rootPath, CancellationToken ct)
|
public Task<IReadOnlyList<RepoEntry>> ListTreeAsync(string rootPath, CancellationToken ct)
|
||||||
{
|
{
|
||||||
var baseDir = SafePath(rootPath ?? "model");
|
var baseDir = SafePath(rootPath ?? "model");
|
||||||
@@ -76,11 +89,21 @@ public sealed class DirectoryRemote : IModelRemote
|
|||||||
|
|
||||||
public async Task<byte[]?> DownloadPackageAsync(RepoPackage package, CancellationToken ct)
|
public async Task<byte[]?> DownloadPackageAsync(RepoPackage package, CancellationToken ct)
|
||||||
{
|
{
|
||||||
if (!string.IsNullOrWhiteSpace(package.Path))
|
// 清单路径 / dist 根目录命名:按仓库内相对路径直接找
|
||||||
|
foreach (var rel in LauncherArtifacts.CandidateFiles(
|
||||||
|
package.Rid, package.Dir, package.Path, package.Name, _launcherVersion))
|
||||||
{
|
{
|
||||||
var local = SafePath(package.Path!);
|
string full;
|
||||||
if (File.Exists(local)) return await File.ReadAllBytesAsync(local, ct);
|
try { full = SafePath(rel); }
|
||||||
|
catch (InvalidOperationException) { continue; }
|
||||||
|
if (File.Exists(full)) return await File.ReadAllBytesAsync(full, ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// dist/<系统>-<架构>/ 里放着的编译产物(与远端同一套查找规则):
|
||||||
|
// 本地源同样要能跑通「只发产物、不发 Release」的更新方式。
|
||||||
|
var fromDist = FindInDist(package);
|
||||||
|
if (fromDist != null) return await File.ReadAllBytesAsync(fromDist, ct);
|
||||||
|
|
||||||
var url = package.Url;
|
var url = package.Url;
|
||||||
if (string.IsNullOrWhiteSpace(url)) return null;
|
if (string.IsNullOrWhiteSpace(url)) return null;
|
||||||
// 离线 U 盘源与 ./build.sh update-test 都会用本地 zip 路径,必须保持兼容。
|
// 离线 U 盘源与 ./build.sh update-test 都会用本地 zip 路径,必须保持兼容。
|
||||||
@@ -93,6 +116,27 @@ public sealed class DirectoryRemote : IModelRemote
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>在 dist/<系统>-<架构>/ 里找这个平台的启动器包;找不到返回 null。</summary>
|
||||||
|
private string? FindInDist(RepoPackage package)
|
||||||
|
{
|
||||||
|
foreach (var dir in LauncherArtifacts.CandidateDirs(package.Rid, package.Dir))
|
||||||
|
{
|
||||||
|
string full;
|
||||||
|
try { full = SafePath(dir); }
|
||||||
|
catch (InvalidOperationException) { continue; }
|
||||||
|
if (!Directory.Exists(full)) continue;
|
||||||
|
|
||||||
|
var zips = Directory.GetFiles(full, "*.zip");
|
||||||
|
if (zips.Length == 0) continue;
|
||||||
|
|
||||||
|
foreach (var zip in zips)
|
||||||
|
if (LauncherArtifacts.LooksLikePackage(Path.GetFileName(zip), _launcherVersion, package.Rid))
|
||||||
|
return zip;
|
||||||
|
if (zips.Length == 1) return zips[0];
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
private string SafePath(string relative)
|
private string SafePath(string relative)
|
||||||
{
|
{
|
||||||
var full = Path.GetFullPath(Path.Combine(_root, relative));
|
var full = Path.GetFullPath(Path.Combine(_root, relative));
|
||||||
@@ -5,21 +5,12 @@ using System.Linq;
|
|||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using CommunityToolkit.Mvvm.ComponentModel;
|
using CommunityToolkit.Mvvm.ComponentModel;
|
||||||
using EarthModelStudio.Models;
|
using GC.Models;
|
||||||
|
|
||||||
namespace EarthModelStudio.Services;
|
namespace GC.Services;
|
||||||
|
|
||||||
public enum DownloadState
|
|
||||||
{
|
|
||||||
Queued,
|
|
||||||
Running,
|
|
||||||
Completed,
|
|
||||||
Failed,
|
|
||||||
Canceled
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>一条下载任务(进入后台列表后一直保留,直到用户清除)。</summary>
|
/// <summary>一条下载任务(进入后台列表后一直保留,直到用户清除)。</summary>
|
||||||
public sealed partial class DownloadJob : ObservableObject
|
public sealed partial class DownloadJob : ObservableObject, IDownloadJob
|
||||||
{
|
{
|
||||||
public RemoteModel Model { get; }
|
public RemoteModel Model { get; }
|
||||||
public string Id => Model.Id;
|
public string Id => Model.Id;
|
||||||
@@ -65,14 +56,16 @@ public sealed partial class DownloadJob : ObservableObject
|
|||||||
partial void OnErrorChanged(string? value) => RefreshText();
|
partial void OnErrorChanged(string? value) => RefreshText();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>下载中心:最多 2 个并发,任务在「后台列表」里折叠展示。</summary>
|
/// <summary>下载中心:最多 4 个并发,任务在「后台列表」里折叠展示。</summary>
|
||||||
public sealed class DownloadCenter
|
public sealed class DownloadCenter : IDownloadCenter
|
||||||
{
|
{
|
||||||
private readonly ModelRepository _repository;
|
private readonly ModelRepository _repository;
|
||||||
private readonly AppPaths _paths;
|
private readonly AppPaths _paths;
|
||||||
private readonly SemaphoreSlim _slots = new(2);
|
// 断点续传后单任务失败重来的代价小了很多,可以适当提高并发;
|
||||||
|
// 更新服务那边已是 6,模型下载保持 4,兼顾弱网吞吐与源站压力。
|
||||||
|
private readonly SemaphoreSlim _slots = new(4);
|
||||||
|
|
||||||
public ObservableCollection<DownloadJob> Jobs { get; } = new();
|
public ObservableCollection<IDownloadJob> Jobs { get; } = new();
|
||||||
public event Action? Installed;
|
public event Action? Installed;
|
||||||
|
|
||||||
public DownloadCenter(AppPaths paths, ModelRepository repository)
|
public DownloadCenter(AppPaths paths, ModelRepository repository)
|
||||||
@@ -81,7 +74,7 @@ public sealed class DownloadCenter
|
|||||||
_repository = repository;
|
_repository = repository;
|
||||||
}
|
}
|
||||||
|
|
||||||
public DownloadJob Enqueue(RemoteModel model)
|
public IDownloadJob Enqueue(RemoteModel model)
|
||||||
{
|
{
|
||||||
var running = Jobs.FirstOrDefault(j => j.Id.Equals(model.Id, StringComparison.OrdinalIgnoreCase) && j.IsActive);
|
var running = Jobs.FirstOrDefault(j => j.Id.Equals(model.Id, StringComparison.OrdinalIgnoreCase) && j.IsActive);
|
||||||
if (running != null) return running;
|
if (running != null) return running;
|
||||||
@@ -92,7 +85,7 @@ public sealed class DownloadCenter
|
|||||||
return job;
|
return job;
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task RunAsync(DownloadJob job)
|
private async Task RunAsync(IDownloadJob job)
|
||||||
{
|
{
|
||||||
// 在 UI 线程构造,回调自动回到 UI 线程
|
// 在 UI 线程构造,回调自动回到 UI 线程
|
||||||
var progress = new Progress<(long Done, long Total)>(p =>
|
var progress = new Progress<(long Done, long Total)>(p =>
|
||||||
@@ -135,20 +128,20 @@ public sealed class DownloadCenter
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void Cancel(DownloadJob job)
|
public void Cancel(IDownloadJob job)
|
||||||
{
|
{
|
||||||
try { job.Cts.Cancel(); } catch { }
|
try { job.Cts.Cancel(); } catch { }
|
||||||
if (job.State == DownloadState.Queued) job.State = DownloadState.Canceled;
|
if (job.State == DownloadState.Queued) job.State = DownloadState.Canceled;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void Retry(DownloadJob job)
|
public void Retry(IDownloadJob job)
|
||||||
{
|
{
|
||||||
if (job.IsActive) return;
|
if (job.IsActive) return;
|
||||||
Jobs.Remove(job);
|
Jobs.Remove(job);
|
||||||
Enqueue(job.Model);
|
Enqueue(job.Model);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void Remove(DownloadJob job)
|
public void Remove(IDownloadJob job)
|
||||||
{
|
{
|
||||||
Cancel(job);
|
Cancel(job);
|
||||||
Jobs.Remove(job);
|
Jobs.Remove(job);
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
using System;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using GC.Models;
|
||||||
|
using GC.Services;
|
||||||
|
|
||||||
|
namespace GC.Download;
|
||||||
|
|
||||||
|
public sealed class DownloadModuleFactory : IDownloadModuleFactory
|
||||||
|
{
|
||||||
|
public IDownloadModule Create(AppPaths paths, SettingsService settings, ModelRepository models) =>
|
||||||
|
new DownloadModule(paths, settings, models);
|
||||||
|
|
||||||
|
public bool TryApplyPending(AppPaths paths) => LauncherUpdater.TryApplyPending(paths);
|
||||||
|
}
|
||||||
|
|
||||||
|
internal sealed class DownloadModule : IDownloadModule
|
||||||
|
{
|
||||||
|
public IDownloadCenter Downloads { get; }
|
||||||
|
public IModelSourceClient Sources { get; }
|
||||||
|
public IUpdateService Updates { get; }
|
||||||
|
public ISourceSelector Selector { get; }
|
||||||
|
public ILauncherUpdateService LauncherUpdates { get; }
|
||||||
|
|
||||||
|
public DownloadModule(AppPaths paths, SettingsService settings, ModelRepository models)
|
||||||
|
{
|
||||||
|
Sources = new ModelSourceClient(paths);
|
||||||
|
Downloads = new DownloadCenter(paths, models);
|
||||||
|
Selector = new SourceSelector();
|
||||||
|
Updates = new UpdateService(paths, settings, UpdateService.CreateRemote(settings.Current));
|
||||||
|
LauncherUpdates = new LauncherUpdateService();
|
||||||
|
}
|
||||||
|
|
||||||
|
public IModelRemote CreateRemote(SourcePreset preset) => SourceSelector.CreateRemote(preset);
|
||||||
|
}
|
||||||
|
|
||||||
|
internal sealed class LauncherUpdateService : ILauncherUpdateService
|
||||||
|
{
|
||||||
|
public Task<string?> CheckAsync(IModelRemote remote, CancellationToken ct = default) =>
|
||||||
|
LauncherUpdater.CheckAsync(remote, ct);
|
||||||
|
|
||||||
|
public Task<UpdateRunResult> DownloadAsync(AppPaths paths, IModelRemote remote,
|
||||||
|
IProgress<UpdateProgressInfo>? progress = null, CancellationToken ct = default) =>
|
||||||
|
LauncherUpdater.DownloadAsync(paths, remote, progress, ct);
|
||||||
|
|
||||||
|
public bool ScheduleApply(AppPaths paths, string packageName) =>
|
||||||
|
LauncherUpdater.ScheduleApply(paths, packageName);
|
||||||
|
|
||||||
|
public bool TryApplyPending(AppPaths paths) => LauncherUpdater.TryApplyPending(paths);
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<RootNamespace>GC.Download</RootNamespace>
|
||||||
|
<AssemblyName>GC.Download</AssemblyName>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="CommunityToolkit.Mvvm" Version="$(MvvmVersion)" />
|
||||||
|
<ProjectReference Include="..\GC\src\GC.Core.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -5,7 +5,7 @@ using System.Text.Json;
|
|||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
namespace EarthModelStudio.Services;
|
namespace GC.Services;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 启动器更新走 GitCode Release,模型仍走仓库 contents API 的远端源。
|
/// 启动器更新走 GitCode Release,模型仍走仓库 contents API 的远端源。
|
||||||
@@ -32,7 +32,7 @@ public sealed class GitCodeReleaseRemote : IModelRemote
|
|||||||
private static HttpClient CreateHttp()
|
private static HttpClient CreateHttp()
|
||||||
{
|
{
|
||||||
var client = new HttpClient { Timeout = TimeSpan.FromSeconds(15) };
|
var client = new HttpClient { Timeout = TimeSpan.FromSeconds(15) };
|
||||||
client.DefaultRequestHeaders.UserAgent.ParseAdd("EarthModelStudio-Updater/1.0");
|
client.DefaultRequestHeaders.UserAgent.ParseAdd("GC-Updater/1.0");
|
||||||
client.DefaultRequestHeaders.Accept.ParseAdd("application/json");
|
client.DefaultRequestHeaders.Accept.ParseAdd("application/json");
|
||||||
return client;
|
return client;
|
||||||
}
|
}
|
||||||
@@ -50,9 +50,9 @@ public sealed class GitCodeReleaseRemote : IModelRemote
|
|||||||
{
|
{
|
||||||
var raw = string.IsNullOrWhiteSpace(url) ? GitCodeRemote.DefaultRepository : url!.Trim();
|
var raw = string.IsNullOrWhiteSpace(url) ? GitCodeRemote.DefaultRepository : url!.Trim();
|
||||||
if (!Uri.TryCreate(raw, UriKind.Absolute, out var uri))
|
if (!Uri.TryCreate(raw, UriKind.Absolute, out var uri))
|
||||||
return ("2509_92447106", "GC");
|
return ("Morris_1", "GC");
|
||||||
var parts = uri.AbsolutePath.Trim('/').Split('/', StringSplitOptions.RemoveEmptyEntries);
|
var parts = uri.AbsolutePath.Trim('/').Split('/', StringSplitOptions.RemoveEmptyEntries);
|
||||||
if (parts.Length < 2) return ("2509_92447106", "GC");
|
if (parts.Length < 2) return ("Morris_1", "GC");
|
||||||
var repo = parts[1].EndsWith(".git", StringComparison.OrdinalIgnoreCase)
|
var repo = parts[1].EndsWith(".git", StringComparison.OrdinalIgnoreCase)
|
||||||
? parts[1][..^4] : parts[1];
|
? parts[1][..^4] : parts[1];
|
||||||
return (parts[0], repo);
|
return (parts[0], repo);
|
||||||
@@ -86,13 +86,19 @@ public sealed class GitCodeReleaseRemote : IModelRemote
|
|||||||
|
|
||||||
if (!gotRelease)
|
if (!gotRelease)
|
||||||
{
|
{
|
||||||
// 没有 Release:启动器版本留空(表示这个源没有可升级的启动器),
|
// 没有 Release ≠ 不能更新:清单已签名,且每个平台包都写了 sha256,
|
||||||
// 但模型清单仍然有效,保证模型能正常同步。
|
// 走「仓库 dist/<系统>-<架构>/ 里的编译产物」同样可信。
|
||||||
Console.WriteLine($"[gitcode] {DisplayName}: Release 为空(模型清单仍可用)");
|
// 这里保留清单里的 launcher 版本与包信息,让下载端去 dist 目录找包。
|
||||||
if (version != null)
|
var v = (version?.Launcher.Version ?? "").Trim();
|
||||||
|
var n = version?.Launcher.Packages.Count ?? 0;
|
||||||
|
if (v.Length == 0 || n == 0)
|
||||||
{
|
{
|
||||||
version.Launcher.Version = "";
|
Console.WriteLine($"[gitcode] {DisplayName}: 没有 Release,清单里也没有启动器包");
|
||||||
version.Launcher.Packages.Clear();
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
Console.WriteLine(
|
||||||
|
$"[gitcode] {DisplayName}: 没有 Release,改用清单声明的 v{v}({n} 个平台包,去 dist/ 找产物)");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return version;
|
return version;
|
||||||
@@ -120,6 +126,7 @@ public sealed class GitCodeReleaseRemote : IModelRemote
|
|||||||
if (latest == null || string.IsNullOrWhiteSpace(latest.Version)) return false;
|
if (latest == null || string.IsNullOrWhiteSpace(latest.Version)) return false;
|
||||||
|
|
||||||
version.Launcher.Version = latest.Version;
|
version.Launcher.Version = latest.Version;
|
||||||
|
_content.SetLauncherVersion(latest.Version);
|
||||||
|
|
||||||
_assets.Clear();
|
_assets.Clear();
|
||||||
foreach (var asset in latest.Assets)
|
foreach (var asset in latest.Assets)
|
||||||
@@ -2,23 +2,24 @@ using System;
|
|||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Net.Http;
|
using System.Net.Http;
|
||||||
|
using System.Security.Cryptography;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
namespace EarthModelStudio.Services;
|
namespace GC.Services;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// gitcode 仓库源。默认地址来自 AppSettings.UpdateRepository
|
/// gitcode 仓库源。默认地址来自 AppSettings.UpdateRepository
|
||||||
/// (https://gitcode.com/2509_92447106/GC),可改成任意 gitcode 仓库或
|
/// (https://gitcode.com/Morris_1/GC),可改成任意 gitcode 仓库或
|
||||||
/// https://gitcode.com/<owner>/<repo>/tree/<branch>/model 这样的地址。
|
/// https://gitcode.com/<owner>/<repo>/tree/<branch>/model 这样的地址。
|
||||||
/// 匿名访问 v5 contents API:目录 -> 数组,文件 -> { content: base64 };
|
/// 匿名访问 v5 contents API:目录 -> 数组,文件 -> { content: base64 };
|
||||||
/// 文件项自带 download_url(raw.gitcode.com/blobs/<sha>/...),可直接下载二进制。
|
/// 文件项自带 download_url(raw.gitcode.com/blobs/<sha>/...),可直接下载二进制。
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public sealed class GitCodeRemote : IModelRemote
|
public sealed class GitCodeRemote : IModelRemote
|
||||||
{
|
{
|
||||||
public const string DefaultRepository = "https://gitcode.com/2509_92447106/GC";
|
public const string DefaultRepository = "https://gitcode.com/Morris_1/GC";
|
||||||
|
|
||||||
private readonly HttpClient _http;
|
private readonly HttpClient _http;
|
||||||
private readonly string _api;
|
private readonly string _api;
|
||||||
@@ -27,6 +28,9 @@ public sealed class GitCodeRemote : IModelRemote
|
|||||||
private readonly string? _fallbackUrl;
|
private readonly string? _fallbackUrl;
|
||||||
private readonly string _displayName;
|
private readonly string _displayName;
|
||||||
private string _modelDir = "model";
|
private string _modelDir = "model";
|
||||||
|
private string? _rawManifest;
|
||||||
|
/// <summary>最近一次读到的启动器版本号,用于推导 dist 目录里的包名。</summary>
|
||||||
|
private string _launcherVersion = "";
|
||||||
|
|
||||||
public string DisplayName => _displayName;
|
public string DisplayName => _displayName;
|
||||||
|
|
||||||
@@ -39,7 +43,7 @@ public sealed class GitCodeRemote : IModelRemote
|
|||||||
? DefaultRepository : repository!.TrimEnd('/');
|
? DefaultRepository : repository!.TrimEnd('/');
|
||||||
|
|
||||||
_http = new HttpClient { Timeout = TimeSpan.FromMinutes(2) };
|
_http = new HttpClient { Timeout = TimeSpan.FromMinutes(2) };
|
||||||
_http.DefaultRequestHeaders.UserAgent.ParseAdd("EarthModelStudio-Updater/1.0");
|
_http.DefaultRequestHeaders.UserAgent.ParseAdd("GC-Updater/1.0");
|
||||||
_http.DefaultRequestHeaders.Accept.ParseAdd("application/json");
|
_http.DefaultRequestHeaders.Accept.ParseAdd("application/json");
|
||||||
|
|
||||||
if (string.IsNullOrWhiteSpace(manifestUrl))
|
if (string.IsNullOrWhiteSpace(manifestUrl))
|
||||||
@@ -59,9 +63,9 @@ public sealed class GitCodeRemote : IModelRemote
|
|||||||
{
|
{
|
||||||
var raw = string.IsNullOrWhiteSpace(url) ? DefaultRepository : url!.Trim();
|
var raw = string.IsNullOrWhiteSpace(url) ? DefaultRepository : url!.Trim();
|
||||||
if (!Uri.TryCreate(raw, UriKind.Absolute, out var uri))
|
if (!Uri.TryCreate(raw, UriKind.Absolute, out var uri))
|
||||||
return ("2509_92447106", "GC", "main");
|
return ("Morris_1", "GC", "main");
|
||||||
var parts = uri.AbsolutePath.Trim('/').Split('/', StringSplitOptions.RemoveEmptyEntries);
|
var parts = uri.AbsolutePath.Trim('/').Split('/', StringSplitOptions.RemoveEmptyEntries);
|
||||||
if (parts.Length < 2) return ("2509_92447106", "GC", "main");
|
if (parts.Length < 2) return ("Morris_1", "GC", "main");
|
||||||
var owner = parts[0];
|
var owner = parts[0];
|
||||||
var repo = parts[1].EndsWith(".git", StringComparison.OrdinalIgnoreCase)
|
var repo = parts[1].EndsWith(".git", StringComparison.OrdinalIgnoreCase)
|
||||||
? parts[1][..^4] : parts[1];
|
? parts[1][..^4] : parts[1];
|
||||||
@@ -77,9 +81,24 @@ public sealed class GitCodeRemote : IModelRemote
|
|||||||
version = await ReadVersionFromAsync(_fallbackUrl, ct);
|
version = await ReadVersionFromAsync(_fallbackUrl, ct);
|
||||||
if (version != null && !string.IsNullOrWhiteSpace(version.ModelDir))
|
if (version != null && !string.IsNullOrWhiteSpace(version.ModelDir))
|
||||||
_modelDir = version.ModelDir.Trim('/');
|
_modelDir = version.ModelDir.Trim('/');
|
||||||
|
if (version != null && !string.IsNullOrWhiteSpace(version.Launcher.Version))
|
||||||
|
_launcherVersion = version.Launcher.Version.Trim();
|
||||||
return version;
|
return version;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>最近一次读到的清单原文(SAVEDOG 二次验签用)。</summary>
|
||||||
|
public Task<string?> GetRawVersionTextAsync(CancellationToken ct)
|
||||||
|
=> Task.FromResult(_rawManifest);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 由 Release 覆盖版本号后同步一次,保证 dist 目录里的包名推导用的是
|
||||||
|
/// 「真正要装的那个版本」,而不是仓库清单里可能滞后的版本号。
|
||||||
|
/// </summary>
|
||||||
|
internal void SetLauncherVersion(string? version)
|
||||||
|
{
|
||||||
|
if (!string.IsNullOrWhiteSpace(version)) _launcherVersion = version!.Trim();
|
||||||
|
}
|
||||||
|
|
||||||
private async Task<RepoVersion?> ReadVersionFromAsync(string url, CancellationToken ct)
|
private async Task<RepoVersion?> ReadVersionFromAsync(string url, CancellationToken ct)
|
||||||
{
|
{
|
||||||
string text;
|
string text;
|
||||||
@@ -107,10 +126,20 @@ public sealed class GitCodeRemote : IModelRemote
|
|||||||
payload = Encoding.UTF8.GetString(raw);
|
payload = Encoding.UTF8.GetString(raw);
|
||||||
}
|
}
|
||||||
if (!payload.TrimStart().StartsWith("{", StringComparison.Ordinal)) return null;
|
if (!payload.TrimStart().StartsWith("{", StringComparison.Ordinal)) return null;
|
||||||
var version = System.Text.Json.JsonSerializer.Deserialize<RepoVersion>(
|
|
||||||
payload, EarthModelStudio.Services.Json.Options);
|
// 验签与解析一起做:拿到的清单必须能说明「它是不是可信的」
|
||||||
|
var version = ManifestLoader.Parse(payload, out var verification);
|
||||||
|
if (version == null) return null;
|
||||||
|
|
||||||
// 404 / 错误页也可能返回一个 JSON 对象,用 generated 确认这确实是版本清单
|
// 404 / 错误页也可能返回一个 JSON 对象,用 generated 确认这确实是版本清单
|
||||||
return version != null && !string.IsNullOrWhiteSpace(version.Generated) ? version : null;
|
if (string.IsNullOrWhiteSpace(version.Generated)) return null;
|
||||||
|
|
||||||
|
if (verification.Trust == ManifestTrust.Invalid)
|
||||||
|
Console.Error.WriteLine($"[gitcode] 清单验签失败: {verification.Error}");
|
||||||
|
|
||||||
|
if (version != null && !string.IsNullOrWhiteSpace(version.Generated))
|
||||||
|
_rawManifest = payload;
|
||||||
|
return version;
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
@@ -283,25 +312,129 @@ public sealed class GitCodeRemote : IModelRemote
|
|||||||
|
|
||||||
public async Task<byte[]?> DownloadPackageAsync(RepoPackage package, CancellationToken ct)
|
public async Task<byte[]?> DownloadPackageAsync(RepoPackage package, CancellationToken ct)
|
||||||
{
|
{
|
||||||
string? url = string.IsNullOrWhiteSpace(package.Url) ? null : package.Url!.Trim();
|
// 先试清单直给的 url(Release 附件):命中的情况下不多发任何一次 API 请求。
|
||||||
if (url == null && !string.IsNullOrWhiteSpace(package.Path))
|
var direct = await TryFetchAsync(package.Url, package.Sha256, ct);
|
||||||
|
if (direct != null) return direct;
|
||||||
|
|
||||||
|
// url 不可用或校验不符:再去找仓库里的编译产物。
|
||||||
|
// 顺序:清单 path → dist/<系统>-<架构>/ 里的 zip → dist 根目录命名。
|
||||||
|
// 每个候选都要和已签名清单的 sha256 对一遍,对不上就换下一个,
|
||||||
|
// 因此「多来源」不放宽校验,只是让「不发 Release 也能更新」成立。
|
||||||
|
foreach (var path in LauncherArtifacts.CandidateFiles(
|
||||||
|
package.Rid, package.Dir, package.Path, package.Name, _launcherVersion))
|
||||||
{
|
{
|
||||||
try
|
var url = await ResolveFileUrlAsync(path, ct);
|
||||||
{
|
var bytes = await TryFetchAsync(url, package.Sha256, ct);
|
||||||
var apiUrl = _api + package.Path!.Trim('/') + "?ref=" + _branch;
|
if (bytes != null) return bytes;
|
||||||
var text = await _http.GetStringAsync(apiUrl, ct);
|
|
||||||
using var doc = JsonDocument.Parse(text);
|
|
||||||
if (doc.RootElement.TryGetProperty("download_url", out var dl))
|
|
||||||
url = dl.GetString();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
foreach (var dir in LauncherArtifacts.CandidateDirs(package.Rid, package.Dir))
|
||||||
|
{
|
||||||
|
var url = await FindZipInDirAsync(dir, package, ct);
|
||||||
|
var bytes = await TryFetchAsync(url, package.Sha256, ct);
|
||||||
|
if (bytes != null) return bytes;
|
||||||
|
}
|
||||||
|
|
||||||
|
Console.Error.WriteLine("[gitcode] 找不到可用的启动器包(Release 附件与 dist 目录都没对上)");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>下载一个候选地址;<paramref name="sha256"/> 非空时必须与内容一致。</summary>
|
||||||
|
private async Task<byte[]?> TryFetchAsync(string? url, string? sha256, CancellationToken ct)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(url)) return null;
|
||||||
|
|
||||||
|
byte[] bytes;
|
||||||
|
try { bytes = await _http.GetByteArrayAsync(url!, ct); }
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
Console.Error.WriteLine($"解析启动器包地址失败: {ex.Message}");
|
Console.Error.WriteLine($"[gitcode] 下载失败 {Short(url!)}: {ex.Message}");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (bytes.Length == 0) return null;
|
||||||
|
|
||||||
|
if (!string.IsNullOrWhiteSpace(sha256))
|
||||||
|
{
|
||||||
|
var actual = Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant();
|
||||||
|
if (!string.Equals(actual, sha256.Trim(), StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
Console.Error.WriteLine($"[gitcode] 包校验不符,换下一个来源: {Short(url!)}");
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (string.IsNullOrWhiteSpace(url)) return null;
|
|
||||||
return await _http.GetByteArrayAsync(url!, ct);
|
Console.WriteLine($"[gitcode] 启动器包来源: {Short(url!)}");
|
||||||
|
return bytes;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Short(string url)
|
||||||
|
=> url.Length <= 96 ? url : url[..60] + "…" + url[^24..];
|
||||||
|
|
||||||
|
/// <summary>把仓库内路径解析成直链;路径不存在或其实是目录时返回 null。</summary>
|
||||||
|
private async Task<string?> ResolveFileUrlAsync(string path, CancellationToken ct)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var url = _api + path.Trim('/') + "?ref=" + _branch;
|
||||||
|
var text = await _http.GetStringAsync(url, ct);
|
||||||
|
if (!text.TrimStart().StartsWith("{", StringComparison.Ordinal)) return null;
|
||||||
|
|
||||||
|
using var doc = JsonDocument.Parse(text);
|
||||||
|
if (doc.RootElement.TryGetProperty("type", out var type) &&
|
||||||
|
string.Equals(type.GetString(), "dir", StringComparison.OrdinalIgnoreCase))
|
||||||
|
return null;
|
||||||
|
return doc.RootElement.TryGetProperty("download_url", out var dl)
|
||||||
|
? dl.GetString() : null;
|
||||||
|
}
|
||||||
|
catch (Exception)
|
||||||
|
{
|
||||||
|
return null; // 404 / 网络问题都当作「这个路径没有」
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 在 <paramref name="dir"/> 里找启动器包。
|
||||||
|
/// 先按「版本 + 平台」精确筛,其次接受目录里唯一的 zip(发布者可能改了命名规则),
|
||||||
|
/// 最终仍由 sha256 兜底。
|
||||||
|
/// </summary>
|
||||||
|
private async Task<string?> FindZipInDirAsync(string dir, RepoPackage package, CancellationToken ct)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var url = _api + dir.Trim('/') + "?ref=" + _branch;
|
||||||
|
var text = await _http.GetStringAsync(url, ct);
|
||||||
|
if (!text.TrimStart().StartsWith("[", StringComparison.Ordinal)) return null;
|
||||||
|
|
||||||
|
var zips = new List<(string Path, string Name)>();
|
||||||
|
using (var doc = JsonDocument.Parse(text))
|
||||||
|
{
|
||||||
|
foreach (var item in doc.RootElement.EnumerateArray())
|
||||||
|
{
|
||||||
|
if (Str(item, "type") != "file") continue;
|
||||||
|
var name = Str(item, "name");
|
||||||
|
if (!name.EndsWith(".zip", StringComparison.OrdinalIgnoreCase)) continue;
|
||||||
|
var path = Str(item, "path");
|
||||||
|
zips.Add((path.Length > 0 ? path : dir + "/" + name, name));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (zips.Count == 0) return null;
|
||||||
|
|
||||||
|
var version = _launcherVersion;
|
||||||
|
var match = zips.FindIndex(z =>
|
||||||
|
LauncherArtifacts.LooksLikePackage(z.Name, version, package.Rid));
|
||||||
|
if (match < 0)
|
||||||
|
{
|
||||||
|
if (zips.Count != 1) return null;
|
||||||
|
match = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
Console.WriteLine($"[gitcode] 在 {dir} 找到编译产物: {zips[match].Name}");
|
||||||
|
return await ResolveFileUrlAsync(zips[match].Path, ct);
|
||||||
|
}
|
||||||
|
catch (Exception)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static string Str(JsonElement item, string name)
|
private static string Str(JsonElement item, string name)
|
||||||
@@ -6,7 +6,7 @@ using System.Text.Json;
|
|||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
namespace EarthModelStudio.Services;
|
namespace GC.Services;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gitea / Forgejo 后端(Xhmcl 用的就是这个)。
|
/// Gitea / Forgejo 后端(Xhmcl 用的就是这个)。
|
||||||
@@ -23,11 +23,12 @@ public sealed class GiteaRemote : IModelRemote
|
|||||||
{
|
{
|
||||||
private readonly SourcePreset _preset;
|
private readonly SourcePreset _preset;
|
||||||
private static readonly HttpClient Http = CreateHttp();
|
private static readonly HttpClient Http = CreateHttp();
|
||||||
|
private string? _rawManifest;
|
||||||
|
|
||||||
private static HttpClient CreateHttp()
|
private static HttpClient CreateHttp()
|
||||||
{
|
{
|
||||||
var c = new HttpClient { Timeout = TimeSpan.FromSeconds(20) };
|
var c = new HttpClient { Timeout = TimeSpan.FromSeconds(20) };
|
||||||
c.DefaultRequestHeaders.UserAgent.ParseAdd("EarthModelStudio-Updater/1.0");
|
c.DefaultRequestHeaders.UserAgent.ParseAdd("GC-Updater/1.0");
|
||||||
c.DefaultRequestHeaders.Accept.ParseAdd("application/json");
|
c.DefaultRequestHeaders.Accept.ParseAdd("application/json");
|
||||||
return c;
|
return c;
|
||||||
}
|
}
|
||||||
@@ -69,7 +70,18 @@ public sealed class GiteaRemote : IModelRemote
|
|||||||
// Release 提供启动器版本与平台附件
|
// Release 提供启动器版本与平台附件
|
||||||
result.Launcher.Version = fromRelease.Launcher.Version;
|
result.Launcher.Version = fromRelease.Launcher.Version;
|
||||||
foreach (var kv in fromRelease.Launcher.Packages)
|
foreach (var kv in fromRelease.Launcher.Packages)
|
||||||
|
{
|
||||||
|
// Release 只能说明"哪个附件",完整性必须回到已签名清单取 sha256,
|
||||||
|
// 否则「有仓库写权限的人发个 Release」就能绕过验签。
|
||||||
|
if (fromRepo != null &&
|
||||||
|
fromRepo.Launcher.Packages.TryGetValue(kv.Key, out var signed) &&
|
||||||
|
!string.IsNullOrWhiteSpace(signed?.Sha256))
|
||||||
|
{
|
||||||
|
kv.Value.Sha256 = signed!.Sha256;
|
||||||
|
if (signed.Size > 0) kv.Value.Size = signed.Size;
|
||||||
|
}
|
||||||
result.Launcher.Packages[kv.Key] = kv.Value;
|
result.Launcher.Packages[kv.Key] = kv.Value;
|
||||||
|
}
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -81,6 +93,10 @@ public sealed class GiteaRemote : IModelRemote
|
|||||||
// 只有模型清单时也返回,保证模型能同步;启动器版本为空表示无升级
|
// 只有模型清单时也返回,保证模型能同步;启动器版本为空表示无升级
|
||||||
return result.Models.Count > 0 ? result : null;
|
return result.Models.Count > 0 ? result : null;
|
||||||
}
|
}
|
||||||
|
/// <summary>最近一次读到的清单原文(SAVEDOG 二次验签用)。</summary>
|
||||||
|
public Task<string?> GetRawVersionTextAsync(CancellationToken ct)
|
||||||
|
=> Task.FromResult(_rawManifest);
|
||||||
|
|
||||||
/// <summary>读仓库里的 version.json(模型清单 + 兜底信息)。</summary>
|
/// <summary>读仓库里的 version.json(模型清单 + 兜底信息)。</summary>
|
||||||
private async Task<RepoVersion?> TryGetVersionFromRepoAsync(CancellationToken ct)
|
private async Task<RepoVersion?> TryGetVersionFromRepoAsync(CancellationToken ct)
|
||||||
{
|
{
|
||||||
@@ -90,8 +106,14 @@ public sealed class GiteaRemote : IModelRemote
|
|||||||
{
|
{
|
||||||
var text = await Http.GetStringAsync(url, ct);
|
var text = await Http.GetStringAsync(url, ct);
|
||||||
if (!text.TrimStart().StartsWith('{')) continue; // 可能返回 HTML
|
if (!text.TrimStart().StartsWith('{')) continue; // 可能返回 HTML
|
||||||
var doc = JsonSerializer.Deserialize<RepoVersion>(text, Json.Options);
|
var doc = ManifestLoader.Parse(text, out var verification);
|
||||||
if (doc != null) return doc;
|
if (verification.Trust == ManifestTrust.Invalid)
|
||||||
|
Console.Error.WriteLine($"[gitea] 清单验签失败: {verification.Error}");
|
||||||
|
if (doc != null)
|
||||||
|
{
|
||||||
|
_rawManifest = text;
|
||||||
|
return doc;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
@@ -282,12 +304,35 @@ public sealed class GiteaRemote : IModelRemote
|
|||||||
|
|
||||||
public async Task<byte[]?> DownloadPackageAsync(RepoPackage package, CancellationToken ct)
|
public async Task<byte[]?> DownloadPackageAsync(RepoPackage package, CancellationToken ct)
|
||||||
{
|
{
|
||||||
if (string.IsNullOrWhiteSpace(package.Url)) return null;
|
// 与 GitCode 一致的策略:Release 附件 → 清单路径 → dist/<系统>-<架构>/ 里的编译产物。
|
||||||
try { return await Http.GetByteArrayAsync(package.Url, ct); }
|
// 每个来源都要过 sha256(来自已签名清单),所以多来源不降低安全性。
|
||||||
catch (Exception ex)
|
var candidates = new List<string>();
|
||||||
|
if (!string.IsNullOrWhiteSpace(package.Url)) candidates.Add(package.Url!.Trim());
|
||||||
|
foreach (var path in LauncherArtifacts.CandidateFiles(
|
||||||
|
package.Rid, package.Dir, package.Path, package.Name, ""))
|
||||||
|
candidates.Add(_preset.RawUrl(path));
|
||||||
|
|
||||||
|
foreach (var candidate in candidates)
|
||||||
{
|
{
|
||||||
Console.Error.WriteLine($"[gitea] 下载更新包失败: {ex.Message}");
|
byte[] bytes;
|
||||||
|
try { bytes = await Http.GetByteArrayAsync(candidate, ct); }
|
||||||
|
catch (Exception) { continue; }
|
||||||
|
if (bytes.Length == 0) continue;
|
||||||
|
|
||||||
|
if (!string.IsNullOrWhiteSpace(package.Sha256))
|
||||||
|
{
|
||||||
|
var actual = Convert.ToHexString(
|
||||||
|
System.Security.Cryptography.SHA256.HashData(bytes)).ToLowerInvariant();
|
||||||
|
if (!string.Equals(actual, package.Sha256.Trim(), StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
Console.Error.WriteLine($"[gitea] 包校验不符,换下一个来源: {candidate}");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Console.WriteLine($"[gitea] 启动器包来源: {candidate}");
|
||||||
|
return bytes;
|
||||||
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace GC.Services;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 平台标签与「仓库里的编译产物位置」的推导规则。
|
||||||
|
///
|
||||||
|
/// 历史背景:启动器更新原本只认 GitCode Release 的附件。但发布者往往只是把编译产物
|
||||||
|
/// 提交(或上传)到仓库的 <c>dist/<系统>-<架构></c> 目录,例如
|
||||||
|
/// <c>dist/mac-arm64/GC-1.0.7-mac-arm64.zip</c>,根本没有发 Release。
|
||||||
|
/// 于是下载端需要一套「同一个平台有哪几种叫法」的映射,才能把这些目录找出来。
|
||||||
|
///
|
||||||
|
/// 安全性说明:多来源尝试**不会**降低安全性——每个候选下载完都要和已签名清单里的
|
||||||
|
/// sha256 对一遍,对不上就换下一个来源,全都不对就失败。sha256 来自签名清单,
|
||||||
|
/// 攻击者即使往 dist/ 里塞包也拿不到匹配的哈希。
|
||||||
|
///
|
||||||
|
/// 本文件同时被启动器(GC-DOWNLOAD)与构建端(VersionStamp)链接编译,
|
||||||
|
/// 保证「写进清单的路径」与「运行时找的路径」永远一致。
|
||||||
|
/// </summary>
|
||||||
|
public static class LauncherArtifacts
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// RID → 文件名里的「系统-架构」标签(与 <c>LauncherUpdater.PlatformLabel</c> 一致)。
|
||||||
|
/// </summary>
|
||||||
|
public static string LabelOf(string rid) => rid switch
|
||||||
|
{
|
||||||
|
"win-x64" => "win-amd64",
|
||||||
|
"win-arm64" => "win-arm64",
|
||||||
|
"osx-arm64" => "mac-arm64",
|
||||||
|
"osx-x64" => "mac-x64",
|
||||||
|
"linux-x64" => "linux-amd64", // 旧产物目录名,仍能读
|
||||||
|
"linux-arm64" => "linux-arm64",
|
||||||
|
_ => rid
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 同一平台在仓库里可能用的目录名(按优先级)。
|
||||||
|
/// 既接受 <c>mac-arm64</c> 这种标签,也接受 <c>osx-arm64</c> 这种 RID,
|
||||||
|
/// 因为 dist 目录名历史上两种写法都出现过。
|
||||||
|
/// </summary>
|
||||||
|
public static IReadOnlyList<string> PlatformAliases(string rid)
|
||||||
|
{
|
||||||
|
var label = LabelOf(rid);
|
||||||
|
if (string.Equals(label, rid, StringComparison.OrdinalIgnoreCase))
|
||||||
|
return new[] { rid };
|
||||||
|
return new[] { label, rid };
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>启动器包应有的文件名,如 <c>GCL-1.0.10-mac-arm64.zip</c>。</summary>
|
||||||
|
public static string PackageFileName(string version, string rid)
|
||||||
|
=> $"GCL-{version.Trim().TrimStart('v', 'V')}-{LabelOf(rid)}.zip";
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 判断某个 zip 名是不是「这个版本 + 这个平台」的启动器包。
|
||||||
|
/// 只做粗筛(版本串 + 平台别名),最终仍以 sha256 为准。
|
||||||
|
/// </summary>
|
||||||
|
public static bool LooksLikePackage(string fileName, string version, string rid)
|
||||||
|
{
|
||||||
|
if (!fileName.EndsWith(".zip", StringComparison.OrdinalIgnoreCase)) return false;
|
||||||
|
// 1.0.10 起发布包统一叫 GCL-<版本>-<平台>.zip;GC- 是老命名,
|
||||||
|
// 一并认,装过 1.0.9 及更早版本的机器才不会把新包当成「不是启动器包」。
|
||||||
|
if (!fileName.StartsWith("GCL-", StringComparison.OrdinalIgnoreCase) &&
|
||||||
|
!fileName.StartsWith("GC-", StringComparison.OrdinalIgnoreCase)) return false;
|
||||||
|
|
||||||
|
var v = version.Trim().TrimStart('v', 'V');
|
||||||
|
if (v.Length > 0 && fileName.IndexOf(v, StringComparison.OrdinalIgnoreCase) < 0) return false;
|
||||||
|
|
||||||
|
var haystack = fileName.ToLowerInvariant();
|
||||||
|
foreach (var alias in PlatformAliases(rid))
|
||||||
|
if (haystack.Contains(alias.ToLowerInvariant(), StringComparison.Ordinal))
|
||||||
|
return true;
|
||||||
|
|
||||||
|
return haystack.Contains(rid.ToLowerInvariant(), StringComparison.Ordinal);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 候选目录:清单显式给的 dir 优先,其次是 <c>dist/<标签></c> 与 <c>dist/<RID></c>。
|
||||||
|
/// </summary>
|
||||||
|
public static IReadOnlyList<string> CandidateDirs(string rid, string? declaredDir)
|
||||||
|
{
|
||||||
|
var dirs = new List<string>();
|
||||||
|
if (!string.IsNullOrWhiteSpace(declaredDir))
|
||||||
|
dirs.Add(declaredDir!.Trim().Trim('/'));
|
||||||
|
|
||||||
|
foreach (var alias in PlatformAliases(rid))
|
||||||
|
dirs.Add("dist/" + alias);
|
||||||
|
|
||||||
|
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||||
|
var result = new List<string>();
|
||||||
|
foreach (var dir in dirs)
|
||||||
|
if (dir.Length > 0 && seen.Add(dir)) result.Add(dir);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 候选文件路径(不含目录扫描):清单给的 path / name,以及 dist 根目录里的两种命名。
|
||||||
|
/// </summary>
|
||||||
|
public static IReadOnlyList<string> CandidateFiles(string rid, string? declaredDir,
|
||||||
|
string? declaredPath, string? declaredName, string version)
|
||||||
|
{
|
||||||
|
var files = new List<string>();
|
||||||
|
if (!string.IsNullOrWhiteSpace(declaredPath))
|
||||||
|
files.Add(declaredPath!.Trim().Trim('/'));
|
||||||
|
|
||||||
|
if (!string.IsNullOrWhiteSpace(declaredName))
|
||||||
|
foreach (var dir in CandidateDirs(rid, declaredDir))
|
||||||
|
files.Add(dir + "/" + declaredName!.Trim());
|
||||||
|
|
||||||
|
if (version.Length > 0)
|
||||||
|
{
|
||||||
|
files.Add("dist/" + PackageFileName(version, rid));
|
||||||
|
foreach (var alias in PlatformAliases(rid))
|
||||||
|
files.Add($"dist/GC-{version.Trim().TrimStart('v', 'V')}-{alias}.zip");
|
||||||
|
}
|
||||||
|
|
||||||
|
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||||
|
var result = new List<string>();
|
||||||
|
foreach (var file in files)
|
||||||
|
if (file.Length > 0 && seen.Add(file)) result.Add(file);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,7 +7,7 @@ using System.Security.Cryptography;
|
|||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
namespace EarthModelStudio.Services;
|
namespace GC.Services;
|
||||||
|
|
||||||
// ===========================================================================
|
// ===========================================================================
|
||||||
// 启动器更新模块(唯一实现)
|
// 启动器更新模块(唯一实现)
|
||||||
@@ -23,31 +23,14 @@ namespace EarthModelStudio.Services;
|
|||||||
// · 一切落盘内容(脚本、标记)只用相对路径,绝不写绝对路径
|
// · 一切落盘内容(脚本、标记)只用相对路径,绝不写绝对路径
|
||||||
// ===========================================================================
|
// ===========================================================================
|
||||||
|
|
||||||
public sealed class UpdateProgressInfo
|
|
||||||
{
|
|
||||||
public double Value { get; init; }
|
|
||||||
public string Stage { get; init; } = "";
|
|
||||||
}
|
|
||||||
|
|
||||||
public enum UpdateRunState { UpToDate, Ready, Failed }
|
|
||||||
|
|
||||||
public sealed class UpdateRunResult
|
|
||||||
{
|
|
||||||
public UpdateRunState State { get; init; }
|
|
||||||
public string Version { get; init; } = "";
|
|
||||||
public string Message { get; init; } = "";
|
|
||||||
public string? PackageName { get; init; }
|
|
||||||
public string? NewAppPath { get; init; }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>下载 / 检查 / 应用启动器更新的唯一入口。</summary>
|
/// <summary>下载 / 检查 / 应用启动器更新的唯一入口。</summary>
|
||||||
public static class LauncherUpdater
|
public static class LauncherUpdater
|
||||||
{
|
{
|
||||||
/// <summary>当前运行程序的版本号(来自程序集)。</summary>
|
/// <summary>当前运行程序的版本号(来自程序集)。</summary>
|
||||||
public static string RunningVersion => UpdateService.CurrentLauncherVersion;
|
public static string RunningVersion => LauncherRuntimeInfo.CurrentLauncherVersion;
|
||||||
|
|
||||||
/// <summary>当前 RID,如 osx-arm64。</summary>
|
/// <summary>当前 RID,如 osx-arm64。</summary>
|
||||||
public static string CurrentRid => UpdateService.CurrentRid;
|
public static string CurrentRid => LauncherRuntimeInfo.CurrentRid;
|
||||||
|
|
||||||
/// <summary>文件名里用的「系统-架构」标签,如 mac-arm64 / win-amd64。</summary>
|
/// <summary>文件名里用的「系统-架构」标签,如 mac-arm64 / win-amd64。</summary>
|
||||||
public static string PlatformLabel => CurrentRid switch
|
public static string PlatformLabel => CurrentRid switch
|
||||||
@@ -211,14 +194,32 @@ public static class LauncherUpdater
|
|||||||
{
|
{
|
||||||
using var ms = new MemoryStream(zip);
|
using var ms = new MemoryStream(zip);
|
||||||
using var archive = new System.IO.Compression.ZipArchive(ms, System.IO.Compression.ZipArchiveMode.Read);
|
using var archive = new System.IO.Compression.ZipArchive(ms, System.IO.Compression.ZipArchiveMode.Read);
|
||||||
// 找主程序:app 内的可执行文件 / EarthModelStudio.dll / 单文件 exe
|
|
||||||
var entry = archive.Entries.FirstOrDefault(e =>
|
// 发布包从 1.0.10 起改为 GCL 命名 + 单文件 + 单顶层目录,主程序是
|
||||||
e.Name.Equals("EarthModelStudio.dll", StringComparison.OrdinalIgnoreCase))
|
// <顶层>/GCL-<版本>-<平台>.exe (Windows)
|
||||||
|
// <顶层>/GCL-<版本>-<平台> (Linux,无扩展名)
|
||||||
|
// <顶层>/GCL-<版本>-mac-arm64.app/... (macOS)
|
||||||
|
// 旧布局则是 GC.dll / GC / GC*.dll。先找新名,再退回旧名,兼容老发布包。
|
||||||
|
// 注意排除 GC-UI / GC-SAVEDOG / .GC/bin 里的附属程序,它们不是启动器本体。
|
||||||
|
bool IsLauncher(System.IO.Compression.ZipArchiveEntry e)
|
||||||
|
{
|
||||||
|
var n = e.Name;
|
||||||
|
if (n.Length == 0) return false; // 目录条目
|
||||||
|
if (n.StartsWith("GC-UI", StringComparison.OrdinalIgnoreCase) ||
|
||||||
|
n.StartsWith("GC-SAVEDOG", StringComparison.OrdinalIgnoreCase)) return false;
|
||||||
|
if (e.FullName.Replace('\\', '/').Contains("/.GC/")) return false;
|
||||||
|
if (n.StartsWith("GCL-", StringComparison.OrdinalIgnoreCase)) return true;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
var entry = archive.Entries.FirstOrDefault(IsLauncher)
|
||||||
?? archive.Entries.FirstOrDefault(e =>
|
?? archive.Entries.FirstOrDefault(e =>
|
||||||
e.Name.Equals("EarthModelStudio", StringComparison.OrdinalIgnoreCase))
|
e.Name.Equals("GC.dll", StringComparison.OrdinalIgnoreCase))
|
||||||
|
?? archive.Entries.FirstOrDefault(e =>
|
||||||
|
e.Name.Equals("GC", StringComparison.OrdinalIgnoreCase))
|
||||||
?? archive.Entries.FirstOrDefault(e =>
|
?? archive.Entries.FirstOrDefault(e =>
|
||||||
e.Name.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) &&
|
e.Name.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) &&
|
||||||
e.Name.StartsWith("EarthModelStudio", StringComparison.OrdinalIgnoreCase));
|
e.Name.StartsWith("GC", StringComparison.OrdinalIgnoreCase));
|
||||||
if (entry == null) return null;
|
if (entry == null) return null;
|
||||||
|
|
||||||
await using var es = entry.Open();
|
await using var es = entry.Open();
|
||||||
@@ -320,46 +321,124 @@ public static class LauncherUpdater
|
|||||||
!version.Launcher.Packages.TryGetValue("default", out pkg))
|
!version.Launcher.Packages.TryGetValue("default", out pkg))
|
||||||
return Fail($"该平台({rid})没有对应发布包");
|
return Fail($"该平台({rid})没有对应发布包");
|
||||||
|
|
||||||
|
// ---- 信任闸门 ---------------------------------------------------
|
||||||
|
// 启动器更新会替换可执行文件,风险最高:清单没签名就一律不动。
|
||||||
|
// 只有显式设置 GC_ALLOW_UNSIGNED_MANIFEST=1(自建私有构建)才放行。
|
||||||
|
var allowUnsigned =
|
||||||
|
Environment.GetEnvironmentVariable("GC_ALLOW_UNSIGNED_MANIFEST") == "1";
|
||||||
|
|
||||||
|
if (!version.IsTrusted && !allowUnsigned)
|
||||||
|
{
|
||||||
|
var reason = version.SignatureTrust == nameof(ManifestTrust.Invalid)
|
||||||
|
? "清单签名无效"
|
||||||
|
: "清单未签名";
|
||||||
|
Console.Error.WriteLine($"[update] 启动器更新被拒绝:{reason}");
|
||||||
|
return Fail($"{reason},已拒绝下载启动器更新");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (string.IsNullOrWhiteSpace(pkg!.Sha256))
|
||||||
|
{
|
||||||
|
Console.Error.WriteLine("[update] 清单没有提供 sha256,拒绝下载启动器更新");
|
||||||
|
return Fail("清单缺少该平台的 sha256,已拒绝下载(无法校验完整性)");
|
||||||
|
}
|
||||||
|
|
||||||
progress?.Report(new UpdateProgressInfo { Value = 0.20, Stage = $"正在下载 v{latest}" });
|
progress?.Report(new UpdateProgressInfo { Value = 0.20, Stage = $"正在下载 v{latest}" });
|
||||||
|
|
||||||
var bytes = await remote.DownloadPackageAsync(pkg!, ct);
|
var bytes = await remote.DownloadPackageAsync(pkg!, ct);
|
||||||
if (bytes == null || bytes.Length == 0) return Fail("下载失败:发布包为空");
|
if (bytes == null || bytes.Length == 0) return Fail("下载失败:发布包为空");
|
||||||
|
|
||||||
// sha256 校验(Release 提供时)
|
// sha256 校验(清单已验签,这里的 sha256 就是"正版"的定义)
|
||||||
if (!string.IsNullOrWhiteSpace(pkg!.Sha256))
|
|
||||||
{
|
{
|
||||||
var actual = Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant();
|
var actual = Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant();
|
||||||
if (!string.Equals(actual, pkg.Sha256!.Trim(), StringComparison.OrdinalIgnoreCase))
|
if (!string.Equals(actual, pkg.Sha256!.Trim(), StringComparison.OrdinalIgnoreCase))
|
||||||
return Fail("下载文件校验失败(sha256 不符)");
|
return Fail("下载文件校验失败(sha256 与已签名清单不符)");
|
||||||
}
|
}
|
||||||
|
|
||||||
progress?.Report(new UpdateProgressInfo { Value = 0.60, Stage = "正在解压到当前目录" });
|
progress?.Report(new UpdateProgressInfo { Value = 0.55, Stage = "正在校验更新包" });
|
||||||
|
|
||||||
|
var updateRoot = paths.UpdateRoot;
|
||||||
|
Directory.CreateDirectory(updateRoot);
|
||||||
|
|
||||||
|
// 更新包留在 .GC/update,交给 SAVEDOG 自己解压 —— 不信任"预解压目录",
|
||||||
|
// 避免「解压后被替换」的中间窗口。
|
||||||
|
var zip = Path.Combine(updateRoot, "package.zip");
|
||||||
|
if (File.Exists(zip)) File.Delete(zip);
|
||||||
|
await File.WriteAllBytesAsync(zip, bytes, ct);
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var inspection = SafeArchive.Inspect(zip);
|
||||||
|
Console.WriteLine($"[update] 更新包检查通过:{inspection.Entries} 个条目," +
|
||||||
|
$"{inspection.UncompressedBytes / 1024 / 1024} MB");
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
try { File.Delete(zip); } catch { }
|
||||||
|
return Fail("更新包安全性检查失败: " + ex.Message);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 二次验签用的清单副本:SAVEDOG 不信任"启动器说它验过了"
|
||||||
|
var rawManifest = await remote.GetRawVersionTextAsync(ct);
|
||||||
|
var manifestCopy = Path.Combine(updateRoot, "version.json");
|
||||||
|
if (!string.IsNullOrWhiteSpace(rawManifest))
|
||||||
|
File.WriteAllText(manifestCopy, rawManifest!);
|
||||||
|
else if (File.Exists(manifestCopy))
|
||||||
|
File.Delete(manifestCopy);
|
||||||
|
|
||||||
|
// 包名:GCL-<版本>-<平台标签>.app/.exe(SAVEDOG 找不到时会自行扫描包内顶层)。
|
||||||
|
// Linux 的启动器没有扩展名,别硬加 .exe —— 那会让按包名查找永远落空。
|
||||||
|
var packageName = $"GCL-{latest}-{PlatformLabel}" +
|
||||||
|
(OperatingSystem.IsMacOS() ? ".app"
|
||||||
|
: OperatingSystem.IsWindows() ? ".exe"
|
||||||
|
: "");
|
||||||
|
|
||||||
|
var request = new SavedogRequest
|
||||||
|
{
|
||||||
|
Version = latest,
|
||||||
|
Rid = rid,
|
||||||
|
PlatformLabel = PlatformLabel,
|
||||||
|
PackageName = packageName,
|
||||||
|
PackageZip = "package.zip",
|
||||||
|
PayloadDir = "payload",
|
||||||
|
ManifestPath = "version.json",
|
||||||
|
PackageSha256 = pkg.Sha256!.Trim().ToLowerInvariant(),
|
||||||
|
PackageSize = bytes.LongLength,
|
||||||
|
RequireSignature = version.IsTrusted,
|
||||||
|
InstallRelative = Path.GetRelativePath(updateRoot, paths.InstallDirectory),
|
||||||
|
CreatedAt = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ")
|
||||||
|
};
|
||||||
|
Json.Write(Path.Combine(updateRoot, SavedogFiles.ApplyRequest), request);
|
||||||
|
|
||||||
|
// 兼容兜底:没有 SAVEDOG 的旧安装,仍然按老方式预解压 + 脚本替换
|
||||||
|
string? legacyPath = null;
|
||||||
|
if (SavedogLauncher.Find(paths) == null)
|
||||||
|
{
|
||||||
|
Console.WriteLine("[update] 未找到 GC-SAVEDOG,使用兼容脚本流程");
|
||||||
|
progress?.Report(new UpdateProgressInfo { Value = 0.7, Stage = "正在解压更新包" });
|
||||||
|
|
||||||
// 解压到临时中转目录,再搬到当前运行目录
|
|
||||||
var installDir = paths.InstallDirectory;
|
|
||||||
Directory.CreateDirectory(installDir);
|
|
||||||
var staging = Path.Combine(paths.CacheRoot, "launcher-staging");
|
var staging = Path.Combine(paths.CacheRoot, "launcher-staging");
|
||||||
if (Directory.Exists(staging)) Directory.Delete(staging, true);
|
if (Directory.Exists(staging)) Directory.Delete(staging, true);
|
||||||
Directory.CreateDirectory(staging);
|
Directory.CreateDirectory(staging);
|
||||||
|
SafeArchive.ExtractToDirectory(zip, staging);
|
||||||
var zip = Path.Combine(paths.CacheRoot, "launcher-" + Safe(latest) + ".zip");
|
|
||||||
await File.WriteAllBytesAsync(zip, bytes, ct);
|
|
||||||
try { ZipSafety.ExtractToDirectory(zip, staging); }
|
|
||||||
finally { try { File.Delete(zip); } catch { } }
|
|
||||||
|
|
||||||
// 只展平「单个非 .app 顶层目录」的 zip
|
|
||||||
FlattenStaging(staging);
|
FlattenStaging(staging);
|
||||||
|
|
||||||
progress?.Report(new UpdateProgressInfo { Value = 0.80, Stage = "正在安装新版本" });
|
var payload = Path.Combine(updateRoot, "payload");
|
||||||
|
if (Directory.Exists(payload)) Directory.Delete(payload, true);
|
||||||
var packageName = MoveToInstallDir(staging, installDir, latest);
|
Directory.CreateDirectory(payload);
|
||||||
|
var legacyName = MoveToPayload(staging, payload);
|
||||||
try { Directory.Delete(staging, true); } catch { }
|
try { Directory.Delete(staging, true); } catch { }
|
||||||
if (packageName == null) return Fail("解压结果里没有找到新版启动器");
|
if (legacyName == null) return Fail("解压结果里没有找到新版启动器");
|
||||||
|
|
||||||
// 写标记(纯文本,脚本读它):只含相对信息,无绝对路径
|
packageName = legacyName;
|
||||||
Directory.CreateDirectory(paths.UpdateRoot);
|
request.PackageName = legacyName;
|
||||||
File.WriteAllText(Path.Combine(paths.UpdateRoot, "update.txt"),
|
Json.Write(Path.Combine(updateRoot, SavedogFiles.ApplyRequest), request);
|
||||||
$"NAME={packageName}\nVERSION={latest}\nPLATFORM={PlatformLabel}\n");
|
legacyPath = Path.Combine(payload, legacyName);
|
||||||
|
|
||||||
|
// 老脚本读这个纯文本标记,只含相对信息
|
||||||
|
File.WriteAllText(Path.Combine(updateRoot, "update.txt"),
|
||||||
|
$"NAME={legacyName}\nVERSION={latest}\nPLATFORM={PlatformLabel}\n" +
|
||||||
|
$"INSTALL_REL={request.InstallRelative}\n");
|
||||||
|
}
|
||||||
|
|
||||||
progress?.Report(new UpdateProgressInfo { Value = 1.0, Stage = "下载完成" });
|
progress?.Report(new UpdateProgressInfo { Value = 1.0, Stage = "下载完成" });
|
||||||
|
|
||||||
@@ -367,9 +446,9 @@ public static class LauncherUpdater
|
|||||||
{
|
{
|
||||||
State = UpdateRunState.Ready,
|
State = UpdateRunState.Ready,
|
||||||
Version = latest,
|
Version = latest,
|
||||||
Message = $"v{latest} 已下载到当前目录",
|
Message = $"v{latest} 已暂存到 .GC/update",
|
||||||
PackageName = packageName,
|
PackageName = packageName,
|
||||||
NewAppPath = Path.Combine(installDir, packageName)
|
NewAppPath = legacyPath
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
catch (OperationCanceledException) { return Fail("已取消"); }
|
catch (OperationCanceledException) { return Fail("已取消"); }
|
||||||
@@ -385,22 +464,32 @@ public static class LauncherUpdater
|
|||||||
// ---------------------------------------------------------------- 应用(下次启动)
|
// ---------------------------------------------------------------- 应用(下次启动)
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 生成替换脚本并启动。脚本等本进程退出后:
|
/// 安排应用已下载的新版。
|
||||||
/// 启动新版 -> 删除同平台且版本号 != latest 的 GC-* 文件 -> 清理标记。
|
/// 首选 <b>GC-SAVEDOG</b>:二次验签、原子替换、启动后健康检查、失败自动回滚;
|
||||||
|
/// 找不到 SAVEDOG 时退回旧脚本流程(只用于从老版本升级的过渡)。
|
||||||
/// 返回 true 表示调用方应立即退出进程。
|
/// 返回 true 表示调用方应立即退出进程。
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static bool ScheduleApply(AppPaths paths, string packageName)
|
/// <param name="execute">只写脚本不执行(测试用,避免真的搬动文件)。</param>
|
||||||
|
public static bool ScheduleApply(AppPaths paths, string packageName, bool execute = true)
|
||||||
{
|
{
|
||||||
var marker = Path.Combine(paths.UpdateRoot, "update.txt");
|
|
||||||
if (!File.Exists(marker)) return false;
|
|
||||||
|
|
||||||
// 安全阀:绝不在源码目录执行替换(防止误删源码)
|
// 安全阀:绝不在源码目录执行替换(防止误删源码)
|
||||||
if (File.Exists(Path.Combine(paths.InstallDirectory, "EarthModelStudio.sln")))
|
if (File.Exists(Path.Combine(paths.InstallDirectory, "GC.sln")))
|
||||||
{
|
{
|
||||||
Console.Error.WriteLine("源码版:新版已下载,但拒绝在源码目录执行替换");
|
Console.Error.WriteLine("源码版:新版已下载,但拒绝在源码目录执行替换");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (File.Exists(Path.Combine(paths.UpdateRoot, SavedogFiles.ApplyRequest)))
|
||||||
|
{
|
||||||
|
string? savedogError = null;
|
||||||
|
if (SavedogLauncher.TryStart(paths, Environment.ProcessId, out savedogError))
|
||||||
|
return true;
|
||||||
|
Console.Error.WriteLine($"[update] {savedogError},改用兼容脚本");
|
||||||
|
}
|
||||||
|
|
||||||
|
var marker = Path.Combine(paths.UpdateRoot, "update.txt");
|
||||||
|
if (!File.Exists(marker)) return false;
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var isWin = OperatingSystem.IsWindows();
|
var isWin = OperatingSystem.IsWindows();
|
||||||
@@ -418,6 +507,8 @@ public static class LauncherUpdater
|
|||||||
catch { }
|
catch { }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!execute) return true;
|
||||||
|
|
||||||
var psi = isWin
|
var psi = isWin
|
||||||
? new System.Diagnostics.ProcessStartInfo("cmd.exe")
|
? new System.Diagnostics.ProcessStartInfo("cmd.exe")
|
||||||
{ UseShellExecute = false, CreateNoWindow = true }
|
{ UseShellExecute = false, CreateNoWindow = true }
|
||||||
@@ -435,20 +526,37 @@ public static class LauncherUpdater
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>启动时若有待应用更新,安排脚本并让 Main 直接退出。</summary>
|
/// <summary>启动时若有待应用更新:交给 SAVEDOG,由调用方退出进程。</summary>
|
||||||
public static bool TryApplyPending(AppPaths paths)
|
public static bool TryApplyPending(AppPaths paths)
|
||||||
{
|
{
|
||||||
if (paths.IsDevelopment) return false;
|
if (paths.IsDevelopment) return false;
|
||||||
if (Environment.GetEnvironmentVariable("EMS_SELFTEST") == "1") return false;
|
if (Environment.GetEnvironmentVariable("EMS_SELFTEST") == "1") return false;
|
||||||
if (Environment.GetEnvironmentVariable("EMS_NO_SELF_UPDATE") == "1") return false;
|
if (Environment.GetEnvironmentVariable("EMS_NO_SELF_UPDATE") == "1") return false;
|
||||||
|
|
||||||
|
// 新协议:apply-request.json + package.zip(SAVEDOG 自己解压 + 验签)
|
||||||
|
var requestPath = Path.Combine(paths.UpdateRoot, SavedogFiles.ApplyRequest);
|
||||||
|
if (File.Exists(requestPath))
|
||||||
|
{
|
||||||
|
var request = Json.Read<SavedogRequest>(requestPath);
|
||||||
|
var zipPath = request == null
|
||||||
|
? null
|
||||||
|
: Path.Combine(paths.UpdateRoot, request.PackageZip);
|
||||||
|
|
||||||
|
if (request != null && zipPath != null && File.Exists(zipPath))
|
||||||
|
return ScheduleApply(paths, request.PackageName);
|
||||||
|
|
||||||
|
Console.Error.WriteLine("[update] 更新申请不完整,已清理");
|
||||||
|
try { File.Delete(requestPath); } catch { }
|
||||||
|
}
|
||||||
|
|
||||||
|
// 旧协议:update.txt + payload(从老版本升级时仍可能遇到)
|
||||||
var marker = Path.Combine(paths.UpdateRoot, "update.txt");
|
var marker = Path.Combine(paths.UpdateRoot, "update.txt");
|
||||||
if (!File.Exists(marker)) return false;
|
if (!File.Exists(marker)) return false;
|
||||||
|
|
||||||
var name = ReadMarker(marker, "NAME");
|
var name = ReadMarker(marker, "NAME");
|
||||||
if (string.IsNullOrWhiteSpace(name)) return false;
|
if (string.IsNullOrWhiteSpace(name)) return false;
|
||||||
if (!File.Exists(Path.Combine(paths.InstallDirectory, name!)) &&
|
var payloadPath = Path.Combine(paths.UpdateRoot, "payload", name!);
|
||||||
!Directory.Exists(Path.Combine(paths.InstallDirectory, name!)))
|
if (!File.Exists(payloadPath) && !Directory.Exists(payloadPath))
|
||||||
return false; // 新版本不在了,放弃
|
return false; // 新版本不在了,放弃
|
||||||
|
|
||||||
return ScheduleApply(paths, name!);
|
return ScheduleApply(paths, name!);
|
||||||
@@ -460,34 +568,43 @@ public static class LauncherUpdater
|
|||||||
{
|
{
|
||||||
var s = new System.Text.StringBuilder();
|
var s = new System.Text.StringBuilder();
|
||||||
s.AppendLine("#!/bin/sh");
|
s.AppendLine("#!/bin/sh");
|
||||||
s.AppendLine("# script lives in .GC/update/ ; install dir is two levels up");
|
s.AppendLine("# script lives in .GC/update/ ; install path is recorded relatively");
|
||||||
s.AppendLine("HERE=$(CDPATH= cd -- \"$(dirname -- \"$0\")\" && pwd)");
|
s.AppendLine("HERE=$(CDPATH= cd -- \"$(dirname -- \"$0\")\" && pwd)");
|
||||||
s.AppendLine("DST=$(CDPATH= cd -- \"$HERE/../..\" && pwd)");
|
|
||||||
s.AppendLine("MARKER=\"$HERE/update.txt\"");
|
s.AppendLine("MARKER=\"$HERE/update.txt\"");
|
||||||
s.AppendLine();
|
s.AppendLine();
|
||||||
s.AppendLine("# read marker");
|
s.AppendLine("# read marker");
|
||||||
s.AppendLine("NEWNAME=$(sed -n 's/^NAME=//p' \"$MARKER\" 2>/dev/null | head -1)");
|
s.AppendLine("NEWNAME=$(sed -n 's/^NAME=//p' \"$MARKER\" 2>/dev/null | head -1)");
|
||||||
s.AppendLine("NEWVER=$(sed -n 's/^VERSION=//p' \"$MARKER\" 2>/dev/null | head -1)");
|
s.AppendLine("NEWVER=$(sed -n 's/^VERSION=//p' \"$MARKER\" 2>/dev/null | head -1)");
|
||||||
s.AppendLine("NEWPLAT=$(sed -n 's/^PLATFORM=//p' \"$MARKER\" 2>/dev/null | head -1)");
|
s.AppendLine("NEWPLAT=$(sed -n 's/^PLATFORM=//p' \"$MARKER\" 2>/dev/null | head -1)");
|
||||||
s.AppendLine("if [ -z \"$NEWNAME\" ] || [ -z \"$NEWVER\" ]; then");
|
s.AppendLine("INSTALLREL=$(sed -n 's/^INSTALL_REL=//p' \"$MARKER\" 2>/dev/null | head -1)");
|
||||||
|
s.AppendLine("if [ -z \"$NEWNAME\" ] || [ -z \"$NEWVER\" ] || [ -z \"$INSTALLREL\" ]; then");
|
||||||
s.AppendLine(" echo \"marker incomplete, abort\"; rm -f \"$HERE\"/*.sh 2>/dev/null; exit 1");
|
s.AppendLine(" echo \"marker incomplete, abort\"; rm -f \"$HERE\"/*.sh 2>/dev/null; exit 1");
|
||||||
s.AppendLine("fi");
|
s.AppendLine("fi");
|
||||||
s.AppendLine("NEW=\"$DST/$NEWNAME\"");
|
s.AppendLine("DST=$(CDPATH= cd -- \"$HERE/$INSTALLREL\" && pwd)");
|
||||||
s.AppendLine("if [ ! -e \"$NEW\" ]; then");
|
s.AppendLine("PAYLOAD=\"$HERE/payload/$NEWNAME\"");
|
||||||
|
s.AppendLine("if [ ! -e \"$PAYLOAD\" ]; then");
|
||||||
s.AppendLine(" echo \"new package missing, abort\"; rm -f \"$HERE\"/*.sh 2>/dev/null; exit 1");
|
s.AppendLine(" echo \"new package missing, abort\"; rm -f \"$HERE\"/*.sh 2>/dev/null; exit 1");
|
||||||
s.AppendLine("fi");
|
s.AppendLine("fi");
|
||||||
s.AppendLine();
|
s.AppendLine();
|
||||||
s.AppendLine("# wait for old process to exit (this script is started by it)");
|
s.AppendLine("# wait for old process to exit (this script is started by it)");
|
||||||
s.AppendLine("sleep 2");
|
s.AppendLine("sleep 2");
|
||||||
s.AppendLine();
|
s.AppendLine();
|
||||||
s.AppendLine("# launch new version first");
|
s.AppendLine("# move the staged package into the install directory");
|
||||||
|
s.AppendLine("NEW=\"$DST/$NEWNAME\"");
|
||||||
|
s.AppendLine("rm -rf \"$NEW\"");
|
||||||
|
s.AppendLine("mv \"$PAYLOAD\" \"$NEW\"");
|
||||||
|
s.AppendLine();
|
||||||
|
s.AppendLine("# launch new version");
|
||||||
s.AppendLine("if [ -d \"$NEW\" ]; then open \"$NEW\" 2>/dev/null &");
|
s.AppendLine("if [ -d \"$NEW\" ]; then open \"$NEW\" 2>/dev/null &");
|
||||||
s.AppendLine("elif [ -x \"$NEW\" ]; then \"$NEW\" >/dev/null 2>&1 &");
|
s.AppendLine("elif [ -x \"$NEW\" ]; then \"$NEW\" >/dev/null 2>&1 &");
|
||||||
s.AppendLine("fi");
|
s.AppendLine("fi");
|
||||||
s.AppendLine();
|
s.AppendLine();
|
||||||
s.AppendLine("# delete old GC-* files: SAME platform only, version != latest");
|
s.AppendLine("# delete old GC-* files: SAME platform only, version != latest");
|
||||||
s.AppendLine("# files of OTHER platforms are NEVER touched");
|
s.AppendLine("# files of OTHER platforms are NEVER touched");
|
||||||
s.AppendLine("for item in \"$DST\"/GC-*.app \"$DST\"/GC-*.exe; do");
|
// Linux 的启动器没有扩展名(GC-1.0.9-linux-amd64),只匹配 *.app/*.exe 会漏掉,
|
||||||
|
// 结果是每次更新都在安装目录里多留一个旧版本。这里统一按 GC- 前缀扫,
|
||||||
|
// 再用「版本号-平台」的形态兜底,避免误删同目录的其它文件。
|
||||||
|
s.AppendLine("for item in \"$DST\"/GC-*; do");
|
||||||
s.AppendLine(" [ -e \"$item\" ] || continue");
|
s.AppendLine(" [ -e \"$item\" ] || continue");
|
||||||
s.AppendLine(" [ \"$item\" = \"$NEW\" ] && continue");
|
s.AppendLine(" [ \"$item\" = \"$NEW\" ] && continue");
|
||||||
s.AppendLine(" base=$(basename \"$item\")");
|
s.AppendLine(" base=$(basename \"$item\")");
|
||||||
@@ -495,6 +612,10 @@ public static class LauncherUpdater
|
|||||||
s.AppendLine(" case \"$base\" in");
|
s.AppendLine(" case \"$base\" in");
|
||||||
s.AppendLine(" *.app) stem=${stem%.app} ;;");
|
s.AppendLine(" *.app) stem=${stem%.app} ;;");
|
||||||
s.AppendLine(" *.exe) stem=${stem%.exe} ;;");
|
s.AppendLine(" *.exe) stem=${stem%.exe} ;;");
|
||||||
|
s.AppendLine(" esac");
|
||||||
|
s.AppendLine(" # 只认 <版本>-<系统>-<架构>,其它名字一律不动");
|
||||||
|
s.AppendLine(" case \"$stem\" in");
|
||||||
|
s.AppendLine(" [0-9]*-*-*) ;;");
|
||||||
s.AppendLine(" *) continue ;;");
|
s.AppendLine(" *) continue ;;");
|
||||||
s.AppendLine(" esac");
|
s.AppendLine(" esac");
|
||||||
s.AppendLine(" ver=${stem%%-*}");
|
s.AppendLine(" ver=${stem%%-*}");
|
||||||
@@ -522,18 +643,28 @@ public static class LauncherUpdater
|
|||||||
s.AppendLine("@echo off");
|
s.AppendLine("@echo off");
|
||||||
s.AppendLine("chcp 65001 >nul 2>&1");
|
s.AppendLine("chcp 65001 >nul 2>&1");
|
||||||
s.AppendLine("set \"HERE=%~dp0\"");
|
s.AppendLine("set \"HERE=%~dp0\"");
|
||||||
s.AppendLine("set \"DST=%~dp0..\\..\"");
|
|
||||||
s.AppendLine("set \"MARKER=%~dp0update.txt\"");
|
s.AppendLine("set \"MARKER=%~dp0update.txt\"");
|
||||||
s.AppendLine("timeout /t 2 /nobreak >nul");
|
s.AppendLine("timeout /t 2 /nobreak >nul");
|
||||||
s.AppendLine();
|
s.AppendLine();
|
||||||
s.AppendLine("set \"NEWNAME=\"");
|
s.AppendLine("set \"NEWNAME=\"");
|
||||||
s.AppendLine("set \"NEWVER=\"");
|
s.AppendLine("set \"NEWVER=\"");
|
||||||
s.AppendLine("set \"NEWPLAT=\"");
|
s.AppendLine("set \"NEWPLAT=\"");
|
||||||
|
s.AppendLine("set \"INSTALLREL=\"");
|
||||||
s.AppendLine("for /f \"tokens=2 delims==\" %%A in ('findstr /b \"NAME=\" \"%MARKER%\" 2^>nul') do set \"NEWNAME=%%A\"");
|
s.AppendLine("for /f \"tokens=2 delims==\" %%A in ('findstr /b \"NAME=\" \"%MARKER%\" 2^>nul') do set \"NEWNAME=%%A\"");
|
||||||
s.AppendLine("for /f \"tokens=2 delims==\" %%A in ('findstr /b \"VERSION=\" \"%MARKER%\" 2^>nul') do set \"NEWVER=%%A\"");
|
s.AppendLine("for /f \"tokens=2 delims==\" %%A in ('findstr /b \"VERSION=\" \"%MARKER%\" 2^>nul') do set \"NEWVER=%%A\"");
|
||||||
s.AppendLine("for /f \"tokens=2 delims==\" %%A in ('findstr /b \"PLATFORM=\" \"%MARKER%\" 2^>nul') do set \"NEWPLAT=%%A\"");
|
s.AppendLine("for /f \"tokens=2 delims==\" %%A in ('findstr /b \"PLATFORM=\" \"%MARKER%\" 2^>nul') do set \"NEWPLAT=%%A\"");
|
||||||
|
s.AppendLine("for /f \"tokens=2 delims==\" %%A in ('findstr /b \"INSTALL_REL=\" \"%MARKER%\" 2^>nul') do set \"INSTALLREL=%%A\"");
|
||||||
s.AppendLine("if \"%NEWNAME%\"==\"\" (echo marker incomplete, abort & del /Q \"%~f0\" >nul 2>&1 & exit /b 1)");
|
s.AppendLine("if \"%NEWNAME%\"==\"\" (echo marker incomplete, abort & del /Q \"%~f0\" >nul 2>&1 & exit /b 1)");
|
||||||
s.AppendLine("if not exist \"%DST%\\%NEWNAME%\" (echo new package missing, abort & del /Q \"%~f0\" >nul 2>&1 & exit /b 1)");
|
s.AppendLine("if \"%INSTALLREL%\"==\"\" (echo install path missing, abort & del /Q \"%~f0\" >nul 2>&1 & exit /b 1)");
|
||||||
|
s.AppendLine("for %%I in (\"%HERE%%INSTALLREL%\") do set \"DST=%%~fI\"");
|
||||||
|
s.AppendLine("set \"PAYLOAD=%HERE%payload\\%NEWNAME%\"");
|
||||||
|
s.AppendLine("if not exist \"%PAYLOAD%\" (echo new package missing, abort & del /Q \"%~f0\" >nul 2>&1 & exit /b 1)");
|
||||||
|
s.AppendLine();
|
||||||
|
s.AppendLine("rem move the staged package into the install directory");
|
||||||
|
s.AppendLine("if exist \"%DST%\\%NEWNAME%\" rmdir /S /Q \"%DST%\\%NEWNAME%\" 2>nul");
|
||||||
|
s.AppendLine("if exist \"%DST%\\%NEWNAME%\" del /Q \"%DST%\\%NEWNAME%\" 2>nul");
|
||||||
|
s.AppendLine("move \"%PAYLOAD%\" \"%DST%\\%NEWNAME%\" >nul");
|
||||||
|
s.AppendLine("if errorlevel 1 (echo failed to install update & exit /b 1)");
|
||||||
s.AppendLine();
|
s.AppendLine();
|
||||||
s.AppendLine("rem launch new version");
|
s.AppendLine("rem launch new version");
|
||||||
s.AppendLine("start \"\" \"%DST%\\%NEWNAME%\"");
|
s.AppendLine("start \"\" \"%DST%\\%NEWNAME%\"");
|
||||||
@@ -574,10 +705,10 @@ public static class LauncherUpdater
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 把 staging 里的新版搬到当前目录,与旧版并列。
|
/// 把 staging 里的新版搬入下载目录的 payload。
|
||||||
/// 返回新版包名(GC-<版本>-<平台>.app/.exe)。.GC 绝不覆盖。
|
/// 返回新版包名(GC-<版本>-<平台>.app/.exe)。
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private static string? MoveToInstallDir(string staging, string installDir, string latest)
|
private static string? MoveToPayload(string staging, string payload)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
@@ -585,7 +716,7 @@ public static class LauncherUpdater
|
|||||||
{
|
{
|
||||||
var name = Path.GetFileName(entry);
|
var name = Path.GetFileName(entry);
|
||||||
if (string.Equals(name, ".GC", StringComparison.OrdinalIgnoreCase)) continue;
|
if (string.Equals(name, ".GC", StringComparison.OrdinalIgnoreCase)) continue;
|
||||||
var dest = Path.Combine(installDir, name);
|
var dest = Path.Combine(payload, name);
|
||||||
|
|
||||||
if (Directory.Exists(dest)) Directory.Delete(dest, true);
|
if (Directory.Exists(dest)) Directory.Delete(dest, true);
|
||||||
else if (File.Exists(dest)) File.Delete(dest);
|
else if (File.Exists(dest)) File.Delete(dest);
|
||||||
@@ -612,6 +743,17 @@ public static class LauncherUpdater
|
|||||||
return name;
|
return name;
|
||||||
}
|
}
|
||||||
if (name.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) return name;
|
if (name.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) return name;
|
||||||
|
|
||||||
|
// Linux 的启动器没有扩展名(GC-1.0.9-linux-amd64),以前只认 .app/.exe,
|
||||||
|
// 结果解压完判定「没找到新版启动器」,Linux 更新永远失败。
|
||||||
|
// 注意不能用 Path.HasExtension:版本号 9.9.9 里的点会让它误判成有扩展名。
|
||||||
|
if ((name.StartsWith("GC-", StringComparison.OrdinalIgnoreCase) ||
|
||||||
|
name.StartsWith("GCL-", StringComparison.OrdinalIgnoreCase)) &&
|
||||||
|
name.EndsWith("-" + PlatformLabel, StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
TryMarkExecutable(dest);
|
||||||
|
return name;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
@@ -621,6 +763,22 @@ public static class LauncherUpdater
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>给 Linux/macOS 上的可执行文件补上执行位(zip 不保留权限)。</summary>
|
||||||
|
private static void TryMarkExecutable(string path)
|
||||||
|
{
|
||||||
|
if (OperatingSystem.IsWindows() || !File.Exists(path)) return;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var mode = File.GetUnixFileMode(path);
|
||||||
|
File.SetUnixFileMode(path, mode | UnixFileMode.UserExecute |
|
||||||
|
UnixFileMode.GroupExecute | UnixFileMode.OtherExecute);
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
// 权限设置失败不影响后续流程,用户可手动 chmod
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private static string? ReadMarker(string file, string key)
|
private static string? ReadMarker(string file, string key)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
@@ -2,9 +2,9 @@ using System;
|
|||||||
using System.IO;
|
using System.IO;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using EarthModelStudio.Models;
|
using GC.Models;
|
||||||
|
|
||||||
namespace EarthModelStudio.Services;
|
namespace GC.Services;
|
||||||
|
|
||||||
public static class ModelInstaller
|
public static class ModelInstaller
|
||||||
{
|
{
|
||||||
@@ -5,18 +5,20 @@ using System.IO;
|
|||||||
using System.IO.Compression;
|
using System.IO.Compression;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Net.Http;
|
using System.Net.Http;
|
||||||
|
using System.Security.Cryptography;
|
||||||
|
using System.Text;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using EarthModelStudio.Models;
|
using GC.Models;
|
||||||
|
|
||||||
namespace EarthModelStudio.Services;
|
namespace GC.Services;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 从链接导入模型源。
|
/// 从链接导入模型源。
|
||||||
/// 支持:git 仓库地址(GitHub / GitLab / Gitee / 任意 git 地址)、zip 直链、本地目录。
|
/// 支持:git 仓库地址(GitHub / GitLab / Gitee / 任意 git 地址)、zip 直链、本地目录。
|
||||||
/// 仓库里的 model/ 目录就是模型列表;下载后缓存到 cache/sources/<id>。
|
/// 仓库里的 model/ 目录就是模型列表;下载后缓存在应用缓存目录。
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public sealed class ModelSourceClient
|
public sealed class ModelSourceClient : IModelSourceClient
|
||||||
{
|
{
|
||||||
private readonly AppPaths _paths;
|
private readonly AppPaths _paths;
|
||||||
private static readonly HttpClient Http = CreateHttp();
|
private static readonly HttpClient Http = CreateHttp();
|
||||||
@@ -26,7 +28,7 @@ public sealed class ModelSourceClient
|
|||||||
private static HttpClient CreateHttp()
|
private static HttpClient CreateHttp()
|
||||||
{
|
{
|
||||||
var client = new HttpClient { Timeout = TimeSpan.FromMinutes(5) };
|
var client = new HttpClient { Timeout = TimeSpan.FromMinutes(5) };
|
||||||
client.DefaultRequestHeaders.UserAgent.ParseAdd("EarthModelStudio/1.0 (+model-source)");
|
client.DefaultRequestHeaders.UserAgent.ParseAdd("GC/1.0 (+model-source)");
|
||||||
return client;
|
return client;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -152,24 +154,33 @@ public sealed class ModelSourceClient
|
|||||||
else if (host.Contains("gitee.com"))
|
else if (host.Contains("gitee.com"))
|
||||||
yield return $"https://gitee.com/{owner}/{repo}/repository/archive/{b}.zip";
|
yield return $"https://gitee.com/{owner}/{repo}/repository/archive/{b}.zip";
|
||||||
else
|
else
|
||||||
yield break;
|
{
|
||||||
|
// 自托管 Gitea(如 git.xhmcl.com):用 archive/<branch>.zip 拉源码归档。
|
||||||
|
// 关键:不能在这里 yield break —— 那样就只剩 git clone 一条路,
|
||||||
|
// 用户机器没装 git 时「检测模型 / 下载 / 自动更新」会全部失效。
|
||||||
|
// 归档下载走 ResumableDownloader,无需系统 git。
|
||||||
|
yield return $"{uri.GetLeftPart(UriPartial.Authority)}/{owner}/{repo}/archive/{b}.zip";
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task DownloadZipAsync(string url, string cacheDir, CancellationToken ct)
|
private async Task DownloadZipAsync(string url, string cacheDir, CancellationToken ct)
|
||||||
{
|
{
|
||||||
|
// .part 用 URL 哈希做稳定文件名:同一个源重试时命中同一份半成品,
|
||||||
|
// 断点续传才有意义(用 GUID 的话每次重试都是新文件,等于从零开始)。
|
||||||
|
// 解压目录仍用 GUID —— 它只是中间产物,成功后整块移走或失败即删。
|
||||||
|
var key = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(url)))[..16].ToLowerInvariant();
|
||||||
|
var partPath = Path.Combine(_paths.CacheRoot, "tmp", "downloads", key + ".part");
|
||||||
var tmpRoot = Path.Combine(_paths.CacheRoot, "tmp", Guid.NewGuid().ToString("N"));
|
var tmpRoot = Path.Combine(_paths.CacheRoot, "tmp", Guid.NewGuid().ToString("N"));
|
||||||
Directory.CreateDirectory(tmpRoot);
|
Directory.CreateDirectory(tmpRoot);
|
||||||
var zipPath = Path.Combine(tmpRoot, "source.zip");
|
var zipPath = Path.Combine(tmpRoot, "source.zip");
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
using (var response = await Http.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, ct))
|
// 带断点续传的流式下载;网络中断时 .part 保留,下次从这里接上。
|
||||||
{
|
await ResumableDownloader.DownloadAsync(Http, url, partPath, null, ct)
|
||||||
response.EnsureSuccessStatusCode();
|
.ConfigureAwait(false);
|
||||||
await using var input = await response.Content.ReadAsStreamAsync(ct);
|
// 下载完整,.part 转正。转正成功即代表这份 zip 已完整,删掉 .part 避免重复下载。
|
||||||
await using var output = File.Create(zipPath);
|
File.Move(partPath, zipPath, overwrite: true);
|
||||||
await input.CopyToAsync(output, 81920, ct);
|
|
||||||
}
|
|
||||||
|
|
||||||
var extractDir = Path.Combine(tmpRoot, "extract");
|
var extractDir = Path.Combine(tmpRoot, "extract");
|
||||||
Directory.CreateDirectory(extractDir);
|
Directory.CreateDirectory(extractDir);
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
using System;
|
||||||
|
using System.IO;
|
||||||
|
using System.Net;
|
||||||
|
using System.Net.Http;
|
||||||
|
using System.Net.Http.Headers;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace GC.Services;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 带断点续传的流式下载器。已下载的部分写在 <c>*.part</c> 文件里,
|
||||||
|
/// 完整下载后由调用方把 .part 改成正式文件名。
|
||||||
|
///
|
||||||
|
/// 为什么需要它:模型源码 zip 可能有上百 MB,弱网中断后如果每次都从头下,
|
||||||
|
/// 用户会反复卡在同一个地方。这里用 HTTP Range 从已下载的字节接着下。
|
||||||
|
///
|
||||||
|
/// 兼容性:服务器不支持 Range(忽略请求、返回 200)时自动退化为整段下载,
|
||||||
|
/// 不会卡死或拿到半截文件。<see cref="Content-Range"/> 起始位置不符时也从头下。
|
||||||
|
///
|
||||||
|
/// .part 文件只有在"续传"场景才复用;一旦下载完整、调用方改名为正式文件,
|
||||||
|
/// 下次就是全新下载,不会把旧内容接在新内容后面。
|
||||||
|
/// </summary>
|
||||||
|
public static class ResumableDownloader
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 下载 <paramref name="url"/>,数据写入 <paramref name="partPath"/>。
|
||||||
|
/// 返回最终 .part 文件的字节数。下载完整后由调用方负责改名 / 校验。
|
||||||
|
/// </summary>
|
||||||
|
public static async Task<long> DownloadAsync(
|
||||||
|
HttpClient http,
|
||||||
|
string url,
|
||||||
|
string partPath,
|
||||||
|
IProgress<(long Done, long Total)>? progress,
|
||||||
|
CancellationToken ct)
|
||||||
|
{
|
||||||
|
// 已有 .part 就尝试从断点续传;没有则从头下
|
||||||
|
long resumeFrom = 0;
|
||||||
|
if (File.Exists(partPath))
|
||||||
|
{
|
||||||
|
try { resumeFrom = new FileInfo(partPath).Length; }
|
||||||
|
catch { resumeFrom = 0; }
|
||||||
|
}
|
||||||
|
|
||||||
|
using var req = new HttpRequestMessage(HttpMethod.Get, url);
|
||||||
|
if (resumeFrom > 0)
|
||||||
|
req.Headers.Range = new RangeHeaderValue(resumeFrom, null);
|
||||||
|
|
||||||
|
using var response = await http.SendAsync(req, HttpCompletionOption.ResponseHeadersRead, ct)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
response.EnsureSuccessStatusCode();
|
||||||
|
|
||||||
|
var canResume = response.StatusCode == HttpStatusCode.PartialContent && resumeFrom > 0;
|
||||||
|
long? total = response.Content.Headers.ContentLength;
|
||||||
|
|
||||||
|
if (canResume)
|
||||||
|
{
|
||||||
|
// 校验服务器确实从我们要的位置开始返回:Content-Range: bytes START-END/TOTAL
|
||||||
|
var range = response.Content.Headers.ContentRange;
|
||||||
|
if (range?.HasRange == true && range.From == resumeFrom && range.Length.HasValue)
|
||||||
|
{
|
||||||
|
total = range.Length.Value;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
// 服务器忽略了 Range 或给出的范围对不上:从头覆盖,避免拼接出损坏的文件
|
||||||
|
canResume = false;
|
||||||
|
resumeFrom = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var mode = canResume ? FileMode.Append : FileMode.Create;
|
||||||
|
var dir = Path.GetDirectoryName(partPath);
|
||||||
|
if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
|
||||||
|
|
||||||
|
await using (var input = await response.Content.ReadAsStreamAsync(ct).ConfigureAwait(false))
|
||||||
|
await using (var output = new FileStream(partPath, mode, FileAccess.Write, FileShare.Read,
|
||||||
|
81920, useAsync: true))
|
||||||
|
{
|
||||||
|
var buffer = new byte[81920];
|
||||||
|
long done = resumeFrom;
|
||||||
|
int read;
|
||||||
|
while ((read = await input.ReadAsync(buffer.AsMemory(), ct).ConfigureAwait(false)) > 0)
|
||||||
|
{
|
||||||
|
await output.WriteAsync(buffer.AsMemory(0, read), ct).ConfigureAwait(false);
|
||||||
|
done += read;
|
||||||
|
// Total 未知时用已下载量当分母,进度条会停在 100% 之前但不报错
|
||||||
|
progress?.Report((done, total ?? done));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return SafeLength(partPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static long SafeLength(string path)
|
||||||
|
{
|
||||||
|
try { return new FileInfo(path).Length; }
|
||||||
|
catch { return 0; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
using System;
|
||||||
|
using System.Diagnostics;
|
||||||
|
using System.IO;
|
||||||
|
using System.Linq;
|
||||||
|
|
||||||
|
namespace GC.Services;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 找到并启动 GC-SAVEDOG(启动器更新的守护进程)。
|
||||||
|
///
|
||||||
|
/// 为什么要独立进程:启动器正在运行时无法安全覆盖自己;一旦覆盖失败,
|
||||||
|
/// 启动器已退出,就没人能回滚。把"替换 + 看护"交给一个只做这件事的小程序,
|
||||||
|
/// 风险面被压缩到最小,也便于审计。
|
||||||
|
/// </summary>
|
||||||
|
public static class SavedogLauncher
|
||||||
|
{
|
||||||
|
/// <summary>在安装目录里寻找 SAVEDOG 可执行文件。</summary>
|
||||||
|
public static string? Find(AppPaths paths)
|
||||||
|
{
|
||||||
|
var name = SavedogFiles.ExecutableName;
|
||||||
|
var install = paths.InstallDirectory;
|
||||||
|
|
||||||
|
// 首选 .GC/safedog:更新时整目录替换不会碰这里,正在运行的守护进程也安全。
|
||||||
|
var home = Path.Combine(paths.SafedogRoot, name);
|
||||||
|
if (File.Exists(home)) return home;
|
||||||
|
|
||||||
|
// 包内 payload:非本体文件统一收在 .GC/bin
|
||||||
|
var payload = Path.Combine(install, ".GC", "bin", name);
|
||||||
|
if (File.Exists(payload)) return payload;
|
||||||
|
|
||||||
|
var direct = Path.Combine(install, name);
|
||||||
|
if (File.Exists(direct)) return direct;
|
||||||
|
|
||||||
|
// 1.0.10 及更早的包把守护进程放在 safedog/ 子目录
|
||||||
|
var packaged = Path.Combine(install, "safedog", name);
|
||||||
|
if (File.Exists(packaged)) return packaged;
|
||||||
|
|
||||||
|
// macOS:可能放在 .app 内部
|
||||||
|
try
|
||||||
|
{
|
||||||
|
foreach (var app in Directory.GetDirectories(install, "*.app"))
|
||||||
|
{
|
||||||
|
var inside = Path.Combine(app, "Contents", "MacOS", name);
|
||||||
|
if (File.Exists(inside)) return inside;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch { }
|
||||||
|
|
||||||
|
var bin = Path.Combine(paths.HomeRoot, "bin", name);
|
||||||
|
if (File.Exists(bin)) return bin;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var exe = Environment.ProcessPath;
|
||||||
|
if (!string.IsNullOrWhiteSpace(exe))
|
||||||
|
{
|
||||||
|
var beside = Path.Combine(Path.GetDirectoryName(exe)!, name);
|
||||||
|
if (File.Exists(beside)) return beside;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch { }
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 启动 SAVEDOG 应用更新。<paramref name="waitForPid"/> 是当前启动器进程,
|
||||||
|
/// SAVEDOG 会等它退出后再动文件。
|
||||||
|
/// </summary>
|
||||||
|
public static bool TryStart(AppPaths paths, int waitForPid, out string? error)
|
||||||
|
{
|
||||||
|
error = null;
|
||||||
|
var exe = Find(paths);
|
||||||
|
if (exe == null)
|
||||||
|
{
|
||||||
|
error = "未找到 GC-SAVEDOG";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var requestPath = Path.Combine(paths.UpdateRoot, SavedogFiles.ApplyRequest);
|
||||||
|
if (!File.Exists(requestPath))
|
||||||
|
{
|
||||||
|
error = "缺少 apply-request.json";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
var psi = new ProcessStartInfo(exe)
|
||||||
|
{
|
||||||
|
UseShellExecute = false,
|
||||||
|
CreateNoWindow = true,
|
||||||
|
WorkingDirectory = paths.InstallDirectory
|
||||||
|
};
|
||||||
|
psi.ArgumentList.Add("apply");
|
||||||
|
psi.ArgumentList.Add("--update");
|
||||||
|
psi.ArgumentList.Add(paths.UpdateRoot);
|
||||||
|
psi.ArgumentList.Add("--install");
|
||||||
|
psi.ArgumentList.Add(paths.InstallDirectory);
|
||||||
|
psi.ArgumentList.Add("--wait-pid");
|
||||||
|
psi.ArgumentList.Add(waitForPid.ToString());
|
||||||
|
psi.ArgumentList.Add("--timeout");
|
||||||
|
psi.ArgumentList.Add("45");
|
||||||
|
|
||||||
|
if (!OperatingSystem.IsWindows())
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var mode = File.GetUnixFileMode(exe);
|
||||||
|
File.SetUnixFileMode(exe, mode | UnixFileMode.UserExecute);
|
||||||
|
}
|
||||||
|
catch { }
|
||||||
|
}
|
||||||
|
|
||||||
|
Process.Start(psi);
|
||||||
|
Console.WriteLine($"[update] GC-SAVEDOG 已启动: {exe}");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
error = ex.Message;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>读取 SAVEDOG 最近一次的执行结果(供界面展示)。</summary>
|
||||||
|
public static SavedogState? ReadState(AppPaths paths)
|
||||||
|
=> Json.Read<SavedogState>(Path.Combine(paths.UpdateRoot, SavedogFiles.State));
|
||||||
|
|
||||||
|
/// <summary>上次成功启动的版本(回滚依据)。</summary>
|
||||||
|
public static LastGoodVersion? ReadLastGood(AppPaths paths)
|
||||||
|
=> Json.Read<LastGoodVersion>(Path.Combine(paths.UpdateRoot, SavedogFiles.LastGood));
|
||||||
|
}
|
||||||
@@ -6,7 +6,7 @@ using System.Net.Http;
|
|||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
namespace EarthModelStudio.Services;
|
namespace GC.Services;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 双源选择:Xhmcl 与 GitCode 是同一份仓库的两个镜像。
|
/// 双源选择:Xhmcl 与 GitCode 是同一份仓库的两个镜像。
|
||||||
@@ -15,14 +15,14 @@ namespace EarthModelStudio.Services;
|
|||||||
/// 取**最快且内容可用**的那个作为本次下载源;探测结果缓存一段时间,
|
/// 取**最快且内容可用**的那个作为本次下载源;探测结果缓存一段时间,
|
||||||
/// 避免每次点下载都重新测速。
|
/// 避免每次点下载都重新测速。
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public sealed class SourceSelector
|
public sealed class SourceSelector : ISourceSelector
|
||||||
{
|
{
|
||||||
private static readonly HttpClient Http = CreateHttp();
|
private static readonly HttpClient Http = CreateHttp();
|
||||||
|
|
||||||
private static HttpClient CreateHttp()
|
private static HttpClient CreateHttp()
|
||||||
{
|
{
|
||||||
var c = new HttpClient { Timeout = TimeSpan.FromSeconds(6) };
|
var c = new HttpClient { Timeout = TimeSpan.FromSeconds(6) };
|
||||||
c.DefaultRequestHeaders.UserAgent.ParseAdd("EarthModelStudio-Probe/1.0");
|
c.DefaultRequestHeaders.UserAgent.ParseAdd("GC-Probe/1.0");
|
||||||
return c;
|
return c;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -40,7 +40,8 @@ public sealed class SourceSelector
|
|||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 探测两个源并返回最快的。force=true 时忽略缓存。
|
/// 探测两个源并返回最快的。force=true 时忽略缓存。
|
||||||
/// 两个都失败时返回 GitCode(默认源)。
|
/// 两个都失败时退回主源(Xhmcl):GitCode 镜像已停更,用它兜底只会拿到过期的
|
||||||
|
/// version.json —— 反而让人以为「没有更新」。
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public async Task<SourcePreset> PickFastestAsync(bool force = false, CancellationToken ct = default)
|
public async Task<SourcePreset> PickFastestAsync(bool force = false, CancellationToken ct = default)
|
||||||
{
|
{
|
||||||
@@ -64,12 +65,20 @@ public sealed class SourceSelector
|
|||||||
LastLatency = latencies;
|
LastLatency = latencies;
|
||||||
|
|
||||||
var usable = results.Where(r => r.Ok).OrderBy(r => r.Ms).ToList();
|
var usable = results.Where(r => r.Ok).OrderBy(r => r.Ms).ToList();
|
||||||
var chosen = usable.Count > 0 ? usable[0].Preset : SourcePreset.GitCode;
|
// 全部探测失败时退回主源(SourcePreset.All 的第一项 = Xhmcl),
|
||||||
|
// 不要退回已停更的 GitCode 镜像。
|
||||||
|
var fallback = SourcePreset.All.Length > 0 ? SourcePreset.All[0] : SourcePreset.Xhmcl;
|
||||||
|
var chosen = usable.Count > 0 ? usable[0].Preset : fallback;
|
||||||
|
|
||||||
|
if (usable.Count == 0)
|
||||||
|
Console.WriteLine($"[selector] 所有源探测失败,退回主源 {chosen.Name}(稍后由实际请求再判定)");
|
||||||
|
|
||||||
lock (_lock)
|
lock (_lock)
|
||||||
{
|
{
|
||||||
_cached = chosen;
|
_cached = chosen;
|
||||||
_cachedAt = DateTime.UtcNow;
|
// 全部探测失败的结果不缓存:网络刚恢复时应该立刻重新测速,
|
||||||
|
// 而不是被一次失败的探测锁住 3 分钟。
|
||||||
|
_cachedAt = usable.Count > 0 ? DateTime.UtcNow : DateTime.MinValue;
|
||||||
}
|
}
|
||||||
|
|
||||||
Console.WriteLine("[selector] 测速:" + string.Join(" ",
|
Console.WriteLine("[selector] 测速:" + string.Join(" ",
|
||||||
@@ -8,16 +8,16 @@ using System.Runtime.InteropServices;
|
|||||||
using System.Security.Cryptography;
|
using System.Security.Cryptography;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using EarthModelStudio.Models;
|
using GC.Models;
|
||||||
|
|
||||||
namespace EarthModelStudio.Services;
|
namespace GC.Services;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 模型自动更新:读远端版本清单,把缺失/过期的模型下载到 cache 后原子替换
|
/// 模型自动更新:读远端版本清单,把缺失/过期的模型下载到 cache 后原子替换
|
||||||
/// .GC/model/<id>,本次启动立即生效。任何失败都保留本地已装模型。
|
/// .GC/model/<id>,本次启动立即生效。任何失败都保留本地已装模型。
|
||||||
/// 启动器更新由 LauncherUpdater / LauncherUpdateFlow 独立负责,不在这里。
|
/// 启动器更新由 LauncherUpdater / LauncherUpdateFlow 独立负责,不在这里。
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public sealed class UpdateService
|
public sealed class UpdateService : IUpdateService
|
||||||
{
|
{
|
||||||
private readonly AppPaths _paths;
|
private readonly AppPaths _paths;
|
||||||
private readonly SettingsService _settings;
|
private readonly SettingsService _settings;
|
||||||
@@ -35,55 +35,6 @@ public sealed class UpdateService
|
|||||||
/// <summary>换源:测速选出最快的一个后,用它的 remote 覆盖当前实例。</summary>
|
/// <summary>换源:测速选出最快的一个后,用它的 remote 覆盖当前实例。</summary>
|
||||||
public void UseRemote(IModelRemote remote) => _remote = remote;
|
public void UseRemote(IModelRemote remote) => _remote = remote;
|
||||||
|
|
||||||
private static string? _versionOverride;
|
|
||||||
|
|
||||||
public static string CurrentLauncherVersion
|
|
||||||
{
|
|
||||||
get
|
|
||||||
{
|
|
||||||
if (!string.IsNullOrWhiteSpace(_versionOverride)) return _versionOverride!;
|
|
||||||
|
|
||||||
// 用**本程序集**的版本,而不是 GetEntryAssembly()。
|
|
||||||
// EntryAssembly 在宿主(dotnet run / 测试宿主 / 单文件解包)下可能指向别的程序,
|
|
||||||
// 读出来会变成 1.0.0,导致「明明是最新版却一直提示有更新」。
|
|
||||||
var asm = typeof(UpdateService).Assembly;
|
|
||||||
var v = asm.GetName().Version;
|
|
||||||
if (v == null || (v.Major == 0 && v.Minor == 0 && v.Build == 0))
|
|
||||||
{
|
|
||||||
// 兜底:读 InformationalVersion(Directory.Build.props 里的 <Version>)
|
|
||||||
var info = asm.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion;
|
|
||||||
if (!string.IsNullOrWhiteSpace(info))
|
|
||||||
{
|
|
||||||
var core = info!.Split('+')[0].Trim();
|
|
||||||
if (Version.TryParse(core, out var iv))
|
|
||||||
v = iv;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (v == null) return "0.0.0";
|
|
||||||
return $"{Math.Max(0, v.Major)}.{Math.Max(0, v.Minor)}.{Math.Max(0, v.Build)}";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>测试 / 自检时临时指定版本号。</summary>
|
|
||||||
public static void OverrideLauncherVersion(string? version) => _versionOverride = version;
|
|
||||||
|
|
||||||
public static string CurrentRid
|
|
||||||
{
|
|
||||||
get
|
|
||||||
{
|
|
||||||
var arch = RuntimeInformation.OSArchitecture switch
|
|
||||||
{
|
|
||||||
Architecture.Arm64 => "arm64",
|
|
||||||
Architecture.X86 => "x86",
|
|
||||||
_ => "x64"
|
|
||||||
};
|
|
||||||
if (OperatingSystem.IsWindows()) return "win-" + arch;
|
|
||||||
if (OperatingSystem.IsMacOS()) return "osx-" + arch;
|
|
||||||
if (OperatingSystem.IsLinux()) return "linux-" + arch;
|
|
||||||
return RuntimeInformation.RuntimeIdentifier;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 同步版本(无法测速时用):按设置里的仓库地址映射到内置源。
|
/// 同步版本(无法测速时用):按设置里的仓库地址映射到内置源。
|
||||||
/// 真正带测速的入口是 <see cref="CreateRemoteAsync"/>。
|
/// 真正带测速的入口是 <see cref="CreateRemoteAsync"/>。
|
||||||
@@ -153,6 +104,37 @@ public sealed class UpdateService
|
|||||||
Message = L.I["update.noManifest"]
|
Message = L.I["update.noManifest"]
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// ---- 清单信任策略 --------------------------------------------------
|
||||||
|
// 签名有效 → 通过;没有签名 / 签名不符 → 默认拒绝(可用设置或环境变量放开)。
|
||||||
|
// 这一道闸门挡住的是「仓库被改、模型 dll 被换成木马」这类攻击。
|
||||||
|
var allowUnsigned = devMode ||
|
||||||
|
!_settings.Current.RequireSignedManifest ||
|
||||||
|
Environment.GetEnvironmentVariable("GC_ALLOW_UNSIGNED_MANIFEST") == "1";
|
||||||
|
|
||||||
|
if (!remote.IsTrusted)
|
||||||
|
{
|
||||||
|
var reason = remote.SignatureTrust == nameof(ManifestTrust.Invalid)
|
||||||
|
? "清单签名无效(内容可能被篡改)"
|
||||||
|
: "清单未签名";
|
||||||
|
|
||||||
|
if (!allowUnsigned)
|
||||||
|
{
|
||||||
|
Console.Error.WriteLine($"[update] {reason},已拒绝本次更新");
|
||||||
|
return new UpdateResult
|
||||||
|
{
|
||||||
|
Outcome = UpdateOutcome.Unavailable,
|
||||||
|
Message = $"{reason},已拒绝更新",
|
||||||
|
Error = remote.SignatureError
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
Console.Error.WriteLine($"[update] {reason},当前为开发/放宽模式,继续");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
Console.WriteLine($"[update] 清单验签通过({remote.SignatureKeyId})");
|
||||||
|
}
|
||||||
|
|
||||||
_settings.Current.LastUpdateCheck = DateTime.UtcNow.ToString("O");
|
_settings.Current.LastUpdateCheck = DateTime.UtcNow.ToString("O");
|
||||||
_settings.Save();
|
_settings.Save();
|
||||||
|
|
||||||
@@ -297,6 +279,22 @@ public sealed class UpdateService
|
|||||||
|
|
||||||
await Task.WhenAll(tasks);
|
await Task.WhenAll(tasks);
|
||||||
|
|
||||||
|
// ---- 完整性校验:清单是签过名的,里面的哈希就是"正版"的定义 --------
|
||||||
|
// 下载到暂存目录后按同一算法复算,不一致直接丢弃,绝不安装。
|
||||||
|
var computed = ModelIntegrity.Compute(staging, model.Id);
|
||||||
|
|
||||||
|
if (!string.IsNullOrWhiteSpace(model.ManifestSha256) &&
|
||||||
|
!string.Equals(computed.ManifestSha256, model.ManifestSha256,
|
||||||
|
StringComparison.OrdinalIgnoreCase))
|
||||||
|
throw new InvalidOperationException(
|
||||||
|
$"模型清单哈希不符(期望 {Short(model.ManifestSha256)},实际 {Short(computed.ManifestSha256)})");
|
||||||
|
|
||||||
|
if (!string.IsNullOrWhiteSpace(model.FilesSha256) &&
|
||||||
|
!string.Equals(computed.FilesSha256, model.FilesSha256,
|
||||||
|
StringComparison.OrdinalIgnoreCase))
|
||||||
|
throw new InvalidOperationException(
|
||||||
|
$"模型文件哈希不符(期望 {Short(model.FilesSha256)},实际 {Short(computed.FilesSha256)}),已丢弃");
|
||||||
|
|
||||||
// 原子替换:先备份旧目录,成功后再删备份;失败自动回滚
|
// 原子替换:先备份旧目录,成功后再删备份;失败自动回滚
|
||||||
Directory.CreateDirectory(_paths.ModelRoot);
|
Directory.CreateDirectory(_paths.ModelRoot);
|
||||||
var target = Path.Combine(_paths.ModelRoot, model.Id);
|
var target = Path.Combine(_paths.ModelRoot, model.Id);
|
||||||
@@ -319,6 +317,25 @@ public sealed class UpdateService
|
|||||||
{
|
{
|
||||||
try { Directory.Delete(backup, true); } catch { /* 占用时留到下次 */ }
|
try { Directory.Delete(backup, true); } catch { /* 占用时留到下次 */ }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 安装成功:把完整性记录写进模型目录,加载 dll 前会再抽查一次
|
||||||
|
try
|
||||||
|
{
|
||||||
|
ModelIntegrity.Write(target, model.Id, new ModelIntegrityFile
|
||||||
|
{
|
||||||
|
Id = model.Id,
|
||||||
|
Version = model.Version,
|
||||||
|
ManifestSha256 = computed.ManifestSha256,
|
||||||
|
FilesSha256 = computed.FilesSha256,
|
||||||
|
Files = computed.Files,
|
||||||
|
InstalledAt = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ"),
|
||||||
|
Source = _remote.DisplayName
|
||||||
|
});
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Console.Error.WriteLine($"写入完整性记录失败 {model.Id}: {ex.Message}");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
catch
|
catch
|
||||||
{
|
{
|
||||||
@@ -332,4 +349,7 @@ public sealed class UpdateService
|
|||||||
foreach (var c in Path.GetInvalidFileNameChars()) value = value.Replace(c, '-');
|
foreach (var c in Path.GetInvalidFileNameChars()) value = value.Replace(c, '-');
|
||||||
return value.Replace('/', '-').Replace(' ', '-');
|
return value.Replace('/', '-').Replace(' ', '-');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static string Short(string? hash)
|
||||||
|
=> string.IsNullOrEmpty(hash) ? "(空)" : hash!.Length <= 8 ? hash : hash[..8];
|
||||||
}
|
}
|
||||||
@@ -1,10 +1,10 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Globalization;
|
using System.Globalization;
|
||||||
|
|
||||||
namespace EarthModelStudio.Services;
|
namespace GC.Services;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 版本号工具:Release tag 有 v1.0.6 / GC-1.0.6 / 1.0.6 等写法,
|
/// 版本号工具:Release tag 有 v1.0.6 / GCL-1.0.6 / GC-1.0.6 / 1.0.6 等写法,
|
||||||
/// 统一成可比较的 Version 再排序,挑**版本号最高**的那个。
|
/// 统一成可比较的 Version 再排序,挑**版本号最高**的那个。
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static class VersionUtil
|
public static class VersionUtil
|
||||||
@@ -15,8 +15,9 @@ public static class VersionUtil
|
|||||||
if (string.IsNullOrWhiteSpace(tag)) return "";
|
if (string.IsNullOrWhiteSpace(tag)) return "";
|
||||||
var s = tag!.Trim();
|
var s = tag!.Trim();
|
||||||
|
|
||||||
// 去掉前缀:v / V / GC- / release-
|
// 去掉前缀:v / V / GC- / GCL- / release-
|
||||||
if (s.StartsWith("GC-", StringComparison.OrdinalIgnoreCase)) s = s[3..];
|
if (s.StartsWith("GCL-", StringComparison.OrdinalIgnoreCase)) s = s[4..];
|
||||||
|
else if (s.StartsWith("GC-", StringComparison.OrdinalIgnoreCase)) s = s[3..];
|
||||||
else if (s.StartsWith("release-", StringComparison.OrdinalIgnoreCase)) s = s[8..];
|
else if (s.StartsWith("release-", StringComparison.OrdinalIgnoreCase)) s = s[8..];
|
||||||
s = s.TrimStart('v', 'V');
|
s = s.TrimStart('v', 'V');
|
||||||
|
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
using System;
|
||||||
|
using System.IO;
|
||||||
|
|
||||||
|
namespace GC.Services;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 安全解压的统一入口(实现在 <see cref="SafeArchive"/>)。
|
||||||
|
/// 保留这个名字是因为模型源导入 / 启动器更新两处都在用,
|
||||||
|
/// 真正的校验逻辑集中在一处,避免两套实现走偏。
|
||||||
|
/// </summary>
|
||||||
|
public static class ZipSafety
|
||||||
|
{
|
||||||
|
public static void ExtractToDirectory(string zipPath, string destination)
|
||||||
|
{
|
||||||
|
if (!File.Exists(zipPath))
|
||||||
|
throw new FileNotFoundException("压缩包不存在", zipPath);
|
||||||
|
SafeArchive.ExtractToDirectory(zipPath, destination);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>只检查不落盘:给下载完成后的预检用。</summary>
|
||||||
|
public static SafeArchive.Inspection Inspect(string zipPath) => SafeArchive.Inspect(zipPath);
|
||||||
|
}
|
||||||
@@ -1,19 +1,22 @@
|
|||||||
using System;
|
using System;
|
||||||
|
using System.Threading.Tasks;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.IO;
|
using System.IO;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using Avalonia;
|
using Avalonia;
|
||||||
|
using Avalonia.Animation;
|
||||||
|
using Avalonia.Animation.Easings;
|
||||||
using Avalonia.Controls;
|
using Avalonia.Controls;
|
||||||
using Avalonia.Input;
|
using Avalonia.Input;
|
||||||
using Avalonia.Layout;
|
using Avalonia.Layout;
|
||||||
using Avalonia.Media;
|
using Avalonia.Media;
|
||||||
using Shapes = Avalonia.Controls.Shapes;
|
using Shapes = Avalonia.Controls.Shapes;
|
||||||
using Avalonia.VisualTree;
|
using Avalonia.VisualTree;
|
||||||
using EarthModelStudio.Models;
|
using GC.Models;
|
||||||
using EarthModelStudio.Services;
|
using GC.Services;
|
||||||
|
|
||||||
namespace EarthModelStudio.Views;
|
namespace GC.Views;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 模型窗口:**只做窗口宿主**。
|
/// 模型窗口:**只做窗口宿主**。
|
||||||
@@ -23,6 +26,7 @@ namespace EarthModelStudio.Views;
|
|||||||
public sealed class PlayerWindow : Window
|
public sealed class PlayerWindow : Window
|
||||||
{
|
{
|
||||||
private LoadedModel? _model;
|
private LoadedModel? _model;
|
||||||
|
private bool _closing;
|
||||||
private Button? _maximizeButton;
|
private Button? _maximizeButton;
|
||||||
private Border? _frame;
|
private Border? _frame;
|
||||||
private TextBlock? _titleText;
|
private TextBlock? _titleText;
|
||||||
@@ -167,7 +171,7 @@ public sealed class PlayerWindow : Window
|
|||||||
|
|
||||||
minimizeButton.Click += (_, _) => WindowState = WindowState.Minimized;
|
minimizeButton.Click += (_, _) => WindowState = WindowState.Minimized;
|
||||||
maximizeButton.Click += (_, _) => ToggleMaximize();
|
maximizeButton.Click += (_, _) => ToggleMaximize();
|
||||||
closeButton.Click += (_, _) => Close();
|
closeButton.Click += (_, _) => _ = CloseWithAnimationAsync();
|
||||||
_maximizeGlyph = maxBadge.Icon;
|
_maximizeGlyph = maxBadge.Icon;
|
||||||
_restoreGlyph = 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";
|
_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";
|
||||||
@@ -394,37 +398,23 @@ public sealed class PlayerWindow : Window
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ── 帮助窗口自建标题栏(带 ✕),与模型窗口同款配色 ──
|
// ── 帮助窗口自建标题栏(带 ✕),与模型窗口同款配色 ──
|
||||||
// 关闭键也用品红卡通圆底 + 矢量 ✕:文字符号在中文字体下常被裁切或基线偏移
|
// 纯矢量图标,无彩色圆底(与三个窗口按钮保持一致)
|
||||||
var helpBadgeShape = new Shapes.Ellipse
|
|
||||||
{
|
|
||||||
Width = 18, Height = 18,
|
|
||||||
Fill = new SolidColorBrush(Color.Parse("#FF7B7B")),
|
|
||||||
HorizontalAlignment = HorizontalAlignment.Center,
|
|
||||||
VerticalAlignment = VerticalAlignment.Center
|
|
||||||
};
|
|
||||||
var helpCross = new Shapes.Path
|
var helpCross = new Shapes.Path
|
||||||
{
|
{
|
||||||
Data = Geometry.Parse("M2,2 L8,8 M8,2 L2,8"),
|
Data = Geometry.Parse("M2,2 L8,8 M8,2 L2,8"),
|
||||||
Stroke = new SolidColorBrush(Color.Parse("#7A1F1F")),
|
Stroke = new SolidColorBrush(btnText),
|
||||||
StrokeThickness = 1.7,
|
StrokeThickness = 1.5,
|
||||||
StrokeLineCap = PenLineCap.Round,
|
StrokeLineCap = PenLineCap.Round,
|
||||||
Fill = null,
|
Fill = null,
|
||||||
Stretch = Stretch.None,
|
Stretch = Stretch.None,
|
||||||
Width = 9, Height = 9,
|
Width = 10, Height = 10,
|
||||||
HorizontalAlignment = HorizontalAlignment.Center,
|
HorizontalAlignment = HorizontalAlignment.Center,
|
||||||
VerticalAlignment = VerticalAlignment.Center
|
VerticalAlignment = VerticalAlignment.Center
|
||||||
};
|
};
|
||||||
var helpCrossLayer = new Grid
|
|
||||||
{
|
|
||||||
HorizontalAlignment = HorizontalAlignment.Center,
|
|
||||||
VerticalAlignment = VerticalAlignment.Center
|
|
||||||
};
|
|
||||||
helpCrossLayer.Children.Add(helpBadgeShape);
|
|
||||||
helpCrossLayer.Children.Add(helpCross);
|
|
||||||
|
|
||||||
var helpClose = new Button
|
var helpClose = new Button
|
||||||
{
|
{
|
||||||
Content = helpCrossLayer,
|
Content = helpCross,
|
||||||
Width = 34,
|
Width = 34,
|
||||||
Height = 26,
|
Height = 26,
|
||||||
Background = Brushes.Transparent,
|
Background = Brushes.Transparent,
|
||||||
@@ -438,14 +428,14 @@ public sealed class PlayerWindow : Window
|
|||||||
};
|
};
|
||||||
helpClose.PointerEntered += (_, _) =>
|
helpClose.PointerEntered += (_, _) =>
|
||||||
{
|
{
|
||||||
helpBadgeShape.Fill = new SolidColorBrush(Color.Parse("#FF9B9B"));
|
|
||||||
helpClose.Background = new SolidColorBrush(IsLight(frameBg)
|
helpClose.Background = new SolidColorBrush(IsLight(frameBg)
|
||||||
? Color.Parse("#EEF1F7") : Color.Parse("#1E2C46"));
|
? Color.Parse("#EEF1F7") : Color.Parse("#1E2C46"));
|
||||||
|
helpCross.Stroke = new SolidColorBrush(Colors.White);
|
||||||
};
|
};
|
||||||
helpClose.PointerExited += (_, _) =>
|
helpClose.PointerExited += (_, _) =>
|
||||||
{
|
{
|
||||||
helpBadgeShape.Fill = new SolidColorBrush(Color.Parse("#FF7B7B"));
|
|
||||||
helpClose.Background = Brushes.Transparent;
|
helpClose.Background = Brushes.Transparent;
|
||||||
|
helpCross.Stroke = new SolidColorBrush(btnText);
|
||||||
};
|
};
|
||||||
|
|
||||||
var helpTitle = new TextBlock
|
var helpTitle = new TextBlock
|
||||||
@@ -555,7 +545,7 @@ public sealed class PlayerWindow : Window
|
|||||||
switch (e.Key)
|
switch (e.Key)
|
||||||
{
|
{
|
||||||
case Key.Escape:
|
case Key.Escape:
|
||||||
Close();
|
_ = CloseWithAnimationAsync();
|
||||||
e.Handled = true;
|
e.Handled = true;
|
||||||
break;
|
break;
|
||||||
case Key.F11:
|
case Key.F11:
|
||||||
@@ -567,6 +557,30 @@ public sealed class PlayerWindow : Window
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <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)
|
private void OnClosed(object? sender, EventArgs e)
|
||||||
{
|
{
|
||||||
Content = null;
|
Content = null;
|
||||||
@@ -0,0 +1,838 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Diagnostics;
|
||||||
|
using System.IO;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text.RegularExpressions;
|
||||||
|
using System.Threading;
|
||||||
|
using GC.Services;
|
||||||
|
|
||||||
|
namespace GC.Savedog;
|
||||||
|
|
||||||
|
internal sealed class ApplyOptions
|
||||||
|
{
|
||||||
|
public string UpdateDir { get; set; } = "";
|
||||||
|
public string? InstallDir { get; set; }
|
||||||
|
public int WaitPid { get; set; }
|
||||||
|
public int TimeoutSeconds { get; set; } = 45;
|
||||||
|
public bool RequireSignature { get; set; } = true;
|
||||||
|
public bool DryRun { get; set; }
|
||||||
|
public bool Force { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 应用一次启动器更新:验签 → 校验 → 原子替换 → 启动 → 看护 → 成功清场 / 失败回滚。
|
||||||
|
/// 任何一步失败都不会留下「删了旧版又没有新版」的状态。
|
||||||
|
/// </summary>
|
||||||
|
internal sealed class Applier
|
||||||
|
{
|
||||||
|
private readonly ApplyOptions _options;
|
||||||
|
private readonly Log _log;
|
||||||
|
|
||||||
|
/// <summary>发布包里的启动器文件名:GC-1.0.9-win-amd64.exe。</summary>
|
||||||
|
private static readonly Regex VersionedExePattern = new(
|
||||||
|
@"^(?:GC|GCL)-\d+(?:\.\d+)+-[A-Za-z0-9]+-[A-Za-z0-9]+\.exe$",
|
||||||
|
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled);
|
||||||
|
|
||||||
|
public Applier(ApplyOptions options, Log log)
|
||||||
|
{
|
||||||
|
_options = options;
|
||||||
|
_log = log;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int Run()
|
||||||
|
{
|
||||||
|
var updateDir = Path.GetFullPath(_options.UpdateDir);
|
||||||
|
var requestPath = Path.Combine(updateDir, SavedogFiles.ApplyRequest);
|
||||||
|
|
||||||
|
if (!File.Exists(requestPath))
|
||||||
|
return Fail(updateDir, "找不到更新申请 " + SavedogFiles.ApplyRequest, 3,
|
||||||
|
"Update request not found: " + SavedogFiles.ApplyRequest);
|
||||||
|
|
||||||
|
var request = Json.Read<SavedogRequest>(requestPath);
|
||||||
|
if (request == null || string.IsNullOrWhiteSpace(request.Version))
|
||||||
|
return Fail(updateDir, "更新申请内容不完整", 3, "The update request is incomplete");
|
||||||
|
|
||||||
|
if (!ValidName(request.PackageName))
|
||||||
|
return Fail(updateDir, "更新包名不合法: " + request.PackageName, 3,
|
||||||
|
"Invalid package name: " + request.PackageName);
|
||||||
|
|
||||||
|
_log.Info($"开始应用 v{request.Version}({request.Rid},{request.PackageName})",
|
||||||
|
$"Starting apply of v{request.Version} ({request.Rid}, {request.PackageName})");
|
||||||
|
|
||||||
|
// 1. 等旧进程退出(否则 Windows 上文件还被占用)
|
||||||
|
if (_options.WaitPid > 0 && !WaitForExit(_options.WaitPid, TimeSpan.FromSeconds(60)))
|
||||||
|
_log.Warn($"等待进程 {_options.WaitPid} 退出超时,继续尝试",
|
||||||
|
$"Timed out waiting for process {_options.WaitPid} to exit; continuing anyway");
|
||||||
|
|
||||||
|
// 2. 安装目录定位与安全检查
|
||||||
|
var installDir = string.IsNullOrWhiteSpace(_options.InstallDir)
|
||||||
|
? Path.GetFullPath(Path.Combine(updateDir, request.InstallRelative))
|
||||||
|
: Path.GetFullPath(_options.InstallDir!);
|
||||||
|
|
||||||
|
if (!Directory.Exists(installDir))
|
||||||
|
return Fail(updateDir, "安装目录不存在: " + installDir, 4,
|
||||||
|
"Install directory does not exist: " + installDir);
|
||||||
|
|
||||||
|
if (!_options.Force && File.Exists(Path.Combine(installDir, "GC.sln")))
|
||||||
|
return Fail(updateDir, "检测到源码目录,拒绝在源码树里替换程序", 4,
|
||||||
|
"Source tree detected; refusing to replace files inside it");
|
||||||
|
|
||||||
|
// 3. 二次验签:不信任「启动器说它验过了」
|
||||||
|
var require = request.RequireSignature && SignatureKeyring.Enforced;
|
||||||
|
var manifestPath = Path.Combine(updateDir, request.ManifestPath);
|
||||||
|
var manifestText = File.Exists(manifestPath) ? File.ReadAllText(manifestPath) : null;
|
||||||
|
var verification = ManifestSignature.Verify(manifestText, require);
|
||||||
|
|
||||||
|
// 签名不对(被改过 / 密钥不认识)永远拒绝;仅「没有签名」在明确不强制时放行。
|
||||||
|
// 之前这里不看 require:即使调用方声明 requireSignature=false(开发态、测试),
|
||||||
|
// 未签名清单也会被当成验签失败直接拒掉。
|
||||||
|
var hostile = verification.Trust == ManifestTrust.Invalid;
|
||||||
|
if (hostile || (verification.IsRejected && require))
|
||||||
|
{
|
||||||
|
_log.Error($"清单验签失败({verification.Trust}):{verification.Error}",
|
||||||
|
$"Manifest signature check failed ({verification.Trust}): {verification.Error}");
|
||||||
|
return Refuse(updateDir, request, verification);
|
||||||
|
}
|
||||||
|
if (verification.IsRejected)
|
||||||
|
{
|
||||||
|
_log.Warn($"清单未签名,按调用方要求放行:{verification.Error}",
|
||||||
|
$"Manifest is unsigned; continuing as requested: {verification.Error}");
|
||||||
|
}
|
||||||
|
_log.Info($"清单可信度:{verification.Trust}" +
|
||||||
|
(verification.KeyId != null ? $"({verification.KeyId})" : ""),
|
||||||
|
$"Manifest trust: {verification.Trust}" +
|
||||||
|
(verification.KeyId != null ? $" ({verification.KeyId})" : ""));
|
||||||
|
|
||||||
|
// 4. 校验更新包
|
||||||
|
var zipPath = Path.Combine(updateDir, request.PackageZip);
|
||||||
|
if (!File.Exists(zipPath))
|
||||||
|
return Fail(updateDir, "更新包不存在: " + request.PackageZip, 5,
|
||||||
|
"Package not found: " + request.PackageZip);
|
||||||
|
|
||||||
|
var zipInfo = new FileInfo(zipPath);
|
||||||
|
if (request.PackageSize > 0 && zipInfo.Length != request.PackageSize)
|
||||||
|
return Fail(updateDir, $"更新包体积不符(期望 {request.PackageSize},实际 {zipInfo.Length})", 5,
|
||||||
|
$"Package size mismatch (expected {request.PackageSize}, got {zipInfo.Length})");
|
||||||
|
|
||||||
|
var actualSha = ContentHash.Sha256File(zipPath);
|
||||||
|
if (!string.IsNullOrWhiteSpace(request.PackageSha256) &&
|
||||||
|
!string.Equals(actualSha, request.PackageSha256, StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
return Fail(updateDir, "更新包 sha256 与清单不符,已丢弃", 5,
|
||||||
|
"Package sha256 does not match the manifest; discarded");
|
||||||
|
}
|
||||||
|
if (string.IsNullOrWhiteSpace(request.PackageSha256))
|
||||||
|
_log.Warn("清单没有提供 sha256,仅依赖签名与解压校验",
|
||||||
|
"Manifest has no sha256; relying on the signature and extraction checks only");
|
||||||
|
|
||||||
|
SafeArchive.Inspection inspection;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
inspection = SafeArchive.Inspect(zipPath);
|
||||||
|
_log.Info($"更新包检查通过:{inspection.Entries} 个条目," +
|
||||||
|
$"{inspection.UncompressedBytes / 1024 / 1024} MB,压缩比 {inspection.Ratio:0.0}:1",
|
||||||
|
$"Package inspection passed: {inspection.Entries} entries, " +
|
||||||
|
$"{inspection.UncompressedBytes / 1024 / 1024} MB, ratio {inspection.Ratio:0.0}:1");
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
return Fail(updateDir, "更新包安全性检查失败: " + ex.Message, 5,
|
||||||
|
"Package safety check failed: " + ex.Message);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5. 解压到暂存区(与安装目录同卷,后续 rename 才是原子的)
|
||||||
|
var stage = Path.Combine(updateDir, "stage");
|
||||||
|
ClearDirectory(stage);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
SafeArchive.ExtractToDirectory(zipPath, stage);
|
||||||
|
FlattenSingleDirectory(stage);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
ClearDirectory(stage);
|
||||||
|
return Fail(updateDir, "解压失败: " + ex.Message, 6, "Extraction failed: " + ex.Message);
|
||||||
|
}
|
||||||
|
|
||||||
|
var artifact = FindArtifact(stage, request.PackageName);
|
||||||
|
if (artifact == null)
|
||||||
|
{
|
||||||
|
ClearDirectory(stage);
|
||||||
|
return Fail(updateDir, "更新包里没有找到新版程序(" + request.PackageName + ")", 6,
|
||||||
|
"No new launcher found in the package (" + request.PackageName + ")");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 主程序:优先用清单里的包名,否则按已知名字挑一个(发布包是整目录,
|
||||||
|
// 里面同时有 GC-UI.exe / GC.UI.Server.exe / GC-SAVEDOG.exe,不能瞎猜第一个)。
|
||||||
|
var mainName = Path.GetFileName(artifact);
|
||||||
|
var mainTarget = Path.Combine(installDir, mainName);
|
||||||
|
|
||||||
|
if (_options.DryRun)
|
||||||
|
{
|
||||||
|
_log.Info($"[dry-run] 校验全部通过,将整目录安装到 {installDir}" +
|
||||||
|
$"({Directory.GetFileSystemEntries(stage).Length} 个顶层条目)",
|
||||||
|
$"[dry-run] All checks passed; would install the whole directory to {installDir} " +
|
||||||
|
$"({Directory.GetFileSystemEntries(stage).Length} top-level entries)");
|
||||||
|
ClearDirectory(stage);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
var previous = ReadLastGood(updateDir);
|
||||||
|
if (previous != null && SameVersion(previous.Version, request.Version) &&
|
||||||
|
(File.Exists(mainTarget) || Directory.Exists(mainTarget)))
|
||||||
|
{
|
||||||
|
// 同一版本重复下发:当成已安装,避免反复覆盖正在运行的文件
|
||||||
|
_log.Info($"v{request.Version} 已安装且上次启动正常,视为已安装",
|
||||||
|
$"v{request.Version} is already installed and started fine last time; treating as installed");
|
||||||
|
ClearDirectory(stage);
|
||||||
|
TryDelete(zipPath);
|
||||||
|
TryDelete(requestPath);
|
||||||
|
WriteState(updateDir, new SavedogState
|
||||||
|
{
|
||||||
|
Status = "applied",
|
||||||
|
Version = request.Version,
|
||||||
|
PackageName = mainName,
|
||||||
|
Verified = true,
|
||||||
|
Message = "目标版本已存在,无需替换"
|
||||||
|
});
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 6. 整目录替换:旧内容先搬到 backup,新内容就位;失败可原样还原。
|
||||||
|
// 只动程序文件,.GC(模型库 / 设置 / 更新目录)永远不碰。
|
||||||
|
var replaced = new List<(string Name, string? BackupPath)>();
|
||||||
|
if (!ReplaceInstallDirectory(stage, installDir, updateDir, replaced, out var replaceError))
|
||||||
|
{
|
||||||
|
RestoreFromBackup(installDir, replaced);
|
||||||
|
ClearDirectory(stage);
|
||||||
|
return Fail(updateDir, "安装失败: " + replaceError, 7, "Installation failed: " + replaceError);
|
||||||
|
}
|
||||||
|
_log.Info($"新版已就位:{mainName}(替换 {replaced.Count} 个条目)",
|
||||||
|
$"New version in place: {mainName} (replaced {replaced.Count} entries)");
|
||||||
|
|
||||||
|
// 7. 启动并看护
|
||||||
|
StartupHealth.Clear(updateDir);
|
||||||
|
|
||||||
|
Process? child;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
child = Launch(mainTarget);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
child = null;
|
||||||
|
_log.Error("启动新版失败: " + ex.Message,
|
||||||
|
"Failed to start the new version: " + ex.Message);
|
||||||
|
}
|
||||||
|
|
||||||
|
var healthy = child != null && WaitForHealth(updateDir, request.Version, child,
|
||||||
|
TimeSpan.FromSeconds(_options.TimeoutSeconds));
|
||||||
|
|
||||||
|
if (healthy)
|
||||||
|
{
|
||||||
|
_log.Info($"v{request.Version} 启动正常,更新完成",
|
||||||
|
$"v{request.Version} started successfully; update complete");
|
||||||
|
CleanupBackup(updateDir);
|
||||||
|
WriteLastGood(updateDir, request.Version, mainName);
|
||||||
|
WriteState(updateDir, new SavedogState
|
||||||
|
{
|
||||||
|
Status = "applied",
|
||||||
|
Version = request.Version,
|
||||||
|
PreviousVersion = previous?.Version,
|
||||||
|
PackageName = mainName,
|
||||||
|
Verified = true,
|
||||||
|
Message = "更新已应用"
|
||||||
|
});
|
||||||
|
ClearDirectory(stage);
|
||||||
|
TryDelete(zipPath);
|
||||||
|
TryDelete(requestPath);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 8. 回滚:撤掉新装的文件,把备份原样搬回
|
||||||
|
_log.Error($"v{request.Version} 启动后未通过健康检查({_options.TimeoutSeconds}s),开始回滚",
|
||||||
|
$"v{request.Version} did not pass the health check after {_options.TimeoutSeconds}s; rolling back");
|
||||||
|
TryKill(child);
|
||||||
|
var restored = RestoreFromBackup(installDir, replaced);
|
||||||
|
_log.Info(restored ? "已还原为更新前的文件" : "部分文件未能还原,请手动重新安装",
|
||||||
|
restored ? "Restored the pre-update files" : "Some files could not be restored; please reinstall manually");
|
||||||
|
|
||||||
|
var relaunched = restored && TryLaunchPrevious(installDir, updateDir, previous, request.PlatformLabel);
|
||||||
|
WriteState(updateDir, new SavedogState
|
||||||
|
{
|
||||||
|
Status = "rolledback",
|
||||||
|
Version = request.Version,
|
||||||
|
PreviousVersion = previous?.Version,
|
||||||
|
PackageName = mainName,
|
||||||
|
Verified = true,
|
||||||
|
Message = relaunched
|
||||||
|
? "新版本未通过启动检查,已回滚到上一个版本"
|
||||||
|
: "新版本未通过启动检查,已移除;未找到可回滚的旧版本,请手动重新安装"
|
||||||
|
});
|
||||||
|
|
||||||
|
ClearDirectory(stage);
|
||||||
|
TryDelete(zipPath);
|
||||||
|
TryDelete(requestPath);
|
||||||
|
return 8;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ 校验辅助
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 包名合法性:只允许「一个文件名」,杜绝 `../` 之类的路径穿越。
|
||||||
|
///
|
||||||
|
/// 不能只认 .app / .exe —— Linux 的启动器没有扩展名
|
||||||
|
/// (GC-1.0.9-linux-amd64),按旧规则会被直接判成非法包名、更新永远失败。
|
||||||
|
/// </summary>
|
||||||
|
private static bool ValidName(string name)
|
||||||
|
=> SafeNamePattern.IsMatch(name);
|
||||||
|
|
||||||
|
private static readonly Regex SafeNamePattern = new(
|
||||||
|
@"^[A-Za-z0-9][A-Za-z0-9._-]{0,198}$",
|
||||||
|
RegexOptions.CultureInvariant | RegexOptions.Compiled);
|
||||||
|
|
||||||
|
private static bool WaitForExit(int pid, TimeSpan timeout)
|
||||||
|
{
|
||||||
|
var deadline = DateTime.UtcNow + timeout;
|
||||||
|
while (DateTime.UtcNow < deadline)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var process = Process.GetProcessById(pid);
|
||||||
|
if (process.HasExited) return true;
|
||||||
|
}
|
||||||
|
catch (ArgumentException) { return true; } // 进程已不存在
|
||||||
|
catch { return true; }
|
||||||
|
Thread.Sleep(200);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void FlattenSingleDirectory(string stage)
|
||||||
|
{
|
||||||
|
var entries = Directory.GetFileSystemEntries(stage);
|
||||||
|
if (entries.Length != 1 || !Directory.Exists(entries[0])) return;
|
||||||
|
var inner = entries[0];
|
||||||
|
if (Path.GetFileName(inner).EndsWith(".app", StringComparison.OrdinalIgnoreCase)) return;
|
||||||
|
|
||||||
|
var temp = stage + "-flat";
|
||||||
|
if (Directory.Exists(temp)) Directory.Delete(temp, true);
|
||||||
|
Directory.Move(inner, temp);
|
||||||
|
Directory.Delete(stage, true);
|
||||||
|
Directory.Move(temp, stage);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 在解压结果里找主程序。
|
||||||
|
///
|
||||||
|
/// 发布包是「整目录」结构(exe + dll + data/),同一层可能有好几个 exe
|
||||||
|
/// (GC-UI / GC.UI.Server / GC-SAVEDOG / createdump),必须按固定优先级挑,
|
||||||
|
/// 不能取第一个 —— 否则会把守护进程或调试辅助程序当成启动器拉起来。
|
||||||
|
/// </summary>
|
||||||
|
private static string? FindArtifact(string stage, string packageName)
|
||||||
|
{
|
||||||
|
if (!string.IsNullOrWhiteSpace(packageName))
|
||||||
|
{
|
||||||
|
var named = Path.Combine(stage, packageName);
|
||||||
|
if (File.Exists(named) || Directory.Exists(named)) return named;
|
||||||
|
}
|
||||||
|
|
||||||
|
var entries = Directory.GetFileSystemEntries(stage);
|
||||||
|
var byName = entries
|
||||||
|
.Where(e => File.Exists(e))
|
||||||
|
.OrderByDescending(e => MainExecutablePriority(Path.GetFileName(e)))
|
||||||
|
.ThenBy(e => Path.GetFileName(e), StringComparer.OrdinalIgnoreCase)
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
var best = byName.FirstOrDefault(e => MainExecutablePriority(Path.GetFileName(e)) > 0);
|
||||||
|
if (best != null) return best;
|
||||||
|
|
||||||
|
// macOS:.app 目录本身就是「可执行单元」
|
||||||
|
foreach (var entry in entries)
|
||||||
|
{
|
||||||
|
if (Directory.Exists(entry) &&
|
||||||
|
Path.GetFileName(entry).EndsWith(".app", StringComparison.OrdinalIgnoreCase))
|
||||||
|
return entry;
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>主程序优先级:数字越大越优先,0 表示不是主程序。</summary>
|
||||||
|
private static int MainExecutablePriority(string fileName)
|
||||||
|
{
|
||||||
|
if (!fileName.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) return 0;
|
||||||
|
|
||||||
|
// 发布包把启动器改名成 GCL-<版本>-<系统>-<架构>.exe(旧包是 GC-),先按这个模式认出来。
|
||||||
|
if (VersionedExePattern.IsMatch(fileName)) return 110;
|
||||||
|
|
||||||
|
var name = Path.GetFileNameWithoutExtension(fileName);
|
||||||
|
return name switch
|
||||||
|
{
|
||||||
|
"GC-UI" => 100,
|
||||||
|
"GC" => 90,
|
||||||
|
"GC.UI.Server" => 80,
|
||||||
|
// 守护进程 / 调试辅助 / 运行时工具:永远不当主程序
|
||||||
|
"GC-SAVEDOG" => 0,
|
||||||
|
"createdump" => 0,
|
||||||
|
"singlefilehost" => 0,
|
||||||
|
_ => 10
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ 启动与看护
|
||||||
|
|
||||||
|
private Process? Launch(string target)
|
||||||
|
{
|
||||||
|
if (Directory.Exists(target))
|
||||||
|
{
|
||||||
|
// .app:优先直接启动内部可执行文件,这样才能拿到 pid 做看护
|
||||||
|
var macOs = Path.Combine(target, "Contents", "MacOS");
|
||||||
|
if (Directory.Exists(macOs))
|
||||||
|
{
|
||||||
|
var exe = Directory.GetFiles(macOs)
|
||||||
|
.OrderByDescending(f => Path.GetFileName(f) == "GC")
|
||||||
|
.FirstOrDefault();
|
||||||
|
if (exe != null)
|
||||||
|
{
|
||||||
|
MakeExecutable(exe);
|
||||||
|
return StartProcess(exe, Path.GetDirectoryName(exe)!);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
MakeExecutable(Path.Combine(target, "Contents", "MacOS", "GC"));
|
||||||
|
var psi = new ProcessStartInfo("open") { UseShellExecute = false };
|
||||||
|
psi.ArgumentList.Add("-n");
|
||||||
|
psi.ArgumentList.Add(target);
|
||||||
|
return Process.Start(psi);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (OperatingSystem.IsWindows() || OperatingSystem.IsLinux() || OperatingSystem.IsMacOS())
|
||||||
|
{
|
||||||
|
if (!OperatingSystem.IsWindows()) MakeExecutable(target);
|
||||||
|
return StartProcess(target, Path.GetDirectoryName(target)!);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Process? StartProcess(string exe, string workingDirectory)
|
||||||
|
{
|
||||||
|
var psi = new ProcessStartInfo(exe)
|
||||||
|
{
|
||||||
|
UseShellExecute = false,
|
||||||
|
WorkingDirectory = workingDirectory
|
||||||
|
};
|
||||||
|
return Process.Start(psi);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void MakeExecutable(string path)
|
||||||
|
{
|
||||||
|
if (OperatingSystem.IsWindows()) return;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (!File.Exists(path)) return;
|
||||||
|
var mode = File.GetUnixFileMode(path);
|
||||||
|
File.SetUnixFileMode(path, mode | UnixFileMode.UserExecute |
|
||||||
|
UnixFileMode.GroupExecute |
|
||||||
|
UnixFileMode.OtherExecute);
|
||||||
|
}
|
||||||
|
catch { }
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool WaitForHealth(string updateDir, string version, Process child, TimeSpan timeout)
|
||||||
|
{
|
||||||
|
var deadline = DateTime.UtcNow + timeout;
|
||||||
|
while (DateTime.UtcNow < deadline)
|
||||||
|
{
|
||||||
|
var health = StartupHealth.Read(updateDir);
|
||||||
|
if (health != null && health.Ok && SameVersion(health.Version, version))
|
||||||
|
{
|
||||||
|
_log.Info($"收到健康标记(pid {health.Pid})", $"Health marker received (pid {health.Pid})");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (child.HasExited)
|
||||||
|
{
|
||||||
|
_log.Error($"新版进程已退出(退出码 {child.ExitCode})",
|
||||||
|
$"The new process exited (code {child.ExitCode})");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
Thread.Sleep(250);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 超时但进程还活着:可能是尚未写入健康标记的旧构建,谨慎放行
|
||||||
|
if (!child.HasExited)
|
||||||
|
{
|
||||||
|
_log.Warn("未收到健康标记,但进程仍在运行,按成功处理",
|
||||||
|
"No health marker, but the process is still running; treating as success");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool SameVersion(string a, string b)
|
||||||
|
=> string.Equals(Normalize(a), Normalize(b), StringComparison.OrdinalIgnoreCase);
|
||||||
|
|
||||||
|
private static string Normalize(string version)
|
||||||
|
{
|
||||||
|
var trimmed = version.Trim().TrimStart('v', 'V');
|
||||||
|
var parts = trimmed.Split('.');
|
||||||
|
var numbers = new List<string>();
|
||||||
|
foreach (var part in parts)
|
||||||
|
{
|
||||||
|
if (!int.TryParse(part, out var n)) break;
|
||||||
|
numbers.Add(n.ToString());
|
||||||
|
}
|
||||||
|
while (numbers.Count > 0 && numbers[^1] == "0") numbers.RemoveAt(numbers.Count - 1);
|
||||||
|
return numbers.Count == 0 ? trimmed : string.Join('.', numbers);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void TryKill(Process? process)
|
||||||
|
{
|
||||||
|
if (process == null) return;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (!process.HasExited) process.Kill(entireProcessTree: true);
|
||||||
|
}
|
||||||
|
catch { }
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ 整目录安装 / 回滚
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 把 <paramref name="stage"/> 的内容替换进 <paramref name="installDir"/>。
|
||||||
|
///
|
||||||
|
/// 发布包是「整目录」(启动器 + 后端运行时 + Flutter 前端资源),只搬一个 exe 会留下
|
||||||
|
/// 旧后端 / 旧界面,所以这里按目录整体替换:
|
||||||
|
/// 1. 安装目录里「新版没有」的条目 → 移到 backup(旧版本残留,如上一版的旧文件名);
|
||||||
|
/// 2. 与新版同名的条目 → 先移到 backup,再把新版放进来(覆盖正在被占用的文件会失败,
|
||||||
|
/// 这种情况直接报错并还原,绝不留下半新半旧的目录);
|
||||||
|
/// 3. `.GC` 只合并 `bin/`(非本体文件),其余子目录与更新目录自身一律跳过。
|
||||||
|
///
|
||||||
|
/// 返回 false 时调用方应调用 <see cref="RestoreFromBackup"/> 还原。
|
||||||
|
/// </summary>
|
||||||
|
private bool ReplaceInstallDirectory(string stage, string installDir, string updateDir,
|
||||||
|
List<(string Name, string? BackupPath)> replaced, out string? error)
|
||||||
|
{
|
||||||
|
error = null;
|
||||||
|
var backupDir = Path.Combine(updateDir, "backup");
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Directory.CreateDirectory(installDir);
|
||||||
|
ClearDirectory(backupDir);
|
||||||
|
Directory.CreateDirectory(backupDir);
|
||||||
|
|
||||||
|
var incoming = new List<string>();
|
||||||
|
foreach (var entry in Directory.GetFileSystemEntries(stage))
|
||||||
|
{
|
||||||
|
var name = Path.GetFileName(entry);
|
||||||
|
if (string.Equals(name, ".GC", StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
// .GC 里只有 bin/ 属于程序本体(守护进程这类「非本体」文件),
|
||||||
|
// 其余(config / model / cache / update / logs / safedog)是用户数据,
|
||||||
|
// 整目录替换时必须原地不动。
|
||||||
|
MergeGcBin(entry, installDir, backupDir, replaced);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (IsProtected(name))
|
||||||
|
{
|
||||||
|
// 例如 GC-SAVEDOG.exe:本进程正在运行,Windows 上无法替换。
|
||||||
|
// 保留旧版守护进程即可,它下次启动会随包里的新版本一起被更新。
|
||||||
|
_log.Warn($"跳过受保护文件,保留旧版本:{name}",
|
||||||
|
$"Skipping protected file, keeping the old one: {name}");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
incoming.Add(entry);
|
||||||
|
}
|
||||||
|
var incomingNames = new HashSet<string>(
|
||||||
|
incoming.Select(e => Path.GetFileName(e)), StringComparer.OrdinalIgnoreCase);
|
||||||
|
|
||||||
|
// 1. 旧版独有的条目先清走(保留在 backup 里以便回滚)
|
||||||
|
foreach (var entry in Directory.GetFileSystemEntries(installDir))
|
||||||
|
{
|
||||||
|
var name = Path.GetFileName(entry);
|
||||||
|
if (incomingNames.Contains(name)) continue;
|
||||||
|
if (IsProtected(name)) continue;
|
||||||
|
if (IsSameOrInside(entry, updateDir)) continue;
|
||||||
|
|
||||||
|
var target = Path.Combine(backupDir, name);
|
||||||
|
MoveEntry(entry, target);
|
||||||
|
replaced.Add((name, target));
|
||||||
|
_log.Info("旧版残留已备份: " + name, "Old leftover backed up: " + name);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 同名条目:旧 → backup,新 → 安装目录
|
||||||
|
foreach (var entry in incoming)
|
||||||
|
{
|
||||||
|
var name = Path.GetFileName(entry);
|
||||||
|
var target = Path.Combine(installDir, name);
|
||||||
|
var backup = Path.Combine(backupDir, name);
|
||||||
|
|
||||||
|
if (File.Exists(target) || Directory.Exists(target))
|
||||||
|
{
|
||||||
|
MoveEntry(target, backup);
|
||||||
|
replaced.Add((name, backup));
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
// 纯新增:回滚时直接删掉,没有备份可还原
|
||||||
|
replaced.Add((name, null));
|
||||||
|
}
|
||||||
|
|
||||||
|
MoveEntry(entry, target);
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
error = ex.Message;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 合并新包里的 <c>.GC/bin</c>:只搬这一层文件,不动 .GC 下的用户数据。
|
||||||
|
///
|
||||||
|
/// 守护进程放在这里(而不是安装目录根)是为了「非本体文件全部收进 .GC/bin」;
|
||||||
|
/// 但正在运行的是 <c>.GC/safedog</c> 里的副本,所以这里的文件可以安全替换。
|
||||||
|
/// </summary>
|
||||||
|
private void MergeGcBin(string stageGc, string installDir, string backupDir,
|
||||||
|
List<(string Name, string? BackupPath)> replaced)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var bin = Path.Combine(stageGc, "bin");
|
||||||
|
if (!Directory.Exists(bin)) return;
|
||||||
|
|
||||||
|
var relBin = Path.Combine(".GC", "bin");
|
||||||
|
var targetBin = Path.Combine(installDir, relBin);
|
||||||
|
Directory.CreateDirectory(targetBin);
|
||||||
|
|
||||||
|
foreach (var file in Directory.GetFiles(bin))
|
||||||
|
{
|
||||||
|
var name = Path.GetFileName(file);
|
||||||
|
var rel = Path.Combine(relBin, name);
|
||||||
|
var target = Path.Combine(targetBin, name);
|
||||||
|
var backup = Path.Combine(backupDir, ".GC-bin", name);
|
||||||
|
|
||||||
|
if (File.Exists(target))
|
||||||
|
{
|
||||||
|
MoveEntry(target, backup);
|
||||||
|
replaced.Add((rel, backup));
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
replaced.Add((rel, null));
|
||||||
|
}
|
||||||
|
|
||||||
|
MoveEntry(file, target);
|
||||||
|
_log.Info("已更新非本体文件: " + rel, "Updated non-core file: " + rel);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_log.Warn($"合并 .GC/bin 失败(继续使用已有版本):{ex.Message}",
|
||||||
|
$"Failed to merge .GC/bin (keeping the existing one): {ex.Message}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 把备份里的条目原样搬回安装目录,撤掉新装的内容。
|
||||||
|
/// <paramref name="BackupPath"/> 为 null 表示这一项是新包里独有的(没有旧版本),
|
||||||
|
/// 回滚时只需要删掉。
|
||||||
|
/// </summary>
|
||||||
|
private bool RestoreFromBackup(string installDir, List<(string Name, string? BackupPath)> replaced)
|
||||||
|
{
|
||||||
|
var ok = true;
|
||||||
|
foreach (var (name, backup) in replaced)
|
||||||
|
{
|
||||||
|
var target = Path.Combine(installDir, name);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
// 先撤掉新版(新包里独有的文件也要删干净,否则回滚后目录里新旧混杂)
|
||||||
|
DeleteEntry(target);
|
||||||
|
|
||||||
|
if (string.IsNullOrWhiteSpace(backup) ||
|
||||||
|
(!File.Exists(backup) && !Directory.Exists(backup)))
|
||||||
|
continue;
|
||||||
|
|
||||||
|
MoveEntry(backup, target);
|
||||||
|
_log.Info("已还原: " + name, "Restored: " + name);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
ok = false;
|
||||||
|
_log.Warn($"还原 {name} 失败: {ex.Message}", $"Failed to restore {name}: {ex.Message}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ok;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>更新成功:删掉整份备份,不再占用磁盘。</summary>
|
||||||
|
private void CleanupBackup(string updateDir)
|
||||||
|
{
|
||||||
|
var backupDir = Path.Combine(updateDir, "backup");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (Directory.Exists(backupDir)) Directory.Delete(backupDir, true);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_log.Warn("清理备份失败: " + ex.Message, "Failed to clean up the backup: " + ex.Message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 安装目录里不该被更新碰的东西:
|
||||||
|
/// · .GC —— 模型库、设置、日志、更新目录本身都在这里(只有 bin/ 由 MergeGcBin 单独处理);
|
||||||
|
/// · GC-SAVEDOG.exe —— 本进程正在运行,Windows 上无法替换。
|
||||||
|
/// </summary>
|
||||||
|
private static bool IsProtected(string name)
|
||||||
|
{
|
||||||
|
if (string.Equals(name, ".GC", StringComparison.OrdinalIgnoreCase)) return true;
|
||||||
|
var self = Environment.ProcessPath;
|
||||||
|
if (!string.IsNullOrWhiteSpace(self) &&
|
||||||
|
string.Equals(name, Path.GetFileName(self!), StringComparison.OrdinalIgnoreCase))
|
||||||
|
return true;
|
||||||
|
return string.Equals(name, "backup", StringComparison.OrdinalIgnoreCase);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsSameOrInside(string path, string root)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var full = Path.GetFullPath(path).TrimEnd(Path.DirectorySeparatorChar);
|
||||||
|
var rootFull = Path.GetFullPath(root).TrimEnd(Path.DirectorySeparatorChar);
|
||||||
|
return full.Equals(rootFull, StringComparison.OrdinalIgnoreCase) ||
|
||||||
|
full.StartsWith(rootFull + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase);
|
||||||
|
}
|
||||||
|
catch { return false; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>移动条目;跨卷或目标占用时退回「复制 + 删除」。</summary>
|
||||||
|
private static void MoveEntry(string from, string to)
|
||||||
|
{
|
||||||
|
var parent = Path.GetDirectoryName(to);
|
||||||
|
if (!string.IsNullOrWhiteSpace(parent)) Directory.CreateDirectory(parent);
|
||||||
|
|
||||||
|
if (Directory.Exists(from))
|
||||||
|
{
|
||||||
|
Directory.Move(from, to);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.Move(from, to, overwrite: true);
|
||||||
|
}
|
||||||
|
catch (IOException)
|
||||||
|
{
|
||||||
|
File.Copy(from, to, overwrite: true);
|
||||||
|
File.Delete(from);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>删除文件或目录,失败时抛出(由调用方决定是否回滚)。</summary>
|
||||||
|
private static void DeleteEntry(string path)
|
||||||
|
{
|
||||||
|
if (Directory.Exists(path)) Directory.Delete(path, true);
|
||||||
|
else if (File.Exists(path)) File.Delete(path);
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool TryLaunchPrevious(string installDir, string updateDir, LastGoodVersion? lastGood,
|
||||||
|
string platformLabel)
|
||||||
|
{
|
||||||
|
// 优先用上次成功启动的主程序;否则按优先级在安装目录里找
|
||||||
|
var candidates = new List<string>();
|
||||||
|
if (lastGood != null && !string.IsNullOrWhiteSpace(lastGood.PackageName))
|
||||||
|
candidates.Add(Path.Combine(installDir, lastGood.PackageName));
|
||||||
|
|
||||||
|
foreach (var entry in Directory.GetFileSystemEntries(installDir))
|
||||||
|
{
|
||||||
|
var name = Path.GetFileName(entry);
|
||||||
|
if (IsProtected(name)) continue;
|
||||||
|
if (MainExecutablePriority(name) > 0) candidates.Add(entry);
|
||||||
|
else if (Directory.Exists(entry) &&
|
||||||
|
name.EndsWith(".app", StringComparison.OrdinalIgnoreCase))
|
||||||
|
candidates.Add(entry);
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var candidate in candidates.Distinct(StringComparer.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
if (!File.Exists(candidate) && !Directory.Exists(candidate)) continue;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Launch(candidate);
|
||||||
|
_log.Info("已回滚启动: " + Path.GetFileName(candidate),
|
||||||
|
"Rolled back and started: " + Path.GetFileName(candidate));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_log.Warn($"回滚启动失败 {Path.GetFileName(candidate)}: {ex.Message}",
|
||||||
|
$"Failed to start rollback candidate {Path.GetFileName(candidate)}: {ex.Message}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ 状态文件
|
||||||
|
|
||||||
|
private void WriteState(string updateDir, SavedogState state)
|
||||||
|
{
|
||||||
|
try { Json.Write(Path.Combine(updateDir, SavedogFiles.State), state); }
|
||||||
|
catch (Exception ex) { _log.Warn("写状态失败: " + ex.Message, "Failed to write state: " + ex.Message); }
|
||||||
|
}
|
||||||
|
|
||||||
|
private int Fail(string updateDir, string message, int code, string? messageEn = null)
|
||||||
|
{
|
||||||
|
_log.Error(message, messageEn ?? message);
|
||||||
|
WriteState(updateDir, new SavedogState { Status = "failed", Message = message });
|
||||||
|
return code;
|
||||||
|
}
|
||||||
|
|
||||||
|
private int Refuse(string updateDir, SavedogRequest request, ManifestVerification verification)
|
||||||
|
{
|
||||||
|
WriteState(updateDir, new SavedogState
|
||||||
|
{
|
||||||
|
Status = "refused",
|
||||||
|
Version = request.Version,
|
||||||
|
PackageName = request.PackageName,
|
||||||
|
Verified = false,
|
||||||
|
Message = $"清单验签失败:{verification.Error}"
|
||||||
|
});
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static LastGoodVersion? ReadLastGood(string updateDir)
|
||||||
|
=> Json.Read<LastGoodVersion>(Path.Combine(updateDir, SavedogFiles.LastGood));
|
||||||
|
|
||||||
|
private static void WriteLastGood(string updateDir, string version, string packageName)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Json.Write(Path.Combine(updateDir, SavedogFiles.LastGood), new LastGoodVersion
|
||||||
|
{
|
||||||
|
Version = version,
|
||||||
|
PackageName = packageName
|
||||||
|
});
|
||||||
|
}
|
||||||
|
catch { }
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void ClearDirectory(string dir)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (Directory.Exists(dir)) Directory.Delete(dir, true);
|
||||||
|
}
|
||||||
|
catch { }
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void TryDelete(string path)
|
||||||
|
{
|
||||||
|
try { if (File.Exists(path)) File.Delete(path); } catch { }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<!--
|
||||||
|
GC-SAVEDOG —— 启动器更新守护进程。
|
||||||
|
|
||||||
|
为什么不把替换逻辑留在启动器里:
|
||||||
|
· 启动器正在运行,Windows 上无法覆盖自己的 exe;
|
||||||
|
· 覆盖失败(断电 / 占用 / 权限)时启动器已经退出,没人能回滚;
|
||||||
|
· 更新逻辑需要访问私钥验签,放在独立的最小进程里更容易审计。
|
||||||
|
|
||||||
|
本进程只做四件事:验签 → 校验 → 替换 → 看护(不健康就回滚)。
|
||||||
|
它不引用 Avalonia,也不引用启动器程序集,源码里只链接 GC/src/Security/ 下的
|
||||||
|
安全原语,保证「校验逻辑与启动器完全同一份实现」。
|
||||||
|
-->
|
||||||
|
<PropertyGroup>
|
||||||
|
<OutputType>Exe</OutputType>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<RootNamespace>GC.Savedog</RootNamespace>
|
||||||
|
<AssemblyName>GC-SAVEDOG</AssemblyName>
|
||||||
|
<InvariantGlobalization>true</InvariantGlobalization>
|
||||||
|
|
||||||
|
<!--
|
||||||
|
裁剪发布:自包含单文件不裁剪约 70MB,裁剪后 14MB 左右。
|
||||||
|
守护进程要跟着更新包一起下发,体积直接影响下载与校验时间。
|
||||||
|
|
||||||
|
裁剪的前提是**不用运行时反射**:JSON 全部走 SavedogJsonContext 的源生成类型信息
|
||||||
|
(见 SavedogJson.cs)。若给这里新加类型却忘了注册,未裁剪的调试构建看不出来,
|
||||||
|
只有发布产物会在运行时报 NotSupportedException —— 测试用例里有一次真实 apply,
|
||||||
|
会覆盖到。
|
||||||
|
-->
|
||||||
|
<PublishTrimmed>true</PublishTrimmed>
|
||||||
|
<TrimMode>full</TrimMode>
|
||||||
|
<JsonSerializerIsReflectionEnabledByDefault>false</JsonSerializerIsReflectionEnabledByDefault>
|
||||||
|
|
||||||
|
<!-- 只保留必要的卫星资源,裁剪后再压一层体积 -->
|
||||||
|
<SatelliteResourceLanguages>en</SatelliteResourceLanguages>
|
||||||
|
<DebugType>none</DebugType>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<!-- 应用器测试要直接构造 Applier(internal):只对测试程序集放开可见性 -->
|
||||||
|
<InternalsVisibleTo Include="GC.Savedog.Tests" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<!-- 与启动器共用同一份安全实现,避免两套逻辑各说各话。
|
||||||
|
ManifestLoader 依赖启动器的 RepoVersion 模型,守护进程不需要,排除。 -->
|
||||||
|
<Compile Include="..\GC\src\Security\**\*.cs" Exclude="..\GC\src\Security\ManifestLoader.cs" LinkBase="Security" />
|
||||||
|
<Compile Include="..\GC\src\Services\Json.cs" Link="Shared\Json.cs" />
|
||||||
|
<!-- 与启动器共用同一份双语日志实现,保证 .GC/logs 里格式一致 -->
|
||||||
|
<Compile Include="..\GC\src\Services\GcLog.cs" Link="Shared\GcLog.cs" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
using System;
|
||||||
|
using GC.Services;
|
||||||
|
|
||||||
|
namespace GC.Savedog;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 守护进程的日志入口,实际写入 <see cref="GcLog"/>:控制台 + <c>.GC/logs</c> 下的
|
||||||
|
/// <c>gc-YYYYMMDD.log</c>(中文)与 <c>gc-YYYYMMDD.en.log</c>(英文)。
|
||||||
|
///
|
||||||
|
/// 每条日志都必须同时给中英两份文案 —— 用户反馈问题时直接发对应语言的文件。
|
||||||
|
/// </summary>
|
||||||
|
internal sealed class Log
|
||||||
|
{
|
||||||
|
public Log(string? dir)
|
||||||
|
{
|
||||||
|
if (!string.IsNullOrWhiteSpace(dir)) GcLog.Init(dir);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Info(string zh, string en) => GcLog.Info(zh, en);
|
||||||
|
public void Warn(string zh, string en) => GcLog.Warn(zh, en);
|
||||||
|
public void Error(string zh, string en) => GcLog.Error(zh, en);
|
||||||
|
}
|
||||||
@@ -0,0 +1,350 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.IO;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Security.Cryptography;
|
||||||
|
using System.Text;
|
||||||
|
using System.Text.Json;
|
||||||
|
using GC.Services;
|
||||||
|
|
||||||
|
namespace GC.Savedog;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// GC-SAVEDOG 命令行。
|
||||||
|
///
|
||||||
|
/// GC-SAVEDOG apply --update <.GC/update> [--install <dir>] [--wait-pid N]
|
||||||
|
/// [--timeout 45] [--dry-run] [--json]
|
||||||
|
/// GC-SAVEDOG verify --manifest <version.json> [--require 1] [--json]
|
||||||
|
/// GC-SAVEDOG verify-model --dir <model/<id>> --id <id> [--json]
|
||||||
|
/// GC-SAVEDOG keygen [--out .signing] [--key-id gc-2026-11]
|
||||||
|
/// GC-SAVEDOG sign --manifest <version.json> [--key .signing/gc-signing.pem]
|
||||||
|
/// [--key-id ...] [--out <file>]
|
||||||
|
/// GC-SAVEDOG status --update <.GC/update> [--json]
|
||||||
|
/// </summary>
|
||||||
|
internal static class Program
|
||||||
|
{
|
||||||
|
private const string DefaultKeyId = "gc-2026-12";
|
||||||
|
private const string DefaultKeyPath = ".signing/gc-signing.pem";
|
||||||
|
|
||||||
|
private static int Main(string[] args)
|
||||||
|
{
|
||||||
|
try { Console.OutputEncoding = Encoding.UTF8; } catch { }
|
||||||
|
|
||||||
|
// 必须在任何 Json.Read/Write 之前接上源生成上下文(裁剪构建必需)
|
||||||
|
SavedogJson.Initialize();
|
||||||
|
|
||||||
|
if (args.Length == 0 || args[0] is "-h" or "--help" or "help")
|
||||||
|
{
|
||||||
|
Help();
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
var command = args[0].ToLowerInvariant();
|
||||||
|
var rest = args.Skip(1).ToArray();
|
||||||
|
var options = Parse(rest);
|
||||||
|
|
||||||
|
return command switch
|
||||||
|
{
|
||||||
|
"apply" => Apply(options),
|
||||||
|
"verify" => Verify(options),
|
||||||
|
"verify-model" => VerifyModel(options),
|
||||||
|
"keygen" => Keygen(options),
|
||||||
|
"sign" => Sign(options),
|
||||||
|
"status" => Status(options),
|
||||||
|
"version" or "--version" => PrintVersion(),
|
||||||
|
_ => Unknown(command)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ apply
|
||||||
|
|
||||||
|
private static int Apply(Dictionary<string, string> options)
|
||||||
|
{
|
||||||
|
var updateDir = Option(options, "update", "");
|
||||||
|
if (string.IsNullOrWhiteSpace(updateDir))
|
||||||
|
{
|
||||||
|
Console.Error.WriteLine("apply 需要 --update <.GC/update>");
|
||||||
|
return 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 日志统一放 .GC/logs(update 目录的上一层),不再塞在 update/ 里
|
||||||
|
var updateRoot = Path.GetFullPath(updateDir);
|
||||||
|
var home = Path.GetDirectoryName(updateRoot) ?? updateRoot;
|
||||||
|
var log = new Log(Path.Combine(home, "logs"));
|
||||||
|
var applyOptions = new ApplyOptions
|
||||||
|
{
|
||||||
|
UpdateDir = updateDir,
|
||||||
|
InstallDir = Option(options, "install", null),
|
||||||
|
WaitPid = Int(options, "wait-pid", 0),
|
||||||
|
TimeoutSeconds = Int(options, "timeout", 45),
|
||||||
|
DryRun = Flag(options, "dry-run"),
|
||||||
|
Force = Flag(options, "force"),
|
||||||
|
RequireSignature = Int(options, "require-signature", 1) != 0
|
||||||
|
};
|
||||||
|
|
||||||
|
var applier = new Applier(applyOptions, log);
|
||||||
|
var code = applier.Run();
|
||||||
|
if (Flag(options, "json"))
|
||||||
|
{
|
||||||
|
if (applyOptions.DryRun)
|
||||||
|
{
|
||||||
|
// dry-run 不落盘,state.json 里是上一次的真实结果,直接打印会误导调用方
|
||||||
|
var request = Json.Read<SavedogRequest>(
|
||||||
|
Path.Combine(Path.GetFullPath(updateDir), SavedogFiles.ApplyRequest));
|
||||||
|
Console.WriteLine(Json.Serialize(new SavedogState
|
||||||
|
{
|
||||||
|
Status = code == 0 ? "checked" : "failed",
|
||||||
|
Version = request?.Version ?? "",
|
||||||
|
PackageName = request?.PackageName ?? "",
|
||||||
|
Verified = code == 0,
|
||||||
|
Message = code == 0 ? "校验全部通过(未安装,dry-run)" : "校验未通过(dry-run)"
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
var state = Json.Read<SavedogState>(
|
||||||
|
Path.Combine(Path.GetFullPath(updateDir), SavedogFiles.State));
|
||||||
|
Console.WriteLine(Json.Serialize(state));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return code;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ verify
|
||||||
|
|
||||||
|
private static int Verify(Dictionary<string, string> options)
|
||||||
|
{
|
||||||
|
var manifest = Option(options, "manifest", "");
|
||||||
|
if (string.IsNullOrWhiteSpace(manifest) || !File.Exists(manifest))
|
||||||
|
{
|
||||||
|
Console.Error.WriteLine("verify 需要 --manifest <version.json>");
|
||||||
|
return 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
var require = Int(options, "require", 1) != 0;
|
||||||
|
var text = File.ReadAllText(manifest);
|
||||||
|
var result = ManifestSignature.Verify(text, require);
|
||||||
|
|
||||||
|
if (Flag(options, "json"))
|
||||||
|
{
|
||||||
|
var report = new VerifyReport
|
||||||
|
{
|
||||||
|
Trust = result.Trust.ToString(),
|
||||||
|
KeyId = result.KeyId,
|
||||||
|
Error = result.Error
|
||||||
|
};
|
||||||
|
foreach (var key in SignatureKeyring.Keys)
|
||||||
|
report.TrustedKeys.Add(new TrustedKey
|
||||||
|
{
|
||||||
|
KeyId = key.KeyId,
|
||||||
|
Fingerprint = ManifestSignature.PublicKeyFingerprint(key.PublicKeyBase64)
|
||||||
|
});
|
||||||
|
Console.WriteLine(Json.Serialize(report));
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
Console.WriteLine($"信任状态: {result.Trust}");
|
||||||
|
if (result.KeyId != null) Console.WriteLine($"密钥: {result.KeyId}");
|
||||||
|
if (result.Error != null) Console.WriteLine($"说明: {result.Error}");
|
||||||
|
foreach (var key in SignatureKeyring.Keys)
|
||||||
|
Console.WriteLine($"受信任公钥: {key.KeyId} ({ManifestSignature.PublicKeyFingerprint(key.PublicKeyBase64)})");
|
||||||
|
}
|
||||||
|
|
||||||
|
return result.IsTrusted ? 0 : 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int VerifyModel(Dictionary<string, string> options)
|
||||||
|
{
|
||||||
|
var dir = Option(options, "dir", "");
|
||||||
|
var id = Option(options, "id", "");
|
||||||
|
if (string.IsNullOrWhiteSpace(dir) || string.IsNullOrWhiteSpace(id))
|
||||||
|
{
|
||||||
|
Console.Error.WriteLine("verify-model 需要 --dir <model 目录> --id <模型 id>");
|
||||||
|
return 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
var result = ModelIntegrity.VerifyForLoad(Path.GetFullPath(dir), id);
|
||||||
|
if (Flag(options, "json"))
|
||||||
|
Console.WriteLine(Json.Serialize(new VerifyModelReport
|
||||||
|
{
|
||||||
|
Ok = result.Ok,
|
||||||
|
Present = result.Present,
|
||||||
|
Message = result.Message
|
||||||
|
}));
|
||||||
|
else
|
||||||
|
Console.WriteLine($"{(result.Ok ? "OK" : "FAIL")} 记录={(result.Present ? "有" : "无")} {result.Message}");
|
||||||
|
|
||||||
|
return result.Ok ? 0 : 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ keygen / sign
|
||||||
|
|
||||||
|
private static int Keygen(Dictionary<string, string> options)
|
||||||
|
{
|
||||||
|
var outDir = Option(options, "out", ".signing")!;
|
||||||
|
var keyId = Option(options, "key-id", DefaultKeyId)!;
|
||||||
|
Directory.CreateDirectory(outDir);
|
||||||
|
|
||||||
|
using var key = ECDsa.Create(ECCurve.NamedCurves.nistP256);
|
||||||
|
var privatePath = Path.Combine(outDir, "gc-signing.pem");
|
||||||
|
var publicPath = Path.Combine(outDir, "gc-signing.pub");
|
||||||
|
|
||||||
|
File.WriteAllText(privatePath, key.ExportPkcs8PrivateKeyPem());
|
||||||
|
var publicBase64 = ManifestSignature.ExportPublicKeyBase64(key);
|
||||||
|
File.WriteAllText(publicPath, publicBase64 + "\n");
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (!OperatingSystem.IsWindows())
|
||||||
|
File.SetUnixFileMode(privatePath, UnixFileMode.UserRead | UnixFileMode.UserWrite);
|
||||||
|
}
|
||||||
|
catch { }
|
||||||
|
|
||||||
|
Console.WriteLine("已生成 ECDSA P-256 密钥对:");
|
||||||
|
Console.WriteLine(" 私钥(绝不要提交): " + privatePath);
|
||||||
|
Console.WriteLine(" 公钥(写进源码) : " + publicPath);
|
||||||
|
Console.WriteLine(" keyId : " + keyId);
|
||||||
|
Console.WriteLine(" 公钥 Base64 : " + publicBase64);
|
||||||
|
Console.WriteLine(" 公钥指纹 : " + ManifestSignature.PublicKeyFingerprint(publicBase64));
|
||||||
|
Console.WriteLine();
|
||||||
|
Console.WriteLine("把下面一行加进 GC/src/Security/SignatureKeyring.cs 的 Keys 列表:");
|
||||||
|
Console.WriteLine($" new KeyEntry(\"{keyId}\", \"{publicBase64}\"),");
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int Sign(Dictionary<string, string> options)
|
||||||
|
{
|
||||||
|
var manifest = Option(options, "manifest", "");
|
||||||
|
var keyPath = Option(options, "key", DefaultKeyPath)!;
|
||||||
|
var keyId = Option(options, "key-id",
|
||||||
|
Environment.GetEnvironmentVariable("GC_SIGNING_KEY_ID") ?? DefaultKeyId)!;
|
||||||
|
|
||||||
|
if (string.IsNullOrWhiteSpace(manifest) || !File.Exists(manifest))
|
||||||
|
{
|
||||||
|
Console.Error.WriteLine("sign 需要 --manifest <version.json>");
|
||||||
|
return 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
using var key = ManifestSignature.TryLoadPrivateKey(keyPath);
|
||||||
|
if (key == null)
|
||||||
|
{
|
||||||
|
Console.Error.WriteLine($"找不到可用的签名私钥: {Path.GetFullPath(keyPath)}");
|
||||||
|
return 4;
|
||||||
|
}
|
||||||
|
|
||||||
|
var text = File.ReadAllText(manifest);
|
||||||
|
var signed = ManifestSignature.SignDocument(text, key, keyId);
|
||||||
|
var output = Option(options, "out", manifest)!;
|
||||||
|
File.WriteAllText(output, signed);
|
||||||
|
|
||||||
|
var check = ManifestSignature.Verify(signed, requireSignature: true);
|
||||||
|
Console.WriteLine($"已签名: {output}({check.Trust})");
|
||||||
|
return check.Trust == ManifestTrust.Verified ? 0 : 5;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ status
|
||||||
|
|
||||||
|
private static int Status(Dictionary<string, string> options)
|
||||||
|
{
|
||||||
|
var updateDir = Path.GetFullPath(Option(options, "update", ".GC/update")!);
|
||||||
|
var state = Json.Read<SavedogState>(Path.Combine(updateDir, SavedogFiles.State));
|
||||||
|
var lastGood = Json.Read<LastGoodVersion>(Path.Combine(updateDir, SavedogFiles.LastGood));
|
||||||
|
var health = StartupHealth.Read(updateDir);
|
||||||
|
|
||||||
|
if (Flag(options, "json"))
|
||||||
|
{
|
||||||
|
Console.WriteLine(Json.Serialize(new StatusReport
|
||||||
|
{
|
||||||
|
State = state,
|
||||||
|
LastGood = lastGood,
|
||||||
|
Health = health
|
||||||
|
}));
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
Console.WriteLine(state == null
|
||||||
|
? "没有更新记录"
|
||||||
|
: $"最近更新: {state.Status} v{state.Version} -> {state.Message}({state.At})");
|
||||||
|
Console.WriteLine(lastGood == null
|
||||||
|
? "上次成功版本: 未知"
|
||||||
|
: $"上次成功版本: v{lastGood.Version}({lastGood.PackageName})");
|
||||||
|
Console.WriteLine(health == null
|
||||||
|
? "健康标记: 无"
|
||||||
|
: $"健康标记: v{health.Version} pid={health.Pid} ok={health.Ok}");
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int PrintVersion()
|
||||||
|
{
|
||||||
|
Console.WriteLine("GC-SAVEDOG 1.0.0");
|
||||||
|
Console.WriteLine("签名算法: " + ManifestSignature.Algorithm);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int Unknown(string command)
|
||||||
|
{
|
||||||
|
Console.Error.WriteLine($"未知命令: {command}");
|
||||||
|
Help();
|
||||||
|
return 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void Help()
|
||||||
|
{
|
||||||
|
Console.WriteLine("""
|
||||||
|
GC-SAVEDOG —— 启动器更新守护进程
|
||||||
|
|
||||||
|
apply --update <.GC/update> [--install <dir>] [--wait-pid N]
|
||||||
|
[--timeout 45] [--dry-run] [--force] [--json]
|
||||||
|
verify --manifest <version.json> [--require 1] [--json]
|
||||||
|
verify-model --dir <model/ID> --id <ID> [--json]
|
||||||
|
keygen [--out .signing] [--key-id gc-2026-11]
|
||||||
|
sign --manifest <version.json> [--key .signing/gc-signing.pem] [--out <file>]
|
||||||
|
status --update <.GC/update> [--json]
|
||||||
|
|
||||||
|
退出码:0 成功 / 2 验签失败(拒绝) / 3 参数或申请错误 / 5 包校验失败 / 8 已回滚
|
||||||
|
""");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ 参数
|
||||||
|
|
||||||
|
private static Dictionary<string, string> Parse(string[] args)
|
||||||
|
{
|
||||||
|
var map = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
|
||||||
|
for (var i = 0; i < args.Length; i++)
|
||||||
|
{
|
||||||
|
var arg = args[i];
|
||||||
|
if (!arg.StartsWith("--", StringComparison.Ordinal))
|
||||||
|
{
|
||||||
|
map[arg] = "1";
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var name = arg[2..];
|
||||||
|
var eq = name.IndexOf('=');
|
||||||
|
if (eq > 0)
|
||||||
|
{
|
||||||
|
map[name[..eq]] = name[(eq + 1)..];
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (i + 1 < args.Length && !args[i + 1].StartsWith("--", StringComparison.Ordinal))
|
||||||
|
{
|
||||||
|
map[name] = args[++i];
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
map[name] = "1";
|
||||||
|
}
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string? Option(Dictionary<string, string> options, string name, string? fallback)
|
||||||
|
=> options.TryGetValue(name, out var value) ? value : fallback;
|
||||||
|
|
||||||
|
private static int Int(Dictionary<string, string> options, string name, int fallback)
|
||||||
|
=> options.TryGetValue(name, out var value) && int.TryParse(value, out var parsed)
|
||||||
|
? parsed : fallback;
|
||||||
|
|
||||||
|
private static bool Flag(Dictionary<string, string> options, string name)
|
||||||
|
=> options.TryGetValue(name, out var value) &&
|
||||||
|
(value == "1" || value.Equals("true", StringComparison.OrdinalIgnoreCase));
|
||||||
|
}
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Text.Json;
|
||||||
|
using System.Text.Json.Serialization;
|
||||||
|
using GC.Services;
|
||||||
|
|
||||||
|
namespace GC.Savedog;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// GC-SAVEDOG 是裁剪发布的(PublishTrimmed),反射式序列化在裁剪后会失效:
|
||||||
|
/// trimmer 认为「没人 new 过」的构造函数会被删掉,运行时反序列化直接抛
|
||||||
|
/// <c>NotSupportedException</c>。因此守护进程把所有 JSON 类型都注册进源生成上下文,
|
||||||
|
/// 编译期生成类型信息,运行时零反射。
|
||||||
|
///
|
||||||
|
/// 新增需要读写的 JSON 类型时,记得在这里补一行 <c>[JsonSerializable]</c>,
|
||||||
|
/// 否则会在裁剪产物里报错(未裁剪的调试构建看不出问题)。
|
||||||
|
/// </summary>
|
||||||
|
[JsonSourceGenerationOptions(
|
||||||
|
PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,
|
||||||
|
PropertyNameCaseInsensitive = true,
|
||||||
|
WriteIndented = true,
|
||||||
|
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
|
||||||
|
AllowTrailingCommas = true,
|
||||||
|
ReadCommentHandling = JsonCommentHandling.Skip)]
|
||||||
|
[JsonSerializable(typeof(SavedogRequest))]
|
||||||
|
[JsonSerializable(typeof(SavedogState))]
|
||||||
|
[JsonSerializable(typeof(LastGoodVersion))]
|
||||||
|
[JsonSerializable(typeof(StartupHealth.HealthRecord))]
|
||||||
|
[JsonSerializable(typeof(ModelIntegrityFile))]
|
||||||
|
[JsonSerializable(typeof(VerifyReport))]
|
||||||
|
[JsonSerializable(typeof(StatusReport))]
|
||||||
|
[JsonSerializable(typeof(VerifyModelReport))]
|
||||||
|
internal partial class SavedogJsonContext : JsonSerializerContext
|
||||||
|
{
|
||||||
|
// 源生成器已提供 (JsonSerializerOptions) 构造函数;实例化时传入启动器的那套选项,
|
||||||
|
// 让两边写出的 JSON 完全同款(中文不转成 \uXXXX、缩进一致),便于直接 diff 排查。
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary><c>verify --json</c> 的输出。</summary>
|
||||||
|
internal sealed class VerifyReport
|
||||||
|
{
|
||||||
|
public string Trust { get; set; } = "";
|
||||||
|
public string? KeyId { get; set; }
|
||||||
|
public string? Error { get; set; }
|
||||||
|
public List<TrustedKey> TrustedKeys { get; set; } = new();
|
||||||
|
}
|
||||||
|
|
||||||
|
internal sealed class TrustedKey
|
||||||
|
{
|
||||||
|
public string KeyId { get; set; } = "";
|
||||||
|
public string Fingerprint { get; set; } = "";
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary><c>status --json</c> 的输出。</summary>
|
||||||
|
internal sealed class StatusReport
|
||||||
|
{
|
||||||
|
public SavedogState? State { get; set; }
|
||||||
|
public LastGoodVersion? LastGood { get; set; }
|
||||||
|
public StartupHealth.HealthRecord? Health { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary><c>verify-model --json</c> 的输出。</summary>
|
||||||
|
internal sealed class VerifyModelReport
|
||||||
|
{
|
||||||
|
public bool Ok { get; set; }
|
||||||
|
public bool Present { get; set; }
|
||||||
|
public string Message { get; set; } = "";
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>把共享的 <see cref="Json"/> 接到源生成上下文上。</summary>
|
||||||
|
internal static class SavedogJson
|
||||||
|
{
|
||||||
|
private static readonly SavedogJsonContext Context = new(new JsonSerializerOptions(Json.Options));
|
||||||
|
|
||||||
|
public static void Initialize()
|
||||||
|
{
|
||||||
|
Json.TypeInfoProvider = type => Context.GetTypeInfo(type);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,161 @@
|
|||||||
|
# GC-UI 持续集成
|
||||||
|
|
||||||
|
alpha 构建的工作流在 [`.gitea/workflows/gc-ui-alpha.yml`](../.gitea/workflows/gc-ui-alpha.yml),
|
||||||
|
**只支持手动触发**(定时任务已取消:它绕开 build.sh,产出的包没有后端、没有前端,跑起来只是个空壳;
|
||||||
|
另外 `cron` 里的 `TZ=` 前缀在部分 Gitea 版本上是非法表达式)。
|
||||||
|
PR 审核流水线在 [`.gitea/workflows/pr-check.yml`](../.gitea/workflows/pr-check.yml)。
|
||||||
|
本仓库是自建 Gitea(不是 GitHub),所以目录是 `.gitea/workflows/`,语法与 GitHub Actions 基本一致,
|
||||||
|
差异集中在 **runner 标签** 和 **API 前缀** 两处。
|
||||||
|
|
||||||
|
## 它做什么
|
||||||
|
|
||||||
|
| 任务 | 运行环境 | 产出 |
|
||||||
|
|---|---|---|
|
||||||
|
| `prepare` | `ubuntu-latest` | 算版本号,建一个 **草稿 + prerelease** 的 Release |
|
||||||
|
| `windows` | `windows-latest` | `gc-ui-alpha-windows-x64.zip`(Flutter release 目录) |
|
||||||
|
| `macos` | `macos-latest` | `gc-ui-alpha-macos-<arch>.zip`(`gc_ui.app`,用 `ditto` 打包保真) |
|
||||||
|
| `publish` | `ubuntu-latest` | 两个平台都成功后才把草稿翻成可见,并断言 latest 没被占用 |
|
||||||
|
|
||||||
|
- **定时**:每天 **21:00(Asia/Shanghai)**,cron 写作 `TZ=Asia/Shanghai 0 21 * * *`。
|
||||||
|
Gitea 1.23 起 Actions 的 cron 默认按 **UTC** 解释,所以这里显式带时区前缀;
|
||||||
|
若你的实例不认 `TZ=`,改成等效的 UTC 写法 `0 13 * * *`。
|
||||||
|
- **alpha 不占用 latest**:Gitea 的 `/releases/latest` 只返回「最近一个既非草稿、也非 prerelease」
|
||||||
|
的发布,所以 `prerelease: true` 的夜间版本永远不会成为 latest。`publish` 任务最后会再查一次
|
||||||
|
`/releases/latest`,一旦指向本次 tag 就 fail。
|
||||||
|
- **手动触发**:Actions 页面 Run workflow;或
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -X POST -u "USER:TOKEN" \
|
||||||
|
"https://git.xhmcl.com/api/v1/repos/Morris/GC/actions/workflows/gc-ui-alpha.yml/dispatches" \
|
||||||
|
-H 'Content-Type: application/json' -d '{"ref":"gc-ui","inputs":{"note":"手动验证"}}'
|
||||||
|
```
|
||||||
|
|
||||||
|
## 前置条件(缺一不可)
|
||||||
|
|
||||||
|
### 1. 必须有 act_runner,并且带这三个标签
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 在准备当构建机的机器上(Windows / macOS 各一台,或一台 Linux 只跑 prepare/publish)
|
||||||
|
docker run -d --name gitea-runner \
|
||||||
|
-v /var/run/docker.sock:/var/run/docker.sock \
|
||||||
|
-v /path/to/runner-data:/data \
|
||||||
|
-e GITEA_INSTANCE_URL=https://git.xhmcl.com \
|
||||||
|
-e GITEA_RUNNER_REGISTRATION_TOKEN=<在 站点管理 → Actions → Runners 里拿> \
|
||||||
|
-e GITEA_RUNNER_LABELS=ubuntu-latest:docker://gitea/runner-images:ubuntu-latest,windows-latest:docker://<你的 windows 镜像>,macos-latest:docker://<你的 macos 镜像> \
|
||||||
|
gitea/act_runner:latest
|
||||||
|
```
|
||||||
|
|
||||||
|
关键点:**`runs-on` 的值必须和 runner 上注册的 label 完全一致**,否则任务永远排队。
|
||||||
|
Windows / macOS 的构建**不能**跑在 Linux docker 容器里(一个要 MSVC,一个要 Xcode),
|
||||||
|
所以那两个 label 需要指向真实的 Windows / macOS 机器(自托管 runner)。
|
||||||
|
|
||||||
|
### 2. Flutter SDK
|
||||||
|
|
||||||
|
工作流里有一条「准备 Flutter SDK」:机器上已有 `flutter` 就直接用;没有就按
|
||||||
|
`FLUTTER_VERSION`(默认 3.24.5,需 >= 3.5.4 以匹配 `pubspec.yaml` 的 `sdk: ^3.5.4`)从
|
||||||
|
`storage.googleapis.com` 下载官方 SDK 并写进 `PATH`。所以机器只要能上外网就够,不必预装。
|
||||||
|
网络受限时请预装 Flutter 并确保 `flutter` 在 `PATH` 里。
|
||||||
|
|
||||||
|
Windows 还需要 **VS Build Tools 的「使用 C++ 的桌面开发」工作负载**;macOS 需要 **Xcode**。
|
||||||
|
|
||||||
|
### 3. Token
|
||||||
|
|
||||||
|
优先用仓库 Secrets 里的 `RELEASE_TOKEN`(Gitea 设置 → Actions → Secrets,需 `repo` 权限的个人访问令牌);
|
||||||
|
没配就退回 Gitea 自动注入的 `github.token`。若自动 token 没有 release 权限,
|
||||||
|
创建 Release 那步会报 401/403 —— 这时配一个 `RELEASE_TOKEN` 即可,不用改工作流文件。
|
||||||
|
|
||||||
|
## 本地构建(不经 CI)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 按构建主机自动选目标,每条产物都带 Flutter 前端:
|
||||||
|
# macOS 主机 → mac-arm64(原生)+ win-amd64 / win-arm64(mingw 交叉)
|
||||||
|
# Linux 主机 → win-amd64 / win-arm64(mingw 交叉)
|
||||||
|
# Linux 产物默认不出:需 aarch64 主机 + GC_BUILD_LINUX=1
|
||||||
|
# Windows 主机 → win-amd64 / win-arm64(原生)
|
||||||
|
./build.sh build
|
||||||
|
|
||||||
|
# 前端是必需项:flutter 缺失或编译失败会直接中断,
|
||||||
|
# 确需降级成只有 Avalonia 回退界面的包时才用:
|
||||||
|
./build.sh build --allow-no-ui
|
||||||
|
|
||||||
|
# 只编 macOS 前端
|
||||||
|
./GC-UI/build-ui.sh macos
|
||||||
|
|
||||||
|
# Windows 主机原生构建
|
||||||
|
GC-UI\build-ui.cmd
|
||||||
|
```
|
||||||
|
|
||||||
|
### Linux 前端(原生)
|
||||||
|
|
||||||
|
Flutter 的 Linux 桌面端只能在 Linux 上编,需要 GTK3 开发库与 C++ 工具链:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo apt install clang cmake ninja-build pkg-config libgtk-3-dev libstdc++-14-dev
|
||||||
|
```
|
||||||
|
|
||||||
|
`libstdc++-14-dev` 容易漏:clang 18 会去 `/usr/lib/gcc/x86_64-linux-gnu/14/` 找
|
||||||
|
`-lstdc++`,系统只装了 gcc-13 的开发包时链接会失败,报 `cannot find -lstdc++`。
|
||||||
|
|
||||||
|
产物布局:`GC-UI` + `lib/libflutter_linux_gtk.so` + `data/`,与官方 `flutter build
|
||||||
|
linux` 的 bundle 一致,直接铺进 `dist/linux-arm64/`。
|
||||||
|
|
||||||
|
### Windows 前端交叉编译
|
||||||
|
|
||||||
|
Flutter 官方不支持在非 Windows 主机上 `flutter build windows`,但 Windows 嵌入层
|
||||||
|
(`windows/runner/*.cpp` + `cpp_client_wrapper`)是纯 Win32 + 标准 C++,只通过 C ABI
|
||||||
|
调用 `flutter_windows.dll`,所以 mingw-w64 就能编译。整条链路上唯一必须执行的
|
||||||
|
Windows 二进制是 AOT 快照生成器 `gen_snapshot.exe`,交给 wine 跑即可。
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 依赖
|
||||||
|
sudo apt install mingw-w64 cmake ninja-build wine # Linux
|
||||||
|
brew install mingw-w64 cmake ninja # macOS
|
||||||
|
brew install --cask wine-stable # macOS 的 wine
|
||||||
|
|
||||||
|
# 单独构建(默认输出到 GC-UI/frontend/build/windows/x64/runner/Release)
|
||||||
|
./buildsh/cross/build-ui-win-cross.sh [输出目录]
|
||||||
|
```
|
||||||
|
|
||||||
|
产物与官方 toolchain 完全一致,可直接拷到 Windows 运行:
|
||||||
|
|
||||||
|
```
|
||||||
|
GC-UI.exe flutter_windows.dll data/{icudtl.dat, app.so, flutter_assets/}
|
||||||
|
```
|
||||||
|
|
||||||
|
实现分三层:
|
||||||
|
|
||||||
|
| 文件 | 职责 |
|
||||||
|
|---|---|
|
||||||
|
| `buildsh/cross/toolchain-mingw.cmake` | CMake 交叉工具链(posix 线程模型,静态链接 libstdc++,产物只依赖系统 DLL) |
|
||||||
|
| `buildsh/cross/CMakeLists.txt` | 只编 C++ 外壳;绕开 `tool_backend.bat` 与 MSVC 专用参数 |
|
||||||
|
| `buildsh/cross/build-ui-win-cross.sh` | 拉引擎产物、装 `gen_snapshot` 的 wine 包装、生成 AOT 快照、组装 |
|
||||||
|
|
||||||
|
两个容易踩的坑,脚本里已处理:
|
||||||
|
|
||||||
|
- `flutter_tools` 会 exec 路径为 `.../windows-x64-release/gen_snapshot`(**没有 `.exe`**)
|
||||||
|
的文件,所以脚本在原 `.exe` 旁边放一个同名 shell 脚本转调 wine。
|
||||||
|
- `Runner.rc` 在 windres 下有两处不兼容:图标用反斜杠相对路径、`VERSION_AS_STRING`
|
||||||
|
依赖命令行传 `-D` 的转义字符串。脚本生成一份路径与宏都已规整的 rc 副本再编译。
|
||||||
|
|
||||||
|
### 交叉编译必须自己嵌 DPI 清单
|
||||||
|
|
||||||
|
`windows/runner/CMakeLists.txt` 把 `runner.exe.manifest` 当**源文件**列进 target,
|
||||||
|
Visual Studio 生成器会把它交给链接器(`/MANIFESTINPUT`)自动嵌入 exe;
|
||||||
|
但 `buildsh/cross/CMakeLists.txt` 只用 windres 编 `Runner.rc`,CMake 不会做这一步。
|
||||||
|
结果就是交叉编出来的 `GC-UI.exe` **完全没有清单**:Windows 认为它「DPI 不感知」,
|
||||||
|
在 125% / 150% 缩放的屏幕上把整块窗口当位图拉伸 —— 界面整体发虚,中文小字最明显。
|
||||||
|
|
||||||
|
现在两处都已加固,改这块代码时不要拆掉任何一处:
|
||||||
|
|
||||||
|
| 位置 | 做法 |
|
||||||
|
|---|---|
|
||||||
|
| `buildsh/cross/CMakeLists.txt` | 往 `Runner.cross.rc` 追加 `1 24 "<abs>/runner.exe.manifest"`(id 1 = CREATEPROCESS_MANIFEST_RESOURCE_ID,type 24 = RT_MANIFEST) |
|
||||||
|
| `windows/runner/main.cpp` | 建窗之前调 `SetProcessDpiAwarenessContext(PER_MONITOR_AWARE_V2)`,失败依次退到 `SetProcessDpiAwareness` / `SetProcessDPIAware` |
|
||||||
|
|
||||||
|
`main.cpp` 那层是兜底:即使清单因为工具链原因没嵌进去,程序自己也会声明 DPI 感知。
|
||||||
|
验证办法(Windows):`GC-UI.exe` 属性 →「兼容性」里不该出现「替代高 DPI 缩放行为」,
|
||||||
|
或在 125% 缩放下截图,文字边缘应是锐利的 1.25 倍像素,而不是模糊的插值。
|
||||||
|
|
||||||
|
`.gitea/workflows` 里的 `windows` 任务仍然跑在 `windows-latest` 上;若手头只有 macOS/Linux
|
||||||
|
构建机,可以把该任务的 `runs-on` 换成对应标签,直接复用这套交叉编译脚本,
|
||||||
|
不再需要 VS Build Tools。
|
||||||
@@ -0,0 +1,201 @@
|
|||||||
|
# GC-UI
|
||||||
|
|
||||||
|
GC 启动器的**前后端分离**实现:界面用 Flutter,服务层留在 .NET。
|
||||||
|
|
||||||
|
```
|
||||||
|
GC-UI/
|
||||||
|
├── backend/GC.UI.Server/ # .NET 8 后端:本地 HTTP API + 模型窗口宿主
|
||||||
|
│ ├── Program.cs # 所有接口(最小 API)
|
||||||
|
│ ├── ApiModels.cs # 前后端 JSON 契约
|
||||||
|
│ └── AvaloniaHost.cs # 模型窗口宿主(Avalonia,惰性启动)
|
||||||
|
└── frontend/ # Flutter 前端(Windows / macOS 桌面)
|
||||||
|
├── lib/
|
||||||
|
│ ├── main.dart # 应用入口
|
||||||
|
│ ├── shell.dart # 侧边栏 + 内容区 + 更新状态条
|
||||||
|
│ ├── pages.dart # 首页 / 下载 / 设置 / 关于
|
||||||
|
│ ├── controller.dart # 外壳状态(设置、健康、更新)
|
||||||
|
│ ├── api_client.dart # 后端 HTTP 客户端 + DTO
|
||||||
|
│ ├── i18n.dart # zh-CN / en 文案
|
||||||
|
│ └── theme.dart # 配色与通用组件
|
||||||
|
├── windows/ # Windows 原生 runner(flutter create 生成)
|
||||||
|
├── macos/ # macOS 原生 runner(flutter create 生成)
|
||||||
|
└── test/ # 单元测试 + 后端契约测试 + 截图脚本
|
||||||
|
```
|
||||||
|
|
||||||
|
## 为什么这样切
|
||||||
|
|
||||||
|
原来的 GC 是「Avalonia 界面 + 服务层」一体式应用。拆分时唯一不能动的是**模型契约**:
|
||||||
|
模型 dll 通过 `IModelRuntime.CreateView` 返回的是 Avalonia `Control`,渲染栈是契约的一部分。
|
||||||
|
把渲染换成 Flutter 等于让所有已发布模型失效。
|
||||||
|
|
||||||
|
所以切法是:
|
||||||
|
|
||||||
|
| 层 | 归属 | 说明 |
|
||||||
|
|---|---|---|
|
||||||
|
| 首页 / 下载 / 设置 / 关于 | **Flutter 前端** | 纯界面,通过 HTTP 调后端 |
|
||||||
|
| 模型扫描、下载、更新、设置持久化 | **.NET 后端** | 直接复用 `GC/src`(GC.Core)与 `GC-DOWNLOAD` |
|
||||||
|
| 模型自己的窗口 | **.NET 后端** | 模型返回 Avalonia 控件,由后端承载 |
|
||||||
|
|
||||||
|
前端只发一条「启动模型」的指令,模型窗口由后端在自己的 UI 线程上打开。
|
||||||
|
|
||||||
|
## 前端方案:为什么是 Flutter
|
||||||
|
|
||||||
|
Windows 与 macOS 用**同一套 Flutter 代码 + 各自的原生 runner**:
|
||||||
|
|
||||||
|
- **一套代码两个平台**:`flutter create --platforms=windows,macos` 生成 `windows/`(CMake + Win32 窗口)与 `macos/`(Xcode + Cocoa 窗口)两个原生壳,业务代码 100% 共用。
|
||||||
|
- **原生桌面窗口**:不是 WebView 套壳,两个平台都是真正的原生窗口,可设置最小尺寸、标题栏、DPI 缩放。
|
||||||
|
- **渲染一致**:Skia/Impeller 自绘,两个平台像素级一致,不需要为 WinUI / AppKit 各写一套控件。
|
||||||
|
- **热重载**:`flutter run -d windows` / `-d macos` 改界面即时生效,迭代比 XAML 快。
|
||||||
|
- **对比过的替代方案**:
|
||||||
|
- *继续用 Avalonia*:跨平台没问题,但那就不是「前后端分离 + Flutter 前端」了。
|
||||||
|
- *WinUI 3 + SwiftUI 各写一套*:两套 UI 代码、两套状态管理,维护成本翻倍。
|
||||||
|
- *Electron / Tauri*:WebView 套壳,包体大(Electron ~150MB)或需要 Rust 工具链,且与 .NET 后端通信仍要额外桥接。
|
||||||
|
|
||||||
|
## 运行
|
||||||
|
|
||||||
|
### 1. 启动后端
|
||||||
|
|
||||||
|
发布版里后端不走独立进程:`GC-BOOT` 直接引用本工程,调用
|
||||||
|
`BackendServer.Start(args, port)` 在自己进程内托管,发布包因此只有一个 exe
|
||||||
|
(两个自包含进程会把 60MB 运行时复制两份)。下面的独立运行方式只用于开发调试。
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 仓库根目录
|
||||||
|
dotnet run --project GC-UI/backend/GC.UI.Server
|
||||||
|
|
||||||
|
# 指定端口(默认 17890)
|
||||||
|
dotnet run --project GC-UI/backend/GC.UI.Server -- --port 17890
|
||||||
|
# 或
|
||||||
|
GC_UI_PORT=17890 dotnet run --project GC-UI/backend/GC.UI.Server
|
||||||
|
```
|
||||||
|
|
||||||
|
端口约定集中在 `GC.Services.GcUiContract`(`DefaultPort` / `PortEnvVar`):
|
||||||
|
正式启动时由 GC-BOOT 选端口(17890 被占用就往后试 9 个),再通过 `GC_UI_PORT`
|
||||||
|
环境变量同时传给后端和前端,所以**不需要为了换端口重新编译前端**。
|
||||||
|
启动后后端会在 `~/.GC/ui-backend.json` 写入 `{ port, pid, url, version, platform }`,
|
||||||
|
排查问题时可以据此确认实际端口。
|
||||||
|
|
||||||
|
### 2. 启动前端
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd GC-UI/frontend
|
||||||
|
flutter pub get
|
||||||
|
|
||||||
|
# Windows
|
||||||
|
flutter run -d windows
|
||||||
|
|
||||||
|
# macOS
|
||||||
|
flutter run -d macos
|
||||||
|
|
||||||
|
# 后端不在默认端口时
|
||||||
|
flutter run -d windows --dart-define=GC_UI_BASE_URL=http://127.0.0.1:18000
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 打包
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd GC-UI/frontend
|
||||||
|
flutter build windows --release # build/windows/x64/runner/Release/
|
||||||
|
flutter build macos --release # build/macos/Build/Products/Release/
|
||||||
|
```
|
||||||
|
|
||||||
|
或直接用仓库根目录的脚本:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
./GC-UI/build-ui.sh # macOS / Linux 上构建(macOS 产物)
|
||||||
|
GC-UI\build-ui.cmd # Windows 上构建(Windows 产物)
|
||||||
|
```
|
||||||
|
|
||||||
|
## HTTP 接口
|
||||||
|
|
||||||
|
后端只监听 `127.0.0.1`,不对外暴露。
|
||||||
|
|
||||||
|
| 方法 | 路径 | 说明 |
|
||||||
|
|---|---|---|
|
||||||
|
| GET | `/api/health` | 健康检查 + 模型窗口宿主是否可用 |
|
||||||
|
| GET | `/api/models` | 已安装模型 |
|
||||||
|
| GET | `/api/models/{id}/preview` | 模型封面图(PNG) |
|
||||||
|
| POST | `/api/models/{id}/launch` | 启动模型(打开模型自己的窗口) |
|
||||||
|
| DELETE | `/api/models/{id}` | 删除模型 |
|
||||||
|
| GET | `/api/settings` | 读取设置 |
|
||||||
|
| POST | `/api/settings` | 修改设置(补丁式,只改传入字段) |
|
||||||
|
| GET | `/api/sources` | 模型源列表 |
|
||||||
|
| POST | `/api/sources/select` | 双源测速并切到最快 |
|
||||||
|
| GET | `/api/remote/models?sourceId=&force=` | 远端可下载模型 |
|
||||||
|
| POST | `/api/download` | 入队下载 `{ sourceId, modelId }` |
|
||||||
|
| GET | `/api/download/jobs` | 下载任务列表 |
|
||||||
|
| POST | `/api/download/{id}/cancel` | 取消 |
|
||||||
|
| POST | `/api/download/{id}/retry` | 重试 |
|
||||||
|
| POST | `/api/download/{id}/remove` | 移除任务 |
|
||||||
|
| POST | `/api/download/clear-finished` | 清除已完成 |
|
||||||
|
| POST | `/api/update/check` | 检查模型 / 启动器更新 |
|
||||||
|
| GET | `/api/about` | 版本 + 贡献者 |
|
||||||
|
| POST | `/api/shell/open-folder` | 打开目录(仅限启动器自己的目录) |
|
||||||
|
| POST | `/api/shell/open-url` | 打开 http/https 链接 |
|
||||||
|
|
||||||
|
契约定义见 `backend/GC.UI.Server/ApiModels.cs`,前端对应 `frontend/lib/api_client.dart`。
|
||||||
|
|
||||||
|
## 测试
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 后端编译
|
||||||
|
dotnet build GC-UI/backend/GC.UI.Server
|
||||||
|
|
||||||
|
# 前端静态检查 + 单元测试
|
||||||
|
cd GC-UI/frontend
|
||||||
|
flutter analyze
|
||||||
|
flutter test
|
||||||
|
|
||||||
|
# 前后端联调(需要后端正在运行;后端没起时自动跳过)
|
||||||
|
flutter test test/backend_contract_test.dart
|
||||||
|
|
||||||
|
# 生成界面截图到 test/shots/(视觉检查用,不需要后端)
|
||||||
|
flutter test tool/render_shots_test.dart
|
||||||
|
```
|
||||||
|
|
||||||
|
截图脚本覆盖四个页面(首页 / 下载 / 设置 / 关于),再加一整套外壳与 1024×680 小窗回归:
|
||||||
|
`test/shots/home.png`、`download.png`、`settings.png`、`about.png`、`shell.png`、
|
||||||
|
`home-small.png`、`download-small.png`、`settings-small.png`,以及浅色主题的
|
||||||
|
`home-light.png`、`settings-light.png`。小窗用例会顺带抓布局溢出(RenderFlex overflow)。
|
||||||
|
|
||||||
|
四个页面都用预置数据(`initialModels` / `initialSources` / `initialAbout` 等)渲染,
|
||||||
|
所以**不需要先起后端**。测试环境的字体是 Ahem(所有字都是方块),脚本会显式加载
|
||||||
|
系统里的 Noto Sans SC / 微软雅黑 / 苹方,并顺带加载 Material 图标字体,中文和图标才正常。
|
||||||
|
截图必须放在 `runAsync` 里取像素(`toImage` / `toByteData` 走真实引擎管线),
|
||||||
|
否则 fake async 时钟不推进,每个用例会卡满 10 分钟才超时。
|
||||||
|
|
||||||
|
## 界面清晰度(DPI)
|
||||||
|
|
||||||
|
`GC-UI.exe` 必须在启动时就声明 DPI 感知,否则 Windows 在 125% / 150% 缩放下会把
|
||||||
|
整块窗口当位图拉伸,界面看起来「糊」—— 中文小字最先糊。两处保证:
|
||||||
|
|
||||||
|
- `windows/runner/runner.exe.manifest`:PerMonitorV2(原生 MSVC 构建由 CMake 自动嵌入)
|
||||||
|
- `windows/runner/main.cpp`:建窗前再声明一次,依次尝试
|
||||||
|
`SetProcessDpiAwarenessContext` → `SetProcessDpiAwareness` → `SetProcessDPIAware`
|
||||||
|
- `buildsh/cross/CMakeLists.txt`:交叉编译时把清单写进 `.rc`(windres 不会自动嵌入)
|
||||||
|
|
||||||
|
另外主题里做了两件跟「清晰」有关的事:字体族走
|
||||||
|
`Segoe UI + Microsoft YaHei UI`(macOS 走苹方)而不是让引擎随意回退;
|
||||||
|
正文最小 12px、行高固定,中文不再挤成一片。详见
|
||||||
|
[CI.md 的「交叉编译必须自己嵌 DPI 清单」](CI.md#交叉编译必须自己嵌-dpi-清单)。
|
||||||
|
|
||||||
|
## 「关于」页展示的技术栈
|
||||||
|
|
||||||
|
「关于」页的版本卡片里直接写明这套实现的两个关键点:
|
||||||
|
|
||||||
|
| 行 | 值 | 来源 |
|
||||||
|
|---|---|---|
|
||||||
|
| 源码语言 | **C#** | 后端 `/api/about` 返回 `sourceLanguage` |
|
||||||
|
| 前端 | **Flutter** | 后端 `/api/about` 返回 `frontend` |
|
||||||
|
| 架构 | Flutter 前端 + .NET 后端(本地 HTTP) | 前端 i18n 文案 |
|
||||||
|
|
||||||
|
两个字段由后端下发(而不是前端写死),所以将来换实现时只改后端一处,
|
||||||
|
前端和「关于」页自动跟着变。契约字段见 `ApiModels.cs` 的 `AboutDto`,
|
||||||
|
前端解析在 `lib/api_client.dart` 的 `AboutInfo`。
|
||||||
|
|
||||||
|
## 安全边界
|
||||||
|
|
||||||
|
- 后端只绑定 `127.0.0.1`,不接受外部连接。
|
||||||
|
- `open-folder` 只允许打开模型库 / 数据目录 / 应用目录之内的路径,避免被当成任意路径执行器。
|
||||||
|
- `open-url` 只允许 `http` / `https`。
|
||||||
|
- CORS 只放行 `localhost` / `127.0.0.1` 来源,方便 `flutter run -d chrome` 调试界面。
|
||||||
@@ -0,0 +1,151 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace GC.UI.Server;
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// 前后端之间的数据契约(HTTP + JSON,camelCase)。
|
||||||
|
// 前端(Flutter)只认这些字段,不认 .NET 类型;后端换实现不影响前端。
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
public sealed record HealthDto(
|
||||||
|
bool Ok,
|
||||||
|
string Version,
|
||||||
|
string Platform,
|
||||||
|
bool UiAvailable,
|
||||||
|
string? UiError);
|
||||||
|
|
||||||
|
public sealed record ModelDto(
|
||||||
|
string Id,
|
||||||
|
string Name,
|
||||||
|
string Description,
|
||||||
|
string Version,
|
||||||
|
string Author,
|
||||||
|
long SizeBytes,
|
||||||
|
string SizeText,
|
||||||
|
IReadOnlyList<string> Tags,
|
||||||
|
bool HasPreview,
|
||||||
|
string PreviewUrl,
|
||||||
|
string Directory,
|
||||||
|
string DataDirectory);
|
||||||
|
|
||||||
|
public sealed record SourceDto(
|
||||||
|
string Id,
|
||||||
|
string Name,
|
||||||
|
string Url,
|
||||||
|
bool Enabled,
|
||||||
|
bool BuiltIn,
|
||||||
|
string Host);
|
||||||
|
|
||||||
|
public sealed record RemoteModelDto(
|
||||||
|
string Id,
|
||||||
|
string Name,
|
||||||
|
string Description,
|
||||||
|
string Version,
|
||||||
|
long SizeBytes,
|
||||||
|
string SizeText,
|
||||||
|
string SourceId,
|
||||||
|
bool Installed,
|
||||||
|
string? InstalledVersion);
|
||||||
|
|
||||||
|
public sealed record SourceIndexDto(
|
||||||
|
string SourceId,
|
||||||
|
string Root,
|
||||||
|
bool FromCache,
|
||||||
|
string? Error,
|
||||||
|
string ResolvedFrom,
|
||||||
|
IReadOnlyList<RemoteModelDto> Models);
|
||||||
|
|
||||||
|
public sealed record JobDto(
|
||||||
|
string Id,
|
||||||
|
string ModelId,
|
||||||
|
string Name,
|
||||||
|
string Version,
|
||||||
|
string State,
|
||||||
|
double Progress,
|
||||||
|
string StatusText,
|
||||||
|
string DetailText,
|
||||||
|
string? Error,
|
||||||
|
bool IsActive,
|
||||||
|
bool CanRetry,
|
||||||
|
bool IsDone);
|
||||||
|
|
||||||
|
public sealed record LanguageDto(string Code, string Label);
|
||||||
|
|
||||||
|
public sealed record SettingsDto(
|
||||||
|
string Language,
|
||||||
|
string Theme,
|
||||||
|
string AccentColor,
|
||||||
|
int RenderFps,
|
||||||
|
int MemoryMb,
|
||||||
|
bool MemoryAuto,
|
||||||
|
bool AutoUpdateOnStartup,
|
||||||
|
bool RequireSignedManifest,
|
||||||
|
string UpdateRepository,
|
||||||
|
string? UpdateLocalRoot,
|
||||||
|
string? ModelRootOverride,
|
||||||
|
int MemoryBudgetMb,
|
||||||
|
string MemoryUsageText,
|
||||||
|
string ModelRoot,
|
||||||
|
string DataRoot,
|
||||||
|
string SettingsFile,
|
||||||
|
string Version,
|
||||||
|
string Platform,
|
||||||
|
IReadOnlyList<SourceDto> Sources,
|
||||||
|
IReadOnlyList<LanguageDto> Languages);
|
||||||
|
|
||||||
|
/// <summary>设置补丁:只改传进来的字段,null 表示不动。</summary>
|
||||||
|
public sealed record SettingsPatch(
|
||||||
|
string? Language,
|
||||||
|
string? Theme,
|
||||||
|
string? AccentColor,
|
||||||
|
int? RenderFps,
|
||||||
|
int? MemoryMb,
|
||||||
|
bool? MemoryAuto,
|
||||||
|
bool? AutoUpdateOnStartup,
|
||||||
|
bool? RequireSignedManifest,
|
||||||
|
string? UpdateRepository,
|
||||||
|
string? UpdateLocalRoot,
|
||||||
|
string? ModelRootOverride);
|
||||||
|
|
||||||
|
public sealed record LatencyDto(string Id, string Name, long Milliseconds);
|
||||||
|
|
||||||
|
public sealed record UpdateCheckDto(
|
||||||
|
string Outcome,
|
||||||
|
string Message,
|
||||||
|
int UpdatedModels,
|
||||||
|
IReadOnlyList<string> ModelNames,
|
||||||
|
string? LauncherMessage,
|
||||||
|
string? Error,
|
||||||
|
string? LauncherLatest,
|
||||||
|
string SourceName,
|
||||||
|
IReadOnlyList<LatencyDto> Latency);
|
||||||
|
|
||||||
|
public sealed record ContributorDto(string Name, int Contributions, string? AvatarUrl);
|
||||||
|
|
||||||
|
public sealed record AboutDto(
|
||||||
|
string AppName,
|
||||||
|
string Version,
|
||||||
|
string Platform,
|
||||||
|
string Repository,
|
||||||
|
IReadOnlyList<ContributorDto> Contributors,
|
||||||
|
string SourceLanguage,
|
||||||
|
string Frontend);
|
||||||
|
|
||||||
|
public sealed record LaunchResultDto(bool Ok, string Message);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 通用错误响应。限流 / 参数校验这类与具体业务无关的失败用它,
|
||||||
|
/// 不要复用 <see cref="LaunchResultDto"/> —— 那会让前端误以为「启动模型」有结果。
|
||||||
|
/// </summary>
|
||||||
|
public sealed record ErrorDto(bool Ok, string Message)
|
||||||
|
{
|
||||||
|
public static ErrorDto Of(string message) => new(false, message);
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed record DownloadRequest(string SourceId, string ModelId);
|
||||||
|
|
||||||
|
public sealed record PathRequest(string Path);
|
||||||
|
|
||||||
|
public sealed record UrlRequest(string Url);
|
||||||
|
|
||||||
|
public sealed record ForceRequest(bool Force);
|
||||||
@@ -0,0 +1,174 @@
|
|||||||
|
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 Task<bool>? _startTask;
|
||||||
|
|
||||||
|
public AvaloniaHost(AppServices services) => _services = services;
|
||||||
|
|
||||||
|
public bool IsAvailable { get; private set; }
|
||||||
|
|
||||||
|
public string? LastError { get; private set; }
|
||||||
|
|
||||||
|
public Task<bool> EnsureStartedAsync()
|
||||||
|
{
|
||||||
|
lock (_gate)
|
||||||
|
{
|
||||||
|
_startTask ??= Task.Run(StartCore);
|
||||||
|
return _startTask;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool StartCore()
|
||||||
|
{
|
||||||
|
var ready = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||||
|
|
||||||
|
var thread = new Thread(() =>
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
AppBuilder.Configure<HostApp>()
|
||||||
|
.UsePlatformDetect()
|
||||||
|
.AfterSetup(_ => ready.TrySetResult(true))
|
||||||
|
.StartWithClassicDesktopLifetime(Array.Empty<string>());
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
LastError = ex.Message;
|
||||||
|
ready.TrySetResult(false);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
{
|
||||||
|
IsBackground = true,
|
||||||
|
Name = "gc-ui-avalonia"
|
||||||
|
};
|
||||||
|
|
||||||
|
// Windows 上 Avalonia 需要 STA 线程;macOS / Linux 不支持也不必要。
|
||||||
|
if (OperatingSystem.IsWindows())
|
||||||
|
{
|
||||||
|
try { thread.SetApartmentState(ApartmentState.STA); }
|
||||||
|
catch { /* 忽略:部分运行时不允许设置 */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
thread.Start();
|
||||||
|
|
||||||
|
if (!ready.Task.Wait(TimeSpan.FromSeconds(30)))
|
||||||
|
{
|
||||||
|
LastError = "图形环境初始化超时";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
IsAvailable = ready.Task.Result;
|
||||||
|
return IsAvailable;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>在 Avalonia UI 线程上加载模型并打开它自己的窗口。</summary>
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,664 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.IO;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text.Json;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using GC.Download;
|
||||||
|
using GC.Models;
|
||||||
|
using GC.Services;
|
||||||
|
using GC.UI.Server;
|
||||||
|
using Microsoft.AspNetCore.Builder;
|
||||||
|
using Microsoft.AspNetCore.Hosting;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Microsoft.Extensions.Hosting;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
|
||||||
|
namespace GC.UI.Server;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// GC-UI 后端(本地 HTTP 服务:模型扫描 / 下载 / 更新 / 设置 / 模型窗口宿主)。
|
||||||
|
///
|
||||||
|
/// 两种跑法共用同一份代码:
|
||||||
|
/// · 独立进程:<c>GC.UI.Server</c> 可执行文件(开发调试 / 旧包兼容);
|
||||||
|
/// · 进程内:启动器直接调用 <see cref="Start"/>,把后端跑在自己的进程里 ——
|
||||||
|
/// 发布包因此只需要一个 exe,不必再复制一份完整的 .NET 运行时。
|
||||||
|
/// </summary>
|
||||||
|
public static class BackendServer
|
||||||
|
{
|
||||||
|
/// <summary>按命令行 / GC_UI_PORT 解析端口并构建(未启动)的后端。</summary>
|
||||||
|
public static WebApplication StartFromCommandLine(string[] args)
|
||||||
|
=> Start(args, ResolvePort(args));
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 构建后端。返回的 <see cref="WebApplication"/> 尚未启动:
|
||||||
|
/// 独立进程直接 <c>Run()</c>,启动器用 <c>StartAsync()</c> 之后继续拉起界面。
|
||||||
|
/// </summary>
|
||||||
|
public static WebApplication Start(string[] args, int port)
|
||||||
|
{
|
||||||
|
// 下载模块(GC-DOWNLOAD)通过宿主钩子注入,和 GC-BOOT 的做法一致。
|
||||||
|
DownloadModuleHost.Factory = new DownloadModuleFactory();
|
||||||
|
|
||||||
|
var services = AppServices.Create();
|
||||||
|
var uiHost = new AvaloniaHost(services);
|
||||||
|
|
||||||
|
var builder = WebApplication.CreateBuilder(new WebApplicationOptions { Args = args });
|
||||||
|
builder.Logging.ClearProviders();
|
||||||
|
builder.WebHost.UseUrls($"http://127.0.0.1:{port}");
|
||||||
|
|
||||||
|
// 本地伴随进程:限制请求体大小、关闭 Server 头、收紧超时,减少被本地恶意页面
|
||||||
|
// 或异常客户端拖垮的攻击面。
|
||||||
|
builder.WebHost.ConfigureKestrel(options =>
|
||||||
|
{
|
||||||
|
options.AddServerHeader = false;
|
||||||
|
options.Limits.MaxRequestBodySize = 2 * 1024 * 1024;
|
||||||
|
options.Limits.RequestHeadersTimeout = TimeSpan.FromSeconds(15);
|
||||||
|
options.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(2);
|
||||||
|
options.Limits.MaxConcurrentConnections = 64;
|
||||||
|
});
|
||||||
|
|
||||||
|
// 桌面端(Windows/macOS)走原生 HTTP,不需要 CORS;
|
||||||
|
// 这里放开本机回环来源,方便用 `flutter run -d chrome` 调试界面。
|
||||||
|
builder.Services.AddCors(options => options.AddDefaultPolicy(policy => policy
|
||||||
|
.SetIsOriginAllowed(origin =>
|
||||||
|
Uri.TryCreate(origin, UriKind.Absolute, out var uri) &&
|
||||||
|
(uri.Host == "127.0.0.1" || uri.Host == "localhost" || uri.Host == "::1"))
|
||||||
|
.AllowAnyHeader()
|
||||||
|
.AllowAnyMethod()));
|
||||||
|
|
||||||
|
var app = builder.Build();
|
||||||
|
app.UseCors();
|
||||||
|
|
||||||
|
// 日志与启动器共用 .GC/logs,整条启动链路(启动器 → 后端 → 守护进程)都在同一组文件里。
|
||||||
|
var logPaths = AppPaths.Discover();
|
||||||
|
GcLog.Init(logPaths.LogsRoot);
|
||||||
|
GcLog.Info($"GC-UI 后端启动,监听 127.0.0.1:{port}",
|
||||||
|
$"GC-UI backend started on 127.0.0.1:{port}");
|
||||||
|
|
||||||
|
// 设置白名单 / 标识校验用到的规则(只在本进程内使用)。
|
||||||
|
var allowedLanguages = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
|
||||||
|
{ "auto", "zh-CN", "en" };
|
||||||
|
var allowedThemes = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
|
||||||
|
{ "light", "dark", "system" };
|
||||||
|
var accentHexRegex = new System.Text.RegularExpressions.Regex(
|
||||||
|
"^#(?:[0-9A-Fa-f]{6})$", System.Text.RegularExpressions.RegexOptions.Compiled);
|
||||||
|
var safeIdRegex = new System.Text.RegularExpressions.Regex(
|
||||||
|
"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$", System.Text.RegularExpressions.RegexOptions.Compiled);
|
||||||
|
|
||||||
|
// 安全响应头 + Host/Origin 校验(抵御 DNS rebinding 与跨站调用)。
|
||||||
|
app.Use(async (context, next) =>
|
||||||
|
{
|
||||||
|
var headers = context.Response.Headers;
|
||||||
|
headers["X-Content-Type-Options"] = "nosniff";
|
||||||
|
headers["X-Frame-Options"] = "DENY";
|
||||||
|
headers["Referrer-Policy"] = "no-referrer";
|
||||||
|
headers["Content-Security-Policy"] = "default-src 'none'; frame-ancestors 'none'";
|
||||||
|
headers["Cache-Control"] = "no-store";
|
||||||
|
|
||||||
|
var host = context.Request.Host.Host;
|
||||||
|
if (!string.Equals(host, "127.0.0.1", StringComparison.OrdinalIgnoreCase) &&
|
||||||
|
!string.Equals(host, "localhost", StringComparison.OrdinalIgnoreCase) &&
|
||||||
|
!string.Equals(host, "::1", StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
context.Response.StatusCode = StatusCodes.Status403Forbidden;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var origin = context.Request.Headers.Origin.ToString();
|
||||||
|
if (!string.IsNullOrEmpty(origin) &&
|
||||||
|
!(Uri.TryCreate(origin, UriKind.Absolute, out var parsed) &&
|
||||||
|
(parsed.Host == "127.0.0.1" || parsed.Host == "localhost" || parsed.Host == "::1")))
|
||||||
|
{
|
||||||
|
context.Response.StatusCode = StatusCodes.Status403Forbidden;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await next();
|
||||||
|
});
|
||||||
|
|
||||||
|
// 写入类接口做简单限流:单 IP 每秒最多 40 次,防止本地脚本刷爆下载/更新。
|
||||||
|
var writeBuckets =
|
||||||
|
new System.Collections.Concurrent.ConcurrentDictionary<string, (long Window, int Count)>();
|
||||||
|
app.Use(async (context, next) =>
|
||||||
|
{
|
||||||
|
if (HttpMethods.IsPost(context.Request.Method) ||
|
||||||
|
HttpMethods.IsDelete(context.Request.Method))
|
||||||
|
{
|
||||||
|
var key = context.Connection.RemoteIpAddress?.ToString() ?? "local";
|
||||||
|
var now = Environment.TickCount64;
|
||||||
|
|
||||||
|
// 定期丢弃过期窗口:本机连接数不多,但长时间运行后桶只增不减会缓慢泄漏。
|
||||||
|
if (writeBuckets.Count > 256)
|
||||||
|
{
|
||||||
|
foreach (var entry in writeBuckets)
|
||||||
|
{
|
||||||
|
if (now - entry.Value.Window > 60_000)
|
||||||
|
writeBuckets.TryRemove(entry.Key, out _);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var bucket = writeBuckets.AddOrUpdate(
|
||||||
|
key,
|
||||||
|
_ => (now, 1),
|
||||||
|
(_, old) => now - old.Window > 1000 ? (now, 1) : (old.Window, old.Count + 1));
|
||||||
|
|
||||||
|
if (bucket.Count > 40)
|
||||||
|
{
|
||||||
|
context.Response.StatusCode = StatusCodes.Status429TooManyRequests;
|
||||||
|
await context.Response.WriteAsJsonAsync(ErrorDto.Of("请求过于频繁,请稍后再试"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await next();
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---- 健康检查 -------------------------------------------------------------
|
||||||
|
|
||||||
|
app.MapGet("/api/health", () => Results.Ok(new HealthDto(
|
||||||
|
true,
|
||||||
|
LauncherRuntimeInfo.CurrentLauncherVersion,
|
||||||
|
LauncherRuntimeInfo.CurrentRid,
|
||||||
|
uiHost.IsAvailable,
|
||||||
|
uiHost.LastError)));
|
||||||
|
|
||||||
|
// ---- 已安装模型 -----------------------------------------------------------
|
||||||
|
|
||||||
|
app.MapGet("/api/models", () =>
|
||||||
|
Results.Ok(services.Models.Scan().Select(ToModelDto).ToList()));
|
||||||
|
|
||||||
|
app.MapGet("/api/models/{id}/preview", (string id, HttpResponse response) =>
|
||||||
|
{
|
||||||
|
if (!IsSafeId(id)) return Results.BadRequest(ErrorDto.Of("模型标识无效"));
|
||||||
|
var package = services.Models.Find(id);
|
||||||
|
if (package == null || !File.Exists(package.PreviewPath)) return Results.NotFound();
|
||||||
|
|
||||||
|
// 封面是静态图,允许前端缓存:默认全局中间件写的 no-store 会让每次滚动都重新请求。
|
||||||
|
// 按扩展名给准确的 MIME —— 统一写 image/png 时,WebP / JPEG 封面在部分平台显示不出来。
|
||||||
|
response.Headers.CacheControl = "private, max-age=300";
|
||||||
|
return Results.File(package.PreviewPath, GuessImageContentType(package.PreviewPath));
|
||||||
|
});
|
||||||
|
|
||||||
|
app.MapPost("/api/models/{id}/launch", async (string id) =>
|
||||||
|
{
|
||||||
|
if (!IsSafeId(id)) return Results.BadRequest(new LaunchResultDto(false, "模型标识无效"));
|
||||||
|
var package = services.Models.Find(id);
|
||||||
|
if (package == null) return Results.NotFound(new LaunchResultDto(false, $"没有找到模型 {id}"));
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
services.Memory.Refresh();
|
||||||
|
var message = await uiHost.LaunchAsync(package);
|
||||||
|
return Results.Ok(new LaunchResultDto(true, message));
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
// 细节只写日志,不回显给调用方,避免泄漏本机路径等内部信息。
|
||||||
|
Console.Error.WriteLine($"[launch] 启动模型 {id} 失败: {ex}");
|
||||||
|
return Results.Json(new LaunchResultDto(false, "模型启动失败,请查看后端日志"), statusCode: 503);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
app.MapDelete("/api/models/{id}", (string id) =>
|
||||||
|
{
|
||||||
|
if (!IsSafeId(id)) return Results.BadRequest(ErrorDto.Of("模型标识无效"));
|
||||||
|
var ok = services.Models.Delete(id);
|
||||||
|
if (ok) services.Models.NotifyChanged();
|
||||||
|
return ok
|
||||||
|
? Results.Ok(new LaunchResultDto(true, $"已删除模型 {id}"))
|
||||||
|
: Results.NotFound(ErrorDto.Of($"没有找到模型 {id}"));
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---- 设置 -----------------------------------------------------------------
|
||||||
|
|
||||||
|
app.MapGet("/api/settings", () => Results.Ok(ToSettingsDto()));
|
||||||
|
|
||||||
|
app.MapPost("/api/settings", (SettingsPatch? patch) =>
|
||||||
|
{
|
||||||
|
if (patch == null) return Results.BadRequest(ErrorDto.Of("缺少设置内容"));
|
||||||
|
|
||||||
|
// 白名单校验:设置项会写进磁盘并被前端直接使用,不接受任意字符串。
|
||||||
|
if (patch.Language != null && !allowedLanguages.Contains(patch.Language))
|
||||||
|
return Results.BadRequest(ErrorDto.Of("不支持的界面语言"));
|
||||||
|
if (patch.Theme != null && !allowedThemes.Contains(patch.Theme))
|
||||||
|
return Results.BadRequest(ErrorDto.Of("不支持的主题"));
|
||||||
|
if (patch.AccentColor != null && !accentHexRegex.IsMatch(patch.AccentColor))
|
||||||
|
return Results.BadRequest(ErrorDto.Of("主题色需为 #RRGGBB"));
|
||||||
|
if (patch.UpdateRepository != null && !IsAllowedRepository(patch.UpdateRepository))
|
||||||
|
return Results.BadRequest(ErrorDto.Of("更新仓库地址不受信任"));
|
||||||
|
|
||||||
|
services.Settings.Apply(s =>
|
||||||
|
{
|
||||||
|
if (patch.Language != null) s.Language = patch.Language;
|
||||||
|
if (patch.Theme != null) s.Theme = patch.Theme;
|
||||||
|
if (patch.AccentColor != null) s.AccentColor = patch.AccentColor.ToUpperInvariant();
|
||||||
|
if (patch.RenderFps.HasValue) s.RenderFps = Math.Clamp(patch.RenderFps.Value, 12, 120);
|
||||||
|
if (patch.MemoryMb.HasValue) s.MemoryMb = Math.Clamp(patch.MemoryMb.Value, 256, 16384);
|
||||||
|
if (patch.MemoryAuto.HasValue) s.MemoryAuto = patch.MemoryAuto.Value;
|
||||||
|
if (patch.AutoUpdateOnStartup.HasValue) s.AutoUpdateOnStartup = patch.AutoUpdateOnStartup.Value;
|
||||||
|
if (patch.RequireSignedManifest.HasValue) s.RequireSignedManifest = patch.RequireSignedManifest.Value;
|
||||||
|
if (patch.UpdateRepository != null) s.UpdateRepository = patch.UpdateRepository;
|
||||||
|
if (patch.UpdateLocalRoot != null) s.UpdateLocalRoot = patch.UpdateLocalRoot;
|
||||||
|
if (patch.ModelRootOverride != null) s.ModelRootOverride = patch.ModelRootOverride;
|
||||||
|
});
|
||||||
|
|
||||||
|
if (patch.Language != null) L.I.SetLanguage(patch.Language);
|
||||||
|
if (patch.MemoryMb.HasValue || patch.MemoryAuto.HasValue)
|
||||||
|
services.Memory.ApplyAuto(services.Settings.Current.MemoryAuto, services.Settings.Current.MemoryMb);
|
||||||
|
|
||||||
|
return Results.Ok(ToSettingsDto());
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---- 模型源 ---------------------------------------------------------------
|
||||||
|
|
||||||
|
app.MapGet("/api/sources", () =>
|
||||||
|
Results.Ok(services.Settings.Current.Sources.Select(ToSourceDto).ToList()));
|
||||||
|
|
||||||
|
app.MapPost("/api/sources/select", async (ForceRequest? request) =>
|
||||||
|
{
|
||||||
|
var force = request?.Force ?? false;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var fastest = await services.Selector.PickFastestAsync(force, CancellationToken.None);
|
||||||
|
services.Updates.UseRemote(services.DownloadModule.CreateRemote(fastest));
|
||||||
|
return Results.Ok(new LatencyDto(
|
||||||
|
fastest.Id, fastest.Name,
|
||||||
|
services.Selector.LastLatency.TryGetValue(fastest.Id, out var ms) ? ms : 0));
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Console.Error.WriteLine($"[sources] 切换模型源失败: {ex}");
|
||||||
|
return Results.Json(ErrorDto.Of("模型源切换失败"), statusCode: 503);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
app.MapGet("/api/remote/models", async (string? sourceId, bool force) =>
|
||||||
|
{
|
||||||
|
var source = ResolveSource(sourceId);
|
||||||
|
if (source == null) return Results.NotFound(ErrorDto.Of("没有可用的模型源"));
|
||||||
|
|
||||||
|
var index = await services.Sources.FetchAsync(source, force, null, CancellationToken.None);
|
||||||
|
var installed = services.Models.Scan()
|
||||||
|
.ToDictionary(p => p.Id, p => p.Manifest.Version, StringComparer.OrdinalIgnoreCase);
|
||||||
|
|
||||||
|
return Results.Ok(new SourceIndexDto(
|
||||||
|
index.SourceId,
|
||||||
|
index.Root,
|
||||||
|
index.FromCache,
|
||||||
|
index.Error,
|
||||||
|
index.ResolvedFrom,
|
||||||
|
index.Models.Select(m => new RemoteModelDto(
|
||||||
|
m.Id,
|
||||||
|
m.LocalizedName,
|
||||||
|
m.LocalizedDescription,
|
||||||
|
m.Manifest.Version,
|
||||||
|
m.SizeBytes,
|
||||||
|
ModelScanner.HumanSize(m.SizeBytes),
|
||||||
|
m.SourceId,
|
||||||
|
installed.ContainsKey(m.Id),
|
||||||
|
installed.TryGetValue(m.Id, out var v) ? v : null)).ToList()));
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---- 下载 -----------------------------------------------------------------
|
||||||
|
|
||||||
|
app.MapPost("/api/download", async (DownloadRequest? request) =>
|
||||||
|
{
|
||||||
|
if (request == null || string.IsNullOrWhiteSpace(request.ModelId))
|
||||||
|
return Results.BadRequest(ErrorDto.Of("缺少 modelId"));
|
||||||
|
|
||||||
|
var source = ResolveSource(request.SourceId);
|
||||||
|
if (source == null) return Results.NotFound(ErrorDto.Of("没有可用的模型源"));
|
||||||
|
|
||||||
|
var index = await services.Sources.FetchAsync(source, false, null, CancellationToken.None);
|
||||||
|
var model = index.Models.FirstOrDefault(m =>
|
||||||
|
m.Id.Equals(request.ModelId, StringComparison.OrdinalIgnoreCase));
|
||||||
|
if (model == null)
|
||||||
|
return Results.NotFound(ErrorDto.Of($"源里没有模型 {request.ModelId}"));
|
||||||
|
|
||||||
|
var job = services.Downloads.Enqueue(model);
|
||||||
|
return Results.Ok(ToJobDto(job));
|
||||||
|
});
|
||||||
|
|
||||||
|
app.MapGet("/api/download/jobs", () =>
|
||||||
|
Results.Ok(services.Downloads.Jobs.Select(ToJobDto).ToList()));
|
||||||
|
|
||||||
|
app.MapPost("/api/download/{id}/cancel", (string id) =>
|
||||||
|
ActOnJob(id, job => services.Downloads.Cancel(job)));
|
||||||
|
|
||||||
|
app.MapPost("/api/download/{id}/retry", (string id) =>
|
||||||
|
ActOnJob(id, job => services.Downloads.Retry(job)));
|
||||||
|
|
||||||
|
app.MapPost("/api/download/{id}/remove", (string id) =>
|
||||||
|
ActOnJob(id, job => services.Downloads.Remove(job)));
|
||||||
|
|
||||||
|
app.MapPost("/api/download/clear-finished", () =>
|
||||||
|
{
|
||||||
|
services.Downloads.ClearFinished();
|
||||||
|
return Results.Ok(new LaunchResultDto(true, "已清除完成的任务"));
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---- 更新 -----------------------------------------------------------------
|
||||||
|
|
||||||
|
app.MapPost("/api/update/check", async (ForceRequest? request) =>
|
||||||
|
{
|
||||||
|
var force = request?.Force ?? true;
|
||||||
|
var messages = new List<string>();
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var fastest = await services.Selector.PickFastestAsync(force, CancellationToken.None);
|
||||||
|
services.Updates.UseRemote(services.DownloadModule.CreateRemote(fastest));
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Console.Error.WriteLine($"[update] 测速失败,沿用当前源: {ex.Message}");
|
||||||
|
}
|
||||||
|
|
||||||
|
string? launcherLatest = null;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
launcherLatest = await services.LauncherUpdates.CheckAsync(
|
||||||
|
services.Updates.Remote, CancellationToken.None);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Console.Error.WriteLine($"[update] 启动器版本检查失败: {ex.Message}");
|
||||||
|
}
|
||||||
|
|
||||||
|
var progress = new Progress<UpdateProgress>(p =>
|
||||||
|
{
|
||||||
|
if (!string.IsNullOrWhiteSpace(p.Message)) messages.Add(p.Message);
|
||||||
|
});
|
||||||
|
|
||||||
|
var result = await services.Updates.RunAsync(force, progress, CancellationToken.None);
|
||||||
|
|
||||||
|
return Results.Ok(new UpdateCheckDto(
|
||||||
|
result.Outcome.ToString(),
|
||||||
|
result.Message,
|
||||||
|
result.UpdatedModels,
|
||||||
|
result.ModelNames,
|
||||||
|
result.LauncherMessage,
|
||||||
|
result.Error,
|
||||||
|
launcherLatest,
|
||||||
|
services.Updates.Remote.DisplayName,
|
||||||
|
services.Selector.LastLatency
|
||||||
|
.Select(kv => new LatencyDto(
|
||||||
|
kv.Key,
|
||||||
|
SourcePreset.Find(kv.Key)?.Name ?? kv.Key,
|
||||||
|
kv.Value))
|
||||||
|
.ToList()));
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---- 关于 -----------------------------------------------------------------
|
||||||
|
|
||||||
|
app.MapGet("/api/about", async () =>
|
||||||
|
{
|
||||||
|
var repository = services.Settings.Current.UpdateRepository;
|
||||||
|
var contributors = new List<ContributorDto>();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
foreach (var c in await ContributorsService.FetchAsync(repository, CancellationToken.None))
|
||||||
|
contributors.Add(new ContributorDto(c.DisplayName, c.Contributions, c.AvatarUrl));
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Console.Error.WriteLine($"[about] 读取贡献者失败: {ex.Message}");
|
||||||
|
}
|
||||||
|
|
||||||
|
return Results.Ok(new AboutDto(
|
||||||
|
"Morris GC",
|
||||||
|
LauncherRuntimeInfo.CurrentLauncherVersion,
|
||||||
|
LauncherRuntimeInfo.CurrentRid,
|
||||||
|
repository,
|
||||||
|
contributors,
|
||||||
|
// 「关于」页展示的技术栈信息:源码语言与前端框架。
|
||||||
|
SourceLanguage: "C#",
|
||||||
|
Frontend: "Flutter"));
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---- 系统集成 -------------------------------------------------------------
|
||||||
|
|
||||||
|
app.MapPost("/api/shell/open-folder", (PathRequest? request) =>
|
||||||
|
{
|
||||||
|
var path = request?.Path;
|
||||||
|
if (string.IsNullOrWhiteSpace(path))
|
||||||
|
return Results.BadRequest(ErrorDto.Of("缺少 path"));
|
||||||
|
|
||||||
|
// 只允许打开启动器自己的目录,避免前端被当成任意路径执行器
|
||||||
|
if (!IsInsideKnownRoot(path!))
|
||||||
|
return Results.BadRequest(ErrorDto.Of("只允许打开启动器自己的目录"));
|
||||||
|
|
||||||
|
Shell.OpenFolder(path!);
|
||||||
|
return Results.Ok(new LaunchResultDto(true, "已打开目录"));
|
||||||
|
});
|
||||||
|
|
||||||
|
app.MapPost("/api/shell/open-url", (UrlRequest? request) =>
|
||||||
|
{
|
||||||
|
var url = request?.Url;
|
||||||
|
if (string.IsNullOrWhiteSpace(url) || url.Length > 2048 ||
|
||||||
|
!Uri.TryCreate(url, UriKind.Absolute, out var uri))
|
||||||
|
return Results.BadRequest(ErrorDto.Of("URL 无效"));
|
||||||
|
|
||||||
|
if (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps)
|
||||||
|
return Results.BadRequest(ErrorDto.Of("只允许 http/https 链接"));
|
||||||
|
|
||||||
|
if (!string.IsNullOrEmpty(uri.UserInfo))
|
||||||
|
return Results.BadRequest(ErrorDto.Of("URL 不允许携带账号密码"));
|
||||||
|
|
||||||
|
Shell.OpenUrl(url!);
|
||||||
|
return Results.Ok(new LaunchResultDto(true, "已打开链接"));
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---- 启动 -----------------------------------------------------------------
|
||||||
|
|
||||||
|
WriteEndpointFile(services, port);
|
||||||
|
Console.WriteLine($"[GC-UI] 后端已启动: http://127.0.0.1:{port}");
|
||||||
|
Console.WriteLine($"[GC-UI] 模型库: {services.Paths.ModelRoot}");
|
||||||
|
|
||||||
|
return app;
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// 局部辅助
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
static void WriteEndpointFile(AppServices services, int port)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var file = Path.Combine(services.Paths.HomeRoot, "ui-backend.json");
|
||||||
|
var payload = JsonSerializer.Serialize(new
|
||||||
|
{
|
||||||
|
port,
|
||||||
|
pid = Environment.ProcessId,
|
||||||
|
url = $"http://127.0.0.1:{port}",
|
||||||
|
version = LauncherRuntimeInfo.CurrentLauncherVersion,
|
||||||
|
platform = LauncherRuntimeInfo.CurrentRid,
|
||||||
|
startedAt = DateTimeOffset.UtcNow.ToString("o")
|
||||||
|
}, new JsonSerializerOptions { WriteIndented = true });
|
||||||
|
|
||||||
|
File.WriteAllText(file, payload);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Console.Error.WriteLine($"[GC-UI] 写入端点文件失败: {ex.Message}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>按扩展名推断图片 MIME;模型封面允许 png / jpg / webp / gif。</summary>
|
||||||
|
static string GuessImageContentType(string path) => Path.GetExtension(path).ToLowerInvariant() switch
|
||||||
|
{
|
||||||
|
".jpg" or ".jpeg" => "image/jpeg",
|
||||||
|
".webp" => "image/webp",
|
||||||
|
".gif" => "image/gif",
|
||||||
|
".bmp" => "image/bmp",
|
||||||
|
".svg" => "image/svg+xml",
|
||||||
|
_ => "image/png"
|
||||||
|
};
|
||||||
|
|
||||||
|
ModelDto ToModelDto(ModelPackage package) => new( package.Id,
|
||||||
|
package.LocalizedName,
|
||||||
|
package.LocalizedDescription,
|
||||||
|
package.Manifest.Version,
|
||||||
|
package.Manifest.Author,
|
||||||
|
package.SizeBytes,
|
||||||
|
ModelScanner.HumanSize(package.SizeBytes),
|
||||||
|
package.Manifest.Tags ?? new List<string>(),
|
||||||
|
File.Exists(package.PreviewPath),
|
||||||
|
$"/api/models/{package.Id}/preview",
|
||||||
|
package.Directory,
|
||||||
|
package.DataDirectory);
|
||||||
|
|
||||||
|
SourceDto ToSourceDto(ModelSource source) => new(
|
||||||
|
source.Id,
|
||||||
|
string.IsNullOrWhiteSpace(source.Name) ? source.Id : source.Name,
|
||||||
|
source.Url,
|
||||||
|
source.Enabled,
|
||||||
|
source.BuiltIn,
|
||||||
|
source.DisplayHost);
|
||||||
|
|
||||||
|
SettingsDto ToSettingsDto() => new(
|
||||||
|
services.Settings.Current.Language,
|
||||||
|
services.Settings.Current.Theme,
|
||||||
|
services.Settings.Current.AccentColor,
|
||||||
|
services.Settings.Current.RenderFps,
|
||||||
|
services.Settings.Current.MemoryMb,
|
||||||
|
services.Settings.Current.MemoryAuto,
|
||||||
|
services.Settings.Current.AutoUpdateOnStartup,
|
||||||
|
services.Settings.Current.RequireSignedManifest,
|
||||||
|
services.Settings.Current.UpdateRepository,
|
||||||
|
services.Settings.Current.UpdateLocalRoot,
|
||||||
|
services.Settings.Current.ModelRootOverride,
|
||||||
|
services.Memory.BudgetMb,
|
||||||
|
services.Memory.UsageText,
|
||||||
|
services.Paths.ModelRoot,
|
||||||
|
services.Paths.DataRoot,
|
||||||
|
services.Paths.SettingsFile,
|
||||||
|
LauncherRuntimeInfo.CurrentLauncherVersion,
|
||||||
|
LauncherRuntimeInfo.CurrentRid,
|
||||||
|
services.Settings.Current.Sources.Select(ToSourceDto).ToList(),
|
||||||
|
L.Supported.Select(s => new LanguageDto(s.Code, s.Label)).ToList());
|
||||||
|
|
||||||
|
JobDto ToJobDto(IDownloadJob job) => new(
|
||||||
|
job.Id,
|
||||||
|
job.Model.Id,
|
||||||
|
job.Name,
|
||||||
|
job.Version,
|
||||||
|
job.State.ToString(),
|
||||||
|
job.Progress,
|
||||||
|
job.StatusText,
|
||||||
|
job.DetailText,
|
||||||
|
job.Error,
|
||||||
|
job.IsActive,
|
||||||
|
job.CanRetry,
|
||||||
|
job.IsDone);
|
||||||
|
|
||||||
|
ModelSource? ResolveSource(string? sourceId)
|
||||||
|
{
|
||||||
|
var sources = services.Settings.Current.Sources;
|
||||||
|
if (!string.IsNullOrWhiteSpace(sourceId))
|
||||||
|
{
|
||||||
|
var exact = sources.FirstOrDefault(s =>
|
||||||
|
s.Id.Equals(sourceId, StringComparison.OrdinalIgnoreCase));
|
||||||
|
if (exact != null) return exact;
|
||||||
|
}
|
||||||
|
|
||||||
|
return sources.FirstOrDefault(s => s.Enabled && !string.IsNullOrWhiteSpace(s.Url))
|
||||||
|
?? sources.FirstOrDefault();
|
||||||
|
}
|
||||||
|
|
||||||
|
IResult ActOnJob(string id, Action<IDownloadJob> action)
|
||||||
|
{
|
||||||
|
if (!IsSafeId(id)) return Results.BadRequest(ErrorDto.Of("任务标识无效"));
|
||||||
|
var job = services.Downloads.Jobs.FirstOrDefault(j =>
|
||||||
|
j.Id.Equals(id, StringComparison.OrdinalIgnoreCase));
|
||||||
|
if (job == null) return Results.NotFound(ErrorDto.Of($"没有找到任务 {id}"));
|
||||||
|
|
||||||
|
action(job);
|
||||||
|
return Results.Ok(ToJobDto(job));
|
||||||
|
}
|
||||||
|
|
||||||
|
bool IsInsideKnownRoot(string path)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var full = Path.GetFullPath(path);
|
||||||
|
var roots = new[]
|
||||||
|
{
|
||||||
|
services.Paths.ModelRoot,
|
||||||
|
services.Paths.DataRoot,
|
||||||
|
services.Paths.HomeRoot,
|
||||||
|
services.Paths.AppRoot
|
||||||
|
};
|
||||||
|
|
||||||
|
foreach (var root in roots)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(root)) continue;
|
||||||
|
var rootFull = Path.GetFullPath(root);
|
||||||
|
if (full.Equals(rootFull, StringComparison.OrdinalIgnoreCase)) return true;
|
||||||
|
if (full.StartsWith(rootFull + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 路由标识:只允许字母数字开头,后接字母数字/点/下划线/短横线,长度上限 64。
|
||||||
|
// 用于模型 id、任务 id,杜绝 `../` 之类的路径穿越尝试。
|
||||||
|
bool IsSafeId(string? id) => !string.IsNullOrEmpty(id) && safeIdRegex.IsMatch(id);
|
||||||
|
|
||||||
|
// 更新仓库地址:必须是 https、不带账号密码、不是回环/内网 IP。
|
||||||
|
// 防止把本地后端当成 SSRF 跳板去访问内网服务。
|
||||||
|
bool IsAllowedRepository(string value)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(value)) return false;
|
||||||
|
if (!Uri.TryCreate(value, UriKind.Absolute, out var uri)) return false;
|
||||||
|
if (uri.Scheme != Uri.UriSchemeHttps) return false;
|
||||||
|
if (!string.IsNullOrEmpty(uri.UserInfo)) return false;
|
||||||
|
if (string.Equals(uri.Host, "localhost", StringComparison.OrdinalIgnoreCase)) return false;
|
||||||
|
if (System.Net.IPAddress.TryParse(uri.Host, out var ip) &&
|
||||||
|
(System.Net.IPAddress.IsLoopback(ip) || IsPrivateAddress(ip)))
|
||||||
|
return false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool IsPrivateAddress(System.Net.IPAddress ip)
|
||||||
|
{
|
||||||
|
var bytes = ip.GetAddressBytes();
|
||||||
|
if (bytes.Length != 4) return false;
|
||||||
|
return bytes[0] == 10
|
||||||
|
|| (bytes[0] == 172 && bytes[1] >= 16 && bytes[1] <= 31)
|
||||||
|
|| (bytes[0] == 192 && bytes[1] == 168)
|
||||||
|
|| (bytes[0] == 169 && bytes[1] == 254);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int ResolvePort(string[] args)
|
||||||
|
{
|
||||||
|
// 优先用启动器传来的端口(GC_UI_PORT),保证前端拼出来的 baseUrl 和这里一致。
|
||||||
|
var env = Environment.GetEnvironmentVariable(GcUiContract.PortEnvVar);
|
||||||
|
if (int.TryParse(env, out var fromEnv) && fromEnv > 0 && fromEnv < 65536) return fromEnv;
|
||||||
|
|
||||||
|
for (var i = 0; i < args.Length; i++)
|
||||||
|
{
|
||||||
|
if (args[i] == "--port" && i + 1 < args.Length &&
|
||||||
|
int.TryParse(args[i + 1], out var next) && next > 0 && next < 65536)
|
||||||
|
return next;
|
||||||
|
|
||||||
|
const string prefix = "--port=";
|
||||||
|
if (args[i].StartsWith(prefix, StringComparison.Ordinal) &&
|
||||||
|
int.TryParse(args[i][prefix.Length..], out var inline) && inline > 0 && inline < 65536)
|
||||||
|
return inline;
|
||||||
|
}
|
||||||
|
|
||||||
|
return GcUiContract.DefaultPort;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||||
|
|
||||||
|
<!--
|
||||||
|
GC-UI 后端:把原来「启动器 = UI + 服务」的一体式结构拆成
|
||||||
|
· 后端(本工程):模型扫描 / 下载 / 更新 / 设置 / 模型窗口宿主,只暴露本地 HTTP API
|
||||||
|
· 前端(GC-UI/frontend,Flutter):只做界面,通过 HTTP 调后端
|
||||||
|
|
||||||
|
模型窗口仍然由 .NET 侧承载:模型 dll 返回的是 Avalonia Control,
|
||||||
|
换掉渲染栈等于换掉模型契约,所以「渲染留在 .NET,界面交给 Flutter」是唯一不破坏模型生态的切法。
|
||||||
|
-->
|
||||||
|
<PropertyGroup>
|
||||||
|
<OutputType>Exe</OutputType>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||||
|
<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" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
using GC.UI.Server;
|
||||||
|
|
||||||
|
// 独立进程入口:`GC.UI.Server --port 17890`
|
||||||
|
// 启动器在进程内直接调用 BackendServer.Start,不会走到这里。
|
||||||
|
var app = BackendServer.StartFromCommandLine(args);
|
||||||
|
app.Run();
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
@echo off
|
||||||
|
REM 构建 GC-UI 前端(Windows 上运行;macOS 请用 build-ui.sh)。
|
||||||
|
REM
|
||||||
|
REM GC-UI\build-ui.cmd
|
||||||
|
|
||||||
|
setlocal
|
||||||
|
set ROOT=%~dp0..
|
||||||
|
set FRONTEND=%ROOT%\GC-UI\frontend
|
||||||
|
|
||||||
|
where flutter >nul 2>nul
|
||||||
|
if errorlevel 1 (
|
||||||
|
echo 找不到 flutter,请先安装 Flutter SDK 并加入 PATH。
|
||||||
|
exit /b 1
|
||||||
|
)
|
||||||
|
|
||||||
|
echo ==^> 构建后端(GC.UI.Server)
|
||||||
|
dotnet build "%ROOT%\GC-UI\backend\GC.UI.Server\GC.UI.Server.csproj" -c Release
|
||||||
|
if errorlevel 1 exit /b 1
|
||||||
|
|
||||||
|
echo ==^> 构建前端(windows)
|
||||||
|
cd /d "%FRONTEND%"
|
||||||
|
call flutter pub get
|
||||||
|
if errorlevel 1 exit /b 1
|
||||||
|
call flutter build windows --release
|
||||||
|
if errorlevel 1 exit /b 1
|
||||||
|
|
||||||
|
echo ==^> 完成
|
||||||
|
echo 产物: %FRONTEND%\build\windows\x64\runner\Release\
|
||||||
|
endlocal
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# 构建 GC-UI 前端(macOS / Linux 上运行;Windows 请用 build-ui.cmd)。
|
||||||
|
#
|
||||||
|
# ./GC-UI/build-ui.sh # 构建当前平台
|
||||||
|
# ./GC-UI/build-ui.sh macos # 指定目标
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||||
|
FRONTEND="$ROOT/GC-UI/frontend"
|
||||||
|
TARGET="${1:-}"
|
||||||
|
|
||||||
|
if ! command -v flutter >/dev/null 2>&1; then
|
||||||
|
echo "找不到 flutter,请先安装 Flutter SDK 并加入 PATH。" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ -z "$TARGET" ]; then
|
||||||
|
case "$(uname -s)" in
|
||||||
|
Darwin) TARGET="macos" ;;
|
||||||
|
*) TARGET="macos" ;;
|
||||||
|
esac
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "==> 构建后端(GC.UI.Server)"
|
||||||
|
dotnet build "$ROOT/GC-UI/backend/GC.UI.Server/GC.UI.Server.csproj" -c Release
|
||||||
|
|
||||||
|
echo "==> 构建前端($TARGET)"
|
||||||
|
cd "$FRONTEND"
|
||||||
|
flutter pub get
|
||||||
|
flutter build "$TARGET" --release
|
||||||
|
|
||||||
|
echo "==> 完成"
|
||||||
|
case "$TARGET" in
|
||||||
|
macos) echo "产物: $FRONTEND/build/macos/Build/Products/Release/" ;;
|
||||||
|
windows) echo "产物: $FRONTEND/build/windows/x64/runner/Release/" ;;
|
||||||
|
*) echo "产物: $FRONTEND/build/$TARGET/" ;;
|
||||||
|
esac
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
# Miscellaneous
|
||||||
|
*.class
|
||||||
|
*.log
|
||||||
|
*.pyc
|
||||||
|
*.swp
|
||||||
|
.DS_Store
|
||||||
|
.atom/
|
||||||
|
.buildlog/
|
||||||
|
.history
|
||||||
|
.svn/
|
||||||
|
migrate_working_dir/
|
||||||
|
|
||||||
|
# IntelliJ related
|
||||||
|
*.iml
|
||||||
|
*.ipr
|
||||||
|
*.iws
|
||||||
|
.idea/
|
||||||
|
|
||||||
|
# The .vscode folder contains launch configuration and tasks you configure in
|
||||||
|
# VS Code which you may wish to be included in version control, so this line
|
||||||
|
# is commented out by default.
|
||||||
|
#.vscode/
|
||||||
|
|
||||||
|
# Flutter/Dart/Pub related
|
||||||
|
**/doc/api/
|
||||||
|
**/ios/Flutter/.last_build_id
|
||||||
|
.dart_tool/
|
||||||
|
.flutter-plugins
|
||||||
|
.flutter-plugins-dependencies
|
||||||
|
.pub-cache/
|
||||||
|
.pub/
|
||||||
|
/build/
|
||||||
|
|
||||||
|
# Symbolication related
|
||||||
|
app.*.symbols
|
||||||
|
|
||||||
|
# Obfuscation related
|
||||||
|
app.*.map.json
|
||||||
|
|
||||||
|
# Android Studio will place build artifacts here
|
||||||
|
/android/app/debug
|
||||||
|
/android/app/profile
|
||||||
|
/android/app/release
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
# This file tracks properties of this Flutter project.
|
||||||
|
# Used by Flutter tool to assess capabilities and perform upgrades etc.
|
||||||
|
#
|
||||||
|
# This file should be version controlled and should not be manually edited.
|
||||||
|
|
||||||
|
version:
|
||||||
|
revision: "dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668"
|
||||||
|
channel: "stable"
|
||||||
|
|
||||||
|
project_type: app
|
||||||
|
|
||||||
|
# Tracks metadata for the flutter migrate command
|
||||||
|
migration:
|
||||||
|
platforms:
|
||||||
|
- platform: root
|
||||||
|
create_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
|
||||||
|
base_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
|
||||||
|
- platform: linux
|
||||||
|
create_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
|
||||||
|
base_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
|
||||||
|
- platform: macos
|
||||||
|
create_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
|
||||||
|
base_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
|
||||||
|
- platform: windows
|
||||||
|
create_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
|
||||||
|
base_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
|
||||||
|
|
||||||
|
# User provided section
|
||||||
|
|
||||||
|
# List of Local paths (relative to this file) that should be
|
||||||
|
# ignored by the migrate tool.
|
||||||
|
#
|
||||||
|
# Files that are not part of the templates will be ignored by default.
|
||||||
|
unmanaged_files:
|
||||||
|
- 'lib/main.dart'
|
||||||
|
- 'ios/Runner.xcodeproj/project.pbxproj'
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
# gc_ui
|
||||||
|
|
||||||
|
GC launcher UI (Flutter frontend)
|
||||||
|
|
||||||
|
## Getting Started
|
||||||
|
|
||||||
|
This project is a starting point for a Flutter application.
|
||||||
|
|
||||||
|
A few resources to get you started if this is your first Flutter project:
|
||||||
|
|
||||||
|
- [Lab: Write your first Flutter app](https://docs.flutter.dev/get-started/codelab)
|
||||||
|
- [Cookbook: Useful Flutter samples](https://docs.flutter.dev/cookbook)
|
||||||
|
|
||||||
|
For help getting started with Flutter development, view the
|
||||||
|
[online documentation](https://docs.flutter.dev/), which offers tutorials,
|
||||||
|
samples, guidance on mobile development, and a full API reference.
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
# This file configures the analyzer, which statically analyzes Dart code to
|
||||||
|
# check for errors, warnings, and lints.
|
||||||
|
#
|
||||||
|
# The issues identified by the analyzer are surfaced in the UI of Dart-enabled
|
||||||
|
# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be
|
||||||
|
# invoked from the command line by running `flutter analyze`.
|
||||||
|
|
||||||
|
# The following line activates a set of recommended lints for Flutter apps,
|
||||||
|
# packages, and plugins designed to encourage good coding practices.
|
||||||
|
include: package:flutter_lints/flutter.yaml
|
||||||
|
|
||||||
|
linter:
|
||||||
|
# The lint rules applied to this project can be customized in the
|
||||||
|
# section below to disable rules from the `package:flutter_lints/flutter.yaml`
|
||||||
|
# included above or to enable additional rules. A list of all available lints
|
||||||
|
# and their documentation is published at https://dart.dev/lints.
|
||||||
|
#
|
||||||
|
# Instead of disabling a lint rule for the entire project in the
|
||||||
|
# section below, it can also be suppressed for a single line of code
|
||||||
|
# or a specific dart file by using the `// ignore: name_of_lint` and
|
||||||
|
# `// ignore_for_file: name_of_lint` syntax on the line or in the file
|
||||||
|
# producing the lint.
|
||||||
|
rules:
|
||||||
|
# avoid_print: false # Uncomment to disable the `avoid_print` rule
|
||||||
|
# prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule
|
||||||
|
|
||||||
|
# Additional information about this file can be found at
|
||||||
|
# https://dart.dev/guides/language/analysis-options
|
||||||
@@ -0,0 +1,521 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:http/http.dart' as http;
|
||||||
|
|
||||||
|
/// 后端返回的错误(HTTP 非 2xx,或后端明确返回 ok=false)。
|
||||||
|
class ApiException implements Exception {
|
||||||
|
ApiException(this.message, {this.statusCode});
|
||||||
|
|
||||||
|
final String message;
|
||||||
|
final int? statusCode;
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() => message;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 已安装模型。
|
||||||
|
class ModelInfo {
|
||||||
|
ModelInfo.fromJson(Map<String, dynamic> json)
|
||||||
|
: id = json['id'] as String? ?? '',
|
||||||
|
name = json['name'] as String? ?? '',
|
||||||
|
description = json['description'] as String? ?? '',
|
||||||
|
version = json['version'] as String? ?? '',
|
||||||
|
author = json['author'] as String? ?? '',
|
||||||
|
sizeBytes = (json['sizeBytes'] as num?)?.toInt() ?? 0,
|
||||||
|
sizeText = json['sizeText'] as String? ?? '',
|
||||||
|
tags = _stringList(json['tags']),
|
||||||
|
hasPreview = json['hasPreview'] as bool? ?? false,
|
||||||
|
previewUrl = json['previewUrl'] as String? ?? '',
|
||||||
|
directory = json['directory'] as String? ?? '',
|
||||||
|
dataDirectory = json['dataDirectory'] as String? ?? '';
|
||||||
|
|
||||||
|
final String id;
|
||||||
|
final String name;
|
||||||
|
final String description;
|
||||||
|
final String version;
|
||||||
|
final String author;
|
||||||
|
final int sizeBytes;
|
||||||
|
final String sizeText;
|
||||||
|
final List<String> tags;
|
||||||
|
final bool hasPreview;
|
||||||
|
final String previewUrl;
|
||||||
|
final String directory;
|
||||||
|
final String dataDirectory;
|
||||||
|
|
||||||
|
String get metaText => 'v$version · $sizeText';
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 模型源。
|
||||||
|
class SourceInfo {
|
||||||
|
SourceInfo.fromJson(Map<String, dynamic> json)
|
||||||
|
: id = json['id'] as String? ?? '',
|
||||||
|
name = json['name'] as String? ?? '',
|
||||||
|
url = json['url'] as String? ?? '',
|
||||||
|
enabled = json['enabled'] as bool? ?? false,
|
||||||
|
builtIn = json['builtIn'] as bool? ?? false,
|
||||||
|
host = json['host'] as String? ?? '';
|
||||||
|
|
||||||
|
final String id;
|
||||||
|
final String name;
|
||||||
|
final String url;
|
||||||
|
final bool enabled;
|
||||||
|
final bool builtIn;
|
||||||
|
final String host;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 远端可下载模型。
|
||||||
|
class RemoteModelInfo {
|
||||||
|
RemoteModelInfo.fromJson(Map<String, dynamic> json)
|
||||||
|
: id = json['id'] as String? ?? '',
|
||||||
|
name = json['name'] as String? ?? '',
|
||||||
|
description = json['description'] as String? ?? '',
|
||||||
|
version = json['version'] as String? ?? '',
|
||||||
|
sizeBytes = (json['sizeBytes'] as num?)?.toInt() ?? 0,
|
||||||
|
sizeText = json['sizeText'] as String? ?? '',
|
||||||
|
sourceId = json['sourceId'] as String? ?? '',
|
||||||
|
installed = json['installed'] as bool? ?? false,
|
||||||
|
installedVersion = json['installedVersion'] as String?;
|
||||||
|
|
||||||
|
final String id;
|
||||||
|
final String name;
|
||||||
|
final String description;
|
||||||
|
final String version;
|
||||||
|
final int sizeBytes;
|
||||||
|
final String sizeText;
|
||||||
|
final String sourceId;
|
||||||
|
final bool installed;
|
||||||
|
final String? installedVersion;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 一次远端源索引结果。
|
||||||
|
class SourceIndexInfo {
|
||||||
|
SourceIndexInfo.fromJson(Map<String, dynamic> json)
|
||||||
|
: sourceId = json['sourceId'] as String? ?? '',
|
||||||
|
root = json['root'] as String? ?? '',
|
||||||
|
fromCache = json['fromCache'] as bool? ?? false,
|
||||||
|
error = json['error'] as String?,
|
||||||
|
resolvedFrom = json['resolvedFrom'] as String? ?? '',
|
||||||
|
models = (json['models'] as List<dynamic>? ?? const [])
|
||||||
|
.map((e) => RemoteModelInfo.fromJson(e as Map<String, dynamic>))
|
||||||
|
.toList();
|
||||||
|
|
||||||
|
final String sourceId;
|
||||||
|
final String root;
|
||||||
|
final bool fromCache;
|
||||||
|
final String? error;
|
||||||
|
final String resolvedFrom;
|
||||||
|
final List<RemoteModelInfo> models;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 下载任务。
|
||||||
|
class JobInfo {
|
||||||
|
JobInfo.fromJson(Map<String, dynamic> json)
|
||||||
|
: id = json['id'] as String? ?? '',
|
||||||
|
modelId = json['modelId'] as String? ?? '',
|
||||||
|
name = json['name'] as String? ?? '',
|
||||||
|
version = json['version'] as String? ?? '',
|
||||||
|
state = json['state'] as String? ?? 'Queued',
|
||||||
|
progress = (json['progress'] as num?)?.toDouble() ?? 0,
|
||||||
|
statusText = json['statusText'] as String? ?? '',
|
||||||
|
detailText = json['detailText'] as String? ?? '',
|
||||||
|
error = json['error'] as String?,
|
||||||
|
isActive = json['isActive'] as bool? ?? false,
|
||||||
|
canRetry = json['canRetry'] as bool? ?? false,
|
||||||
|
isDone = json['isDone'] as bool? ?? false;
|
||||||
|
|
||||||
|
final String id;
|
||||||
|
final String modelId;
|
||||||
|
final String name;
|
||||||
|
final String version;
|
||||||
|
final String state;
|
||||||
|
final double progress;
|
||||||
|
final String statusText;
|
||||||
|
final String detailText;
|
||||||
|
final String? error;
|
||||||
|
final bool isActive;
|
||||||
|
final bool canRetry;
|
||||||
|
final bool isDone;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 界面语言选项。
|
||||||
|
class LanguageInfo {
|
||||||
|
LanguageInfo.fromJson(Map<String, dynamic> json)
|
||||||
|
: code = json['code'] as String? ?? '',
|
||||||
|
label = json['label'] as String? ?? '';
|
||||||
|
|
||||||
|
final String code;
|
||||||
|
final String label;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 设置。
|
||||||
|
class SettingsInfo {
|
||||||
|
SettingsInfo.fromJson(Map<String, dynamic> json)
|
||||||
|
: language = json['language'] as String? ?? 'auto',
|
||||||
|
theme = json['theme'] as String? ?? 'light',
|
||||||
|
accentColor = json['accentColor'] as String? ?? '#8FB6FF',
|
||||||
|
renderFps = (json['renderFps'] as num?)?.toInt() ?? 120,
|
||||||
|
memoryMb = (json['memoryMb'] as num?)?.toInt() ?? 2048,
|
||||||
|
memoryAuto = json['memoryAuto'] as bool? ?? true,
|
||||||
|
autoUpdateOnStartup = json['autoUpdateOnStartup'] as bool? ?? true,
|
||||||
|
requireSignedManifest = json['requireSignedManifest'] as bool? ?? true,
|
||||||
|
updateRepository = json['updateRepository'] as String? ?? '',
|
||||||
|
updateLocalRoot = json['updateLocalRoot'] as String?,
|
||||||
|
modelRootOverride = json['modelRootOverride'] as String?,
|
||||||
|
memoryBudgetMb = (json['memoryBudgetMb'] as num?)?.toInt() ?? 0,
|
||||||
|
memoryUsageText = json['memoryUsageText'] as String? ?? '',
|
||||||
|
modelRoot = json['modelRoot'] as String? ?? '',
|
||||||
|
dataRoot = json['dataRoot'] as String? ?? '',
|
||||||
|
settingsFile = json['settingsFile'] as String? ?? '',
|
||||||
|
version = json['version'] as String? ?? '',
|
||||||
|
platform = json['platform'] as String? ?? '',
|
||||||
|
sources = (json['sources'] as List<dynamic>? ?? const [])
|
||||||
|
.map((e) => SourceInfo.fromJson(e as Map<String, dynamic>))
|
||||||
|
.toList(),
|
||||||
|
languages = (json['languages'] as List<dynamic>? ?? const [])
|
||||||
|
.map((e) => LanguageInfo.fromJson(e as Map<String, dynamic>))
|
||||||
|
.toList();
|
||||||
|
|
||||||
|
final String language;
|
||||||
|
final String theme;
|
||||||
|
final String accentColor;
|
||||||
|
final int renderFps;
|
||||||
|
final int memoryMb;
|
||||||
|
final bool memoryAuto;
|
||||||
|
final bool autoUpdateOnStartup;
|
||||||
|
final bool requireSignedManifest;
|
||||||
|
final String updateRepository;
|
||||||
|
final String? updateLocalRoot;
|
||||||
|
final String? modelRootOverride;
|
||||||
|
final int memoryBudgetMb;
|
||||||
|
final String memoryUsageText;
|
||||||
|
final String modelRoot;
|
||||||
|
final String dataRoot;
|
||||||
|
final String settingsFile;
|
||||||
|
final String version;
|
||||||
|
final String platform;
|
||||||
|
final List<SourceInfo> sources;
|
||||||
|
final List<LanguageInfo> languages;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 设置补丁:只提交要改的字段。
|
||||||
|
class SettingsPatch {
|
||||||
|
const SettingsPatch({
|
||||||
|
this.language,
|
||||||
|
this.theme,
|
||||||
|
this.accentColor,
|
||||||
|
this.renderFps,
|
||||||
|
this.memoryMb,
|
||||||
|
this.memoryAuto,
|
||||||
|
this.autoUpdateOnStartup,
|
||||||
|
this.requireSignedManifest,
|
||||||
|
this.updateRepository,
|
||||||
|
this.updateLocalRoot,
|
||||||
|
this.modelRootOverride,
|
||||||
|
});
|
||||||
|
|
||||||
|
final String? language;
|
||||||
|
final String? theme;
|
||||||
|
final String? accentColor;
|
||||||
|
final int? renderFps;
|
||||||
|
final int? memoryMb;
|
||||||
|
final bool? memoryAuto;
|
||||||
|
final bool? autoUpdateOnStartup;
|
||||||
|
final bool? requireSignedManifest;
|
||||||
|
final String? updateRepository;
|
||||||
|
final String? updateLocalRoot;
|
||||||
|
final String? modelRootOverride;
|
||||||
|
|
||||||
|
Map<String, dynamic> toJson() {
|
||||||
|
final map = <String, dynamic>{};
|
||||||
|
if (language != null) map['language'] = language;
|
||||||
|
if (theme != null) map['theme'] = theme;
|
||||||
|
if (accentColor != null) map['accentColor'] = accentColor;
|
||||||
|
if (renderFps != null) map['renderFps'] = renderFps;
|
||||||
|
if (memoryMb != null) map['memoryMb'] = memoryMb;
|
||||||
|
if (memoryAuto != null) map['memoryAuto'] = memoryAuto;
|
||||||
|
if (autoUpdateOnStartup != null) map['autoUpdateOnStartup'] = autoUpdateOnStartup;
|
||||||
|
if (requireSignedManifest != null) map['requireSignedManifest'] = requireSignedManifest;
|
||||||
|
if (updateRepository != null) map['updateRepository'] = updateRepository;
|
||||||
|
if (updateLocalRoot != null) map['updateLocalRoot'] = updateLocalRoot;
|
||||||
|
if (modelRootOverride != null) map['modelRootOverride'] = modelRootOverride;
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 健康检查。
|
||||||
|
class HealthInfo {
|
||||||
|
HealthInfo.fromJson(Map<String, dynamic> json)
|
||||||
|
: ok = json['ok'] as bool? ?? false,
|
||||||
|
version = json['version'] as String? ?? '',
|
||||||
|
platform = json['platform'] as String? ?? '',
|
||||||
|
uiAvailable = json['uiAvailable'] as bool? ?? false,
|
||||||
|
uiError = json['uiError'] as String?;
|
||||||
|
|
||||||
|
final bool ok;
|
||||||
|
final String version;
|
||||||
|
final String platform;
|
||||||
|
final bool uiAvailable;
|
||||||
|
final String? uiError;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 一次更新检查的结果。
|
||||||
|
class UpdateCheckInfo {
|
||||||
|
UpdateCheckInfo.fromJson(Map<String, dynamic> json)
|
||||||
|
: outcome = json['outcome'] as String? ?? '',
|
||||||
|
message = json['message'] as String? ?? '',
|
||||||
|
updatedModels = (json['updatedModels'] as num?)?.toInt() ?? 0,
|
||||||
|
modelNames = _stringList(json['modelNames']),
|
||||||
|
launcherMessage = json['launcherMessage'] as String?,
|
||||||
|
error = json['error'] as String?,
|
||||||
|
launcherLatest = json['launcherLatest'] as String?,
|
||||||
|
sourceName = json['sourceName'] as String? ?? '';
|
||||||
|
|
||||||
|
final String outcome;
|
||||||
|
final String message;
|
||||||
|
final int updatedModels;
|
||||||
|
final List<String> modelNames;
|
||||||
|
final String? launcherMessage;
|
||||||
|
final String? error;
|
||||||
|
final String? launcherLatest;
|
||||||
|
final String sourceName;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 贡献者。
|
||||||
|
class ContributorInfo {
|
||||||
|
ContributorInfo.fromJson(Map<String, dynamic> json)
|
||||||
|
: name = json['name'] as String? ?? '',
|
||||||
|
contributions = (json['contributions'] as num?)?.toInt() ?? 0,
|
||||||
|
avatarUrl = json['avatarUrl'] as String?;
|
||||||
|
|
||||||
|
final String name;
|
||||||
|
final int contributions;
|
||||||
|
final String? avatarUrl;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 关于页数据。
|
||||||
|
class AboutInfo {
|
||||||
|
AboutInfo.fromJson(Map<String, dynamic> json)
|
||||||
|
: appName = json['appName'] as String? ?? '',
|
||||||
|
version = json['version'] as String? ?? '',
|
||||||
|
platform = json['platform'] as String? ?? '',
|
||||||
|
repository = json['repository'] as String? ?? '',
|
||||||
|
sourceLanguage = json['sourceLanguage'] as String? ?? 'C#',
|
||||||
|
frontend = json['frontend'] as String? ?? 'Flutter',
|
||||||
|
contributors = (json['contributors'] as List<dynamic>? ?? const [])
|
||||||
|
.map((e) => ContributorInfo.fromJson(e as Map<String, dynamic>))
|
||||||
|
.toList();
|
||||||
|
|
||||||
|
final String appName;
|
||||||
|
final String version;
|
||||||
|
final String platform;
|
||||||
|
final String repository;
|
||||||
|
|
||||||
|
/// 源码语言(后端 / 模型层),由后端 `/api/about` 返回。
|
||||||
|
final String sourceLanguage;
|
||||||
|
|
||||||
|
/// 前端框架,由后端 `/api/about` 返回。
|
||||||
|
final String frontend;
|
||||||
|
|
||||||
|
final List<ContributorInfo> contributors;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 通用操作结果。
|
||||||
|
class ActionResult {
|
||||||
|
ActionResult.fromJson(Map<String, dynamic> json)
|
||||||
|
: ok = json['ok'] as bool? ?? false,
|
||||||
|
message = json['message'] as String? ?? '';
|
||||||
|
|
||||||
|
final bool ok;
|
||||||
|
final String message;
|
||||||
|
}
|
||||||
|
|
||||||
|
List<String> _stringList(dynamic value) =>
|
||||||
|
(value as List<dynamic>? ?? const []).map((e) => e.toString()).toList();
|
||||||
|
|
||||||
|
/// GC-UI 后端客户端。
|
||||||
|
///
|
||||||
|
/// 后端是本地伴随进程,端口由启动器(GC-BOOT)选定后通过 `GC_UI_PORT`
|
||||||
|
/// 环境变量传进来 —— 这样端口被占用时换端口不用重新编译前端。
|
||||||
|
/// 也可用 `--dart-define=GC_UI_BASE_URL=http://127.0.0.1:12345` 强制指定。
|
||||||
|
class GcApi {
|
||||||
|
GcApi({String? baseUrl})
|
||||||
|
: baseUrl = baseUrl ?? defaultBaseUrl;
|
||||||
|
|
||||||
|
/// 复用同一个 HTTP 连接:轮询(下载任务每秒一次)时每次都新建连接
|
||||||
|
/// 会不断握手,桌面端也能明显看到延迟抖动。
|
||||||
|
static final http.Client _client = http.Client();
|
||||||
|
|
||||||
|
/// 兜底默认端口,与后端 GC.Services.GcUiContract.DefaultPort 保持一致。
|
||||||
|
static const int fallbackPort = 17890;
|
||||||
|
|
||||||
|
static String get defaultBaseUrl {
|
||||||
|
const fromDefine = String.fromEnvironment('GC_UI_BASE_URL');
|
||||||
|
if (fromDefine.isNotEmpty) return fromDefine;
|
||||||
|
|
||||||
|
final fromEnvUrl = Platform.environment['GC_UI_BASE_URL'];
|
||||||
|
if (fromEnvUrl != null && fromEnvUrl.isNotEmpty) return fromEnvUrl;
|
||||||
|
|
||||||
|
// 启动器通过 GC_UI_PORT 传端口(主路径)。
|
||||||
|
final port = int.tryParse(Platform.environment['GC_UI_PORT'] ?? '');
|
||||||
|
if (port != null) return 'http://127.0.0.1:$port';
|
||||||
|
|
||||||
|
// 手动起后端 / 前端调试时没有环境变量:读后端写的 .GC/ui-backend.json。
|
||||||
|
final discovered = _endpointFileUrl();
|
||||||
|
if (discovered != null) return discovered;
|
||||||
|
|
||||||
|
return 'http://127.0.0.1:$fallbackPort';
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 从运行目录下的 `.GC/ui-backend.json` 发现后端地址。
|
||||||
|
///
|
||||||
|
/// 后端每次启动都会写这个文件(port / pid / url)。只认 24 小时内的记录:
|
||||||
|
/// 更早的多半是上次遗留的,连过去只会得到一个「无法连接」。
|
||||||
|
static String? _endpointFileUrl() {
|
||||||
|
try {
|
||||||
|
final file = File('${Directory.current.path}/.GC/ui-backend.json');
|
||||||
|
if (!file.existsSync()) return null;
|
||||||
|
|
||||||
|
final age = DateTime.now().difference(file.lastModifiedSync());
|
||||||
|
if (age.inHours >= 24) return null;
|
||||||
|
|
||||||
|
final decoded = jsonDecode(file.readAsStringSync());
|
||||||
|
if (decoded is! Map<String, dynamic>) return null;
|
||||||
|
|
||||||
|
final url = decoded['url'];
|
||||||
|
if (url is String && url.startsWith('http://127.0.0.1:')) return url;
|
||||||
|
|
||||||
|
final port = (decoded['port'] as num?)?.toInt();
|
||||||
|
if (port != null && port > 0 && port < 65536) {
|
||||||
|
return 'http://127.0.0.1:$port';
|
||||||
|
}
|
||||||
|
} catch (_) {
|
||||||
|
// 文件损坏 / 无权限:退回默认端口即可
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
final String baseUrl;
|
||||||
|
|
||||||
|
Uri _uri(String path, [Map<String, String>? query]) =>
|
||||||
|
Uri.parse('$baseUrl$path').replace(queryParameters: query);
|
||||||
|
|
||||||
|
Future<dynamic> _send(String method, String path,
|
||||||
|
{Map<String, String>? query, Object? body}) async {
|
||||||
|
final uri = _uri(path, query);
|
||||||
|
late http.Response response;
|
||||||
|
try {
|
||||||
|
switch (method) {
|
||||||
|
case 'GET':
|
||||||
|
response = await _client.get(uri).timeout(const Duration(seconds: 30));
|
||||||
|
break;
|
||||||
|
case 'POST':
|
||||||
|
response = await _client
|
||||||
|
.post(uri,
|
||||||
|
headers: const {'Content-Type': 'application/json'},
|
||||||
|
body: body == null ? null : jsonEncode(body))
|
||||||
|
.timeout(const Duration(seconds: 120));
|
||||||
|
break;
|
||||||
|
case 'DELETE':
|
||||||
|
response = await _client.delete(uri).timeout(const Duration(seconds: 30));
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
throw ApiException('不支持的方法 $method');
|
||||||
|
}
|
||||||
|
} on ApiException {
|
||||||
|
rethrow;
|
||||||
|
} catch (error) {
|
||||||
|
throw ApiException('无法连接后端($baseUrl):$error');
|
||||||
|
}
|
||||||
|
|
||||||
|
final text = utf8.decode(response.bodyBytes);
|
||||||
|
dynamic decoded;
|
||||||
|
if (text.isNotEmpty) {
|
||||||
|
try {
|
||||||
|
decoded = jsonDecode(text);
|
||||||
|
} catch (_) {
|
||||||
|
decoded = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (response.statusCode >= 400) {
|
||||||
|
final message = decoded is Map<String, dynamic>
|
||||||
|
? (decoded['message'] as String? ?? 'HTTP ${response.statusCode}')
|
||||||
|
: 'HTTP ${response.statusCode}';
|
||||||
|
throw ApiException(message, statusCode: response.statusCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
return decoded;
|
||||||
|
}
|
||||||
|
|
||||||
|
List<Map<String, dynamic>> _asList(dynamic value) =>
|
||||||
|
(value as List<dynamic>? ?? const [])
|
||||||
|
.map((e) => e as Map<String, dynamic>)
|
||||||
|
.toList();
|
||||||
|
|
||||||
|
Future<HealthInfo> health() async =>
|
||||||
|
HealthInfo.fromJson(await _send('GET', '/api/health') as Map<String, dynamic>);
|
||||||
|
|
||||||
|
Future<List<ModelInfo>> models() async =>
|
||||||
|
_asList(await _send('GET', '/api/models')).map(ModelInfo.fromJson).toList();
|
||||||
|
|
||||||
|
Future<ActionResult> launchModel(String id) async => ActionResult.fromJson(
|
||||||
|
await _send('POST', '/api/models/$id/launch') as Map<String, dynamic>);
|
||||||
|
|
||||||
|
Future<ActionResult> deleteModel(String id) async => ActionResult.fromJson(
|
||||||
|
await _send('DELETE', '/api/models/$id') as Map<String, dynamic>);
|
||||||
|
|
||||||
|
Future<SettingsInfo> settings() async =>
|
||||||
|
SettingsInfo.fromJson(await _send('GET', '/api/settings') as Map<String, dynamic>);
|
||||||
|
|
||||||
|
Future<SettingsInfo> saveSettings(SettingsPatch patch) async =>
|
||||||
|
SettingsInfo.fromJson(await _send('POST', '/api/settings', body: patch.toJson())
|
||||||
|
as Map<String, dynamic>);
|
||||||
|
|
||||||
|
Future<List<SourceInfo>> sources() async =>
|
||||||
|
_asList(await _send('GET', '/api/sources')).map(SourceInfo.fromJson).toList();
|
||||||
|
|
||||||
|
Future<SourceIndexInfo> remoteModels({String? sourceId, bool force = false}) async =>
|
||||||
|
SourceIndexInfo.fromJson(await _send('GET', '/api/remote/models', query: {
|
||||||
|
if (sourceId != null) 'sourceId': sourceId,
|
||||||
|
'force': force.toString(),
|
||||||
|
}) as Map<String, dynamic>);
|
||||||
|
|
||||||
|
Future<List<JobInfo>> jobs() async =>
|
||||||
|
_asList(await _send('GET', '/api/download/jobs')).map(JobInfo.fromJson).toList();
|
||||||
|
|
||||||
|
Future<JobInfo> startDownload(String sourceId, String modelId) async =>
|
||||||
|
JobInfo.fromJson(await _send('POST', '/api/download',
|
||||||
|
body: {'sourceId': sourceId, 'modelId': modelId}) as Map<String, dynamic>);
|
||||||
|
|
||||||
|
Future<JobInfo> cancelJob(String id) async => JobInfo.fromJson(
|
||||||
|
await _send('POST', '/api/download/$id/cancel') as Map<String, dynamic>);
|
||||||
|
|
||||||
|
Future<JobInfo> retryJob(String id) async => JobInfo.fromJson(
|
||||||
|
await _send('POST', '/api/download/$id/retry') as Map<String, dynamic>);
|
||||||
|
|
||||||
|
Future<JobInfo> removeJob(String id) async => JobInfo.fromJson(
|
||||||
|
await _send('POST', '/api/download/$id/remove') as Map<String, dynamic>);
|
||||||
|
|
||||||
|
Future<ActionResult> clearFinished() async => ActionResult.fromJson(
|
||||||
|
await _send('POST', '/api/download/clear-finished') as Map<String, dynamic>);
|
||||||
|
|
||||||
|
Future<UpdateCheckInfo> checkUpdate({bool force = true}) async =>
|
||||||
|
UpdateCheckInfo.fromJson(
|
||||||
|
await _send('POST', '/api/update/check', body: {'force': force})
|
||||||
|
as Map<String, dynamic>);
|
||||||
|
|
||||||
|
Future<AboutInfo> about() async =>
|
||||||
|
AboutInfo.fromJson(await _send('GET', '/api/about') as Map<String, dynamic>);
|
||||||
|
|
||||||
|
Future<ActionResult> openFolder(String path) async => ActionResult.fromJson(
|
||||||
|
await _send('POST', '/api/shell/open-folder', body: {'path': path})
|
||||||
|
as Map<String, dynamic>);
|
||||||
|
|
||||||
|
Future<ActionResult> openUrl(String url) async => ActionResult.fromJson(
|
||||||
|
await _send('POST', '/api/shell/open-url', body: {'url': url})
|
||||||
|
as Map<String, dynamic>);
|
||||||
|
|
||||||
|
/// 模型封面图地址(直接给 Image.network 用)。
|
||||||
|
String previewUrl(ModelInfo model) => '$baseUrl${model.previewUrl}';
|
||||||
|
}
|
||||||
@@ -0,0 +1,187 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:flutter/foundation.dart';
|
||||||
|
|
||||||
|
import 'api_client.dart';
|
||||||
|
import 'i18n.dart';
|
||||||
|
import 'theme.dart';
|
||||||
|
|
||||||
|
/// 外壳状态:后端客户端 + 设置 + 健康状态 + 更新状态条。
|
||||||
|
///
|
||||||
|
/// 各页面只读这里的数据、通过这里的方法改后端,避免每页各持一份状态。
|
||||||
|
class ShellController extends ChangeNotifier {
|
||||||
|
ShellController({GcApi? api}) : api = api ?? GcApi();
|
||||||
|
|
||||||
|
final GcApi api;
|
||||||
|
|
||||||
|
int index = 0;
|
||||||
|
SettingsInfo? settings;
|
||||||
|
HealthInfo? health;
|
||||||
|
String? loadError;
|
||||||
|
|
||||||
|
bool updateBarVisible = false;
|
||||||
|
bool updateBusy = false;
|
||||||
|
double updateProgress = 0;
|
||||||
|
String updateStatus = '';
|
||||||
|
String updateDetail = '';
|
||||||
|
String launcherNotice = '';
|
||||||
|
|
||||||
|
/// 模型库版本号:安装 / 删除 / 下载完成后自增,首页据此重新拉列表。
|
||||||
|
///
|
||||||
|
/// 首页被 `Offstage` 保活,切走再切回不会重建;没有这个信号时,
|
||||||
|
/// 下载完模型回到首页仍然显示旧的空列表。
|
||||||
|
int modelsRevision = 0;
|
||||||
|
|
||||||
|
Timer? _retryTimer;
|
||||||
|
int _retryAttempt = 0;
|
||||||
|
|
||||||
|
bool get backendReady => settings != null;
|
||||||
|
|
||||||
|
Future<void> bootstrap() async {
|
||||||
|
_retryTimer?.cancel();
|
||||||
|
|
||||||
|
HealthInfo? healthResult;
|
||||||
|
SettingsInfo? settingsResult;
|
||||||
|
Object? firstError;
|
||||||
|
|
||||||
|
// 两个请求互不依赖,并行发;各自捕获异常,避免一方失败时
|
||||||
|
// 另一个的 Future 抛成未处理异常(Flutter 会在控制台打出恶性警告)。
|
||||||
|
await Future.wait<void>(<Future<void>>[
|
||||||
|
() async {
|
||||||
|
try {
|
||||||
|
healthResult = await api.health();
|
||||||
|
} catch (error) {
|
||||||
|
firstError ??= error;
|
||||||
|
}
|
||||||
|
}(),
|
||||||
|
() async {
|
||||||
|
try {
|
||||||
|
settingsResult = await api.settings();
|
||||||
|
} catch (error) {
|
||||||
|
firstError ??= error;
|
||||||
|
}
|
||||||
|
}(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
if (healthResult != null) health = healthResult;
|
||||||
|
if (settingsResult != null) {
|
||||||
|
settings = settingsResult;
|
||||||
|
_applySettings(settingsResult!);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (firstError != null && settingsResult == null) {
|
||||||
|
loadError = firstError.toString();
|
||||||
|
_scheduleRetry();
|
||||||
|
} else {
|
||||||
|
loadError = null;
|
||||||
|
_retryAttempt = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 后端没起来时自动重试(2s、4s、8s…最多 5 次),不必让用户手动点。
|
||||||
|
void _scheduleRetry() {
|
||||||
|
if (_retryAttempt >= 5) return;
|
||||||
|
final seconds = 1 << _retryAttempt; // 1,2,4,8,16
|
||||||
|
_retryAttempt++;
|
||||||
|
_retryTimer?.cancel();
|
||||||
|
_retryTimer = Timer(Duration(seconds: seconds), () {
|
||||||
|
if (settings == null) bootstrap();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
void _applySettings(SettingsInfo value) {
|
||||||
|
I18n.setLanguage(value.language);
|
||||||
|
GcPalette.apply(value.accentColor);
|
||||||
|
GcPalette.applyTheme(value.theme);
|
||||||
|
}
|
||||||
|
|
||||||
|
void goTo(int value) {
|
||||||
|
if (index == value) return;
|
||||||
|
index = value;
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 模型库有变化(安装 / 删除 / 下载完成):通知首页刷新。
|
||||||
|
void modelsChanged() {
|
||||||
|
modelsRevision++;
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> reloadSettings() async {
|
||||||
|
try {
|
||||||
|
settings = await api.settings();
|
||||||
|
loadError = null;
|
||||||
|
_applySettings(settings!);
|
||||||
|
} catch (error) {
|
||||||
|
loadError = error.toString();
|
||||||
|
}
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> saveSettings(SettingsPatch patch) async {
|
||||||
|
try {
|
||||||
|
settings = await api.saveSettings(patch);
|
||||||
|
loadError = null;
|
||||||
|
_applySettings(settings!);
|
||||||
|
} catch (error) {
|
||||||
|
loadError = error.toString();
|
||||||
|
}
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
|
||||||
|
void setUpdateStatus({
|
||||||
|
bool? visible,
|
||||||
|
bool? busy,
|
||||||
|
double? progress,
|
||||||
|
String? status,
|
||||||
|
String? detail,
|
||||||
|
String? notice,
|
||||||
|
}) {
|
||||||
|
if (visible != null) updateBarVisible = visible;
|
||||||
|
if (busy != null) updateBusy = busy;
|
||||||
|
if (progress != null) updateProgress = progress;
|
||||||
|
if (status != null) updateStatus = status;
|
||||||
|
if (detail != null) updateDetail = detail;
|
||||||
|
if (notice != null) launcherNotice = notice;
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 检查模型 / 启动器更新(设置页与状态条共用)。
|
||||||
|
Future<void> checkUpdate({bool force = true}) async {
|
||||||
|
if (updateBusy) return;
|
||||||
|
setUpdateStatus(
|
||||||
|
visible: true,
|
||||||
|
busy: true,
|
||||||
|
progress: 0,
|
||||||
|
status: T('update.checking'),
|
||||||
|
detail: '',
|
||||||
|
notice: '',
|
||||||
|
);
|
||||||
|
|
||||||
|
try {
|
||||||
|
final result = await api.checkUpdate(force: force);
|
||||||
|
setUpdateStatus(
|
||||||
|
busy: false,
|
||||||
|
progress: 1,
|
||||||
|
status: result.message.isEmpty ? T('update.done') : result.message,
|
||||||
|
detail: result.error ?? '',
|
||||||
|
notice: result.launcherMessage ?? '',
|
||||||
|
);
|
||||||
|
if (result.updatedModels > 0) modelsChanged();
|
||||||
|
} catch (error) {
|
||||||
|
setUpdateStatus(
|
||||||
|
busy: false,
|
||||||
|
status: T('update.offline'),
|
||||||
|
detail: error.toString(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
_retryTimer?.cancel();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,310 @@
|
|||||||
|
import 'package:flutter/widgets.dart';
|
||||||
|
|
||||||
|
/// 轻量 i18n:键值表 + 运行时切换,和后端 `GC/src/Assets/i18n/*.json` 的键保持一致。
|
||||||
|
class I18n {
|
||||||
|
I18n._();
|
||||||
|
|
||||||
|
static const List<String> supported = <String>['zh-CN', 'en'];
|
||||||
|
|
||||||
|
static final ValueNotifier<String> language = ValueNotifier<String>('zh-CN');
|
||||||
|
|
||||||
|
static const Map<String, Map<String, String>> _tables = <String, Map<String, String>>{
|
||||||
|
'zh-CN': <String, String>{
|
||||||
|
'app.name': 'Morris GC',
|
||||||
|
'app.tagline': '天文教学模型 · 可视化启动器',
|
||||||
|
'nav.home': '主页',
|
||||||
|
'nav.download': '下载',
|
||||||
|
'nav.settings': '设置',
|
||||||
|
'nav.about': '关于',
|
||||||
|
'home.title': '模型库',
|
||||||
|
'home.subtitle': '选择模型,用可交互的三维演示讲清自转、公转与四季成因。',
|
||||||
|
'home.launch': '启动模型',
|
||||||
|
'home.download': '下载模型',
|
||||||
|
'home.settings': '设置',
|
||||||
|
'home.installed': '已安装模型',
|
||||||
|
'home.count': '{0} 个模型',
|
||||||
|
'home.noDescription': '暂无简介',
|
||||||
|
'home.empty': '模型库还是空的',
|
||||||
|
'home.emptyHint': '启动时会自动检查并下载模型。若当前断网:可把模型文件夹放进 .GC/model/ 后重新打开,或联网后在「下载」页点重试。',
|
||||||
|
'home.emptyAction': '去下载模型',
|
||||||
|
'home.open': '打开目录',
|
||||||
|
'home.delete': '删除',
|
||||||
|
'home.deleteConfirm': '删除模型「{0}」?模型文件会从本地模型库移除。',
|
||||||
|
'home.stats.models': '已安装',
|
||||||
|
'home.stats.sources': '模型源',
|
||||||
|
'home.stats.memory': '内存预算',
|
||||||
|
'home.recent': '选择模型后点击「启动模型」',
|
||||||
|
'home.launchHint': '模型在自己的窗口里运行,可播放/暂停、切换视角并使用教学要点。',
|
||||||
|
'dl.title': '下载模型',
|
||||||
|
'dl.subtitle': '从内置模型源读取可下载模型;模型源在「设置」里查看。',
|
||||||
|
'dl.sources': '模型源',
|
||||||
|
'dl.refresh': '刷新',
|
||||||
|
'dl.available': '可用模型',
|
||||||
|
'dl.download': '下载',
|
||||||
|
'dl.installed': '已安装',
|
||||||
|
'dl.reinstall': '重新下载',
|
||||||
|
'dl.background': '后台任务',
|
||||||
|
'dl.bgEmpty': '暂无后台任务',
|
||||||
|
'dl.cancel': '取消',
|
||||||
|
'dl.retry': '重试',
|
||||||
|
'dl.clearDone': '清除已完成',
|
||||||
|
'dl.removeTask': '移除',
|
||||||
|
'dl.status.queued': '排队中',
|
||||||
|
'dl.status.downloading': '下载中',
|
||||||
|
'dl.status.done': '已完成',
|
||||||
|
'dl.status.failed': '失败',
|
||||||
|
'dl.status.canceled': '已取消',
|
||||||
|
'dl.empty': '这个源里没有模型',
|
||||||
|
'dl.emptyHint': '仓库需要包含 model/<模型ID>/<模型ID>.json 结构',
|
||||||
|
'dl.syncing': '正在读取模型源…',
|
||||||
|
'dl.ready': '共 {0} 个模型',
|
||||||
|
'dl.fromCache': '本地缓存',
|
||||||
|
'dl.pickSource': '选择一个模型源,查看可下载的模型',
|
||||||
|
'set.title': '设置',
|
||||||
|
'set.subtitle': '模型源、启动时内存分配与本地存储。',
|
||||||
|
'set.general': '通用',
|
||||||
|
'set.appearance': '外观',
|
||||||
|
'set.theme': '主题模式',
|
||||||
|
'set.theme.desc': '深色、浅色,或跟随系统设置。',
|
||||||
|
'set.theme.dark': '深色',
|
||||||
|
'set.theme.light': '浅色',
|
||||||
|
'set.theme.system': '跟随系统',
|
||||||
|
'set.accent': '主题颜色',
|
||||||
|
'set.accent.desc': '选择启动器的主色调,按钮、滑块与高亮会同步换色。',
|
||||||
|
'set.accent.custom': '自定义颜色',
|
||||||
|
'set.accent.hexHint': '格式 #RRGGBB,例如 #8FB6FF',
|
||||||
|
'set.accent.invalid': '颜色格式无效,请使用 #RRGGBB',
|
||||||
|
'set.language': '界面语言',
|
||||||
|
'set.language.auto': '跟随系统',
|
||||||
|
'set.fps': '渲染帧率',
|
||||||
|
'set.fps.desc': '越高越顺滑,CPU 占用也越高。',
|
||||||
|
'set.memory': '启动时运行内存分配',
|
||||||
|
'set.memory.desc': '启动器把这份预算交给模型:模型自己决定用它缓存多少数据(贴图分辨率、缓冲等)。',
|
||||||
|
'set.memory.current': '当前占用',
|
||||||
|
'set.memory.auto': '自动(根据设备内存分配)',
|
||||||
|
'set.memory.hint': '建议 2048 MB 以上,低配设备可选 1024 MB。',
|
||||||
|
'set.sources': '模型源',
|
||||||
|
'set.sources.desc': '停用的模型源不会出现在下载页。',
|
||||||
|
'set.sourceEnabled': '启用',
|
||||||
|
'set.storage': '存储',
|
||||||
|
'set.modelDir': '模型库目录',
|
||||||
|
'set.dataDir': '数据目录',
|
||||||
|
'set.openFolder': '打开文件夹',
|
||||||
|
'set.clearCache': '清理缓存',
|
||||||
|
'set.cacheCleared': '缓存已清理',
|
||||||
|
'set.about': '关于',
|
||||||
|
'set.version': '版本',
|
||||||
|
'set.platform': '平台',
|
||||||
|
'set.license': '许可',
|
||||||
|
'set.licenseValue': 'MIT',
|
||||||
|
'set.checkUpdate': '检查更新',
|
||||||
|
'set.checkUpdate.desc': '启动时自动检查模型与启动器是否为最新版。',
|
||||||
|
'set.backend': '后端服务',
|
||||||
|
'set.backend.desc': '界面(Flutter)与后端(.NET)分离,后端只监听本机回环地址。',
|
||||||
|
'set.backend.ui': '模型窗口宿主',
|
||||||
|
'set.backend.uiOk': '可用',
|
||||||
|
'set.backend.uiBad': '不可用',
|
||||||
|
'update.title': '自动更新',
|
||||||
|
'update.auto': '启动时自动检查更新',
|
||||||
|
'update.checkNow': '检查更新',
|
||||||
|
'update.source': '更新源',
|
||||||
|
'update.lastCheck': '上次检查',
|
||||||
|
'update.never': '尚未检查',
|
||||||
|
'update.none': '无',
|
||||||
|
'update.checking': '正在检查更新…',
|
||||||
|
'update.offline': '暂时无法连接更新服务器,继续使用本地模型',
|
||||||
|
'update.noChange': '模型与启动器均为最新版',
|
||||||
|
'update.applied': '已更新 {0} 个模型,立即生效',
|
||||||
|
'update.done': '更新检查完成',
|
||||||
|
'update.pendingReady': '启动器新版 {0} 已就绪,下次启动生效',
|
||||||
|
'common.cancel': '取消',
|
||||||
|
'common.confirm': '确定',
|
||||||
|
'common.delete': '删除',
|
||||||
|
'common.close': '关闭',
|
||||||
|
'common.open': '打开',
|
||||||
|
'common.applied': '已应用',
|
||||||
|
'common.confirmTitle': '请确认',
|
||||||
|
'common.retry': '重试',
|
||||||
|
'common.loading': '加载中…',
|
||||||
|
'common.error': '出错了',
|
||||||
|
'common.refresh': '刷新',
|
||||||
|
'about.developers': '开发者',
|
||||||
|
'about.contributorsHint': '来自仓库提交记录',
|
||||||
|
'about.repository': '仓库',
|
||||||
|
'about.openRepository': '打开仓库',
|
||||||
|
'about.contributions': '{0} 次提交',
|
||||||
|
'about.noContributors': '暂无贡献者信息',
|
||||||
|
'about.architecture': '架构',
|
||||||
|
'about.architectureValue': 'Flutter 前端 + .NET 后端(本地 HTTP)',
|
||||||
|
'about.sourceLanguage': '源码语言',
|
||||||
|
'about.frontend': '前端',
|
||||||
|
'about.gitService': 'Git 服务',
|
||||||
|
'about.thanks': '感谢',
|
||||||
|
'about.thanksHint': '特别感谢以下朋友的支持',
|
||||||
|
'about.thanksGit': 'Git 服务与部署支持',
|
||||||
|
'about.thanksGeo': '地理学科内容指导',
|
||||||
|
},
|
||||||
|
'en': <String, String>{
|
||||||
|
'app.name': 'Morris GC',
|
||||||
|
'app.tagline': 'Astronomy teaching models · visual launcher',
|
||||||
|
'nav.home': 'Home',
|
||||||
|
'nav.download': 'Download',
|
||||||
|
'nav.settings': 'Settings',
|
||||||
|
'nav.about': 'About',
|
||||||
|
'home.title': 'Model library',
|
||||||
|
'home.subtitle': 'Pick a model and explain rotation, revolution and the seasons with an interactive 3D scene.',
|
||||||
|
'home.launch': 'Launch model',
|
||||||
|
'home.download': 'Get models',
|
||||||
|
'home.settings': 'Settings',
|
||||||
|
'home.installed': 'Installed models',
|
||||||
|
'home.count': '{0} models',
|
||||||
|
'home.noDescription': 'No description',
|
||||||
|
'home.empty': 'No models yet',
|
||||||
|
'home.emptyHint': 'Models are checked and downloaded on startup. Offline: drop model folders into .GC/model/ and reopen, or retry from the Download page once online.',
|
||||||
|
'home.emptyAction': 'Get models',
|
||||||
|
'home.open': 'Open folder',
|
||||||
|
'home.delete': 'Delete',
|
||||||
|
'home.deleteConfirm': 'Delete the model "{0}"? Its files will be removed from the local library.',
|
||||||
|
'home.stats.models': 'Installed',
|
||||||
|
'home.stats.sources': 'Sources',
|
||||||
|
'home.stats.memory': 'Memory budget',
|
||||||
|
'home.recent': 'Select a model, then press Launch',
|
||||||
|
'home.launchHint': 'Models open in their own window with play/pause, view controls and teaching notes.',
|
||||||
|
'dl.title': 'Download',
|
||||||
|
'dl.subtitle': 'Read downloadable models from the built-in sources; manage sources in Settings.',
|
||||||
|
'dl.sources': 'Sources',
|
||||||
|
'dl.refresh': 'Refresh',
|
||||||
|
'dl.available': 'Available models',
|
||||||
|
'dl.download': 'Download',
|
||||||
|
'dl.installed': 'Installed',
|
||||||
|
'dl.reinstall': 'Re-download',
|
||||||
|
'dl.background': 'Background tasks',
|
||||||
|
'dl.bgEmpty': 'No background tasks',
|
||||||
|
'dl.cancel': 'Cancel',
|
||||||
|
'dl.retry': 'Retry',
|
||||||
|
'dl.clearDone': 'Clear finished',
|
||||||
|
'dl.removeTask': 'Remove',
|
||||||
|
'dl.status.queued': 'Queued',
|
||||||
|
'dl.status.downloading': 'Downloading',
|
||||||
|
'dl.status.done': 'Completed',
|
||||||
|
'dl.status.failed': 'Failed',
|
||||||
|
'dl.status.canceled': 'Canceled',
|
||||||
|
'dl.empty': 'No models in this source',
|
||||||
|
'dl.emptyHint': 'A source needs model/<model-id>/<model-id>.json layout',
|
||||||
|
'dl.syncing': 'Reading model source…',
|
||||||
|
'dl.ready': '{0} models',
|
||||||
|
'dl.fromCache': 'cached',
|
||||||
|
'dl.pickSource': 'Select a source to see available models',
|
||||||
|
'set.title': 'Settings',
|
||||||
|
'set.subtitle': 'Model sources, startup memory allocation and local storage.',
|
||||||
|
'set.general': 'General',
|
||||||
|
'set.appearance': 'Appearance',
|
||||||
|
'set.theme': 'Theme mode',
|
||||||
|
'set.theme.desc': 'Dark, light, or follow the system setting.',
|
||||||
|
'set.theme.dark': 'Dark',
|
||||||
|
'set.theme.light': 'Light',
|
||||||
|
'set.theme.system': 'System',
|
||||||
|
'set.accent': 'Theme color',
|
||||||
|
'set.accent.desc': 'Pick the launcher accent color; buttons, sliders and highlights follow it.',
|
||||||
|
'set.accent.custom': 'Custom color',
|
||||||
|
'set.accent.hexHint': 'Format #RRGGBB, e.g. #8FB6FF',
|
||||||
|
'set.accent.invalid': 'Invalid color, use #RRGGBB',
|
||||||
|
'set.language': 'Language',
|
||||||
|
'set.language.auto': 'System',
|
||||||
|
'set.fps': 'Render frame rate',
|
||||||
|
'set.fps.desc': 'Higher is smoother but uses more CPU.',
|
||||||
|
'set.memory': 'Startup memory allocation',
|
||||||
|
'set.memory.desc': 'The launcher hands this budget to each model; models decide how much data to cache with it.',
|
||||||
|
'set.memory.current': 'In use',
|
||||||
|
'set.memory.auto': 'Auto (allocate based on device memory)',
|
||||||
|
'set.memory.hint': '2048 MB or more is recommended; 1024 MB for low-end devices.',
|
||||||
|
'set.sources': 'Model sources',
|
||||||
|
'set.sources.desc': 'Disabled sources are hidden from the Download page.',
|
||||||
|
'set.sourceEnabled': 'Enabled',
|
||||||
|
'set.storage': 'Storage',
|
||||||
|
'set.modelDir': 'Model library',
|
||||||
|
'set.dataDir': 'Data folder',
|
||||||
|
'set.openFolder': 'Open folder',
|
||||||
|
'set.clearCache': 'Clear cache',
|
||||||
|
'set.cacheCleared': 'Cache cleared',
|
||||||
|
'set.about': 'About',
|
||||||
|
'set.version': 'Version',
|
||||||
|
'set.platform': 'Platform',
|
||||||
|
'set.license': 'License',
|
||||||
|
'set.licenseValue': 'MIT',
|
||||||
|
'set.checkUpdate': 'Check for updates',
|
||||||
|
'set.checkUpdate.desc': 'Check on startup whether models and the launcher are up to date.',
|
||||||
|
'set.backend': 'Backend service',
|
||||||
|
'set.backend.desc': 'The UI (Flutter) and the backend (.NET) are separate; the backend only listens on loopback.',
|
||||||
|
'set.backend.ui': 'Model window host',
|
||||||
|
'set.backend.uiOk': 'available',
|
||||||
|
'set.backend.uiBad': 'unavailable',
|
||||||
|
'update.title': 'Auto update',
|
||||||
|
'update.auto': 'Check for updates on startup',
|
||||||
|
'update.checkNow': 'Check now',
|
||||||
|
'update.source': 'Update source',
|
||||||
|
'update.lastCheck': 'Last check',
|
||||||
|
'update.never': 'Never',
|
||||||
|
'update.none': 'None',
|
||||||
|
'update.checking': 'Checking for updates…',
|
||||||
|
'update.offline': 'Update server unavailable — continuing with local models',
|
||||||
|
'update.noChange': 'Models and launcher are up to date',
|
||||||
|
'update.applied': 'Updated {0} models, applied now',
|
||||||
|
'update.done': 'Update check complete',
|
||||||
|
'update.pendingReady': 'Launcher {0} is ready, applies on next start',
|
||||||
|
'common.cancel': 'Cancel',
|
||||||
|
'common.confirm': 'Confirm',
|
||||||
|
'common.delete': 'Delete',
|
||||||
|
'common.close': 'Close',
|
||||||
|
'common.open': 'Open',
|
||||||
|
'common.applied': 'Applied',
|
||||||
|
'common.confirmTitle': 'Please confirm',
|
||||||
|
'common.retry': 'Retry',
|
||||||
|
'common.loading': 'Loading…',
|
||||||
|
'common.error': 'Something went wrong',
|
||||||
|
'common.refresh': 'Refresh',
|
||||||
|
'about.developers': 'Developers',
|
||||||
|
'about.contributorsHint': 'From repository commits',
|
||||||
|
'about.repository': 'Repository',
|
||||||
|
'about.openRepository': 'Open repository',
|
||||||
|
'about.contributions': '{0} commits',
|
||||||
|
'about.noContributors': 'No contributor information',
|
||||||
|
'about.architecture': 'Architecture',
|
||||||
|
'about.architectureValue': 'Flutter frontend + .NET backend (local HTTP)',
|
||||||
|
'about.sourceLanguage': 'Source language',
|
||||||
|
'about.frontend': 'Frontend',
|
||||||
|
'about.gitService': 'Git hosting',
|
||||||
|
'about.thanks': 'Thanks',
|
||||||
|
'about.thanksHint': 'Special thanks to',
|
||||||
|
'about.thanksGit': 'Git hosting and deployment',
|
||||||
|
'about.thanksGeo': 'Geography content guidance',
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
/// 取一条文案;`{0}` 这类占位符用 [args] 填充。
|
||||||
|
static String t(String key, [List<Object?> args = const <Object?>[]]) {
|
||||||
|
final table = _tables[language.value] ?? _tables['zh-CN']!;
|
||||||
|
var text = table[key] ?? _tables['zh-CN']![key] ?? key;
|
||||||
|
for (var i = 0; i < args.length; i++) {
|
||||||
|
text = text.replaceAll('{$i}', '${args[i]}');
|
||||||
|
}
|
||||||
|
return text;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 把后端语言设置(auto / zh-CN / en)解析成实际语言。
|
||||||
|
static String resolve(String? preference) {
|
||||||
|
if (preference != null && preference.isNotEmpty && preference != 'auto') {
|
||||||
|
return preference.startsWith('en') ? 'en' : 'zh-CN';
|
||||||
|
}
|
||||||
|
final locale = WidgetsBinding.instance.platformDispatcher.locale;
|
||||||
|
return locale.languageCode == 'zh' ? 'zh-CN' : 'en';
|
||||||
|
}
|
||||||
|
|
||||||
|
static void setLanguage(String code) {
|
||||||
|
final resolved = resolve(code);
|
||||||
|
if (language.value != resolved) language.value = resolved;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 便捷取词:`T('nav.home')`。
|
||||||
|
String T(String key, [List<Object?> args = const <Object?>[]]) => I18n.t(key, args);
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
import 'controller.dart';
|
||||||
|
import 'i18n.dart';
|
||||||
|
import 'shell.dart';
|
||||||
|
import 'theme.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
// 桌面端无需异步初始化外部插件:尽早绑定并直接渲染首帧,
|
||||||
|
// 让窗口在引擎就绪后立刻出现,后端探测在外壳里异步进行。
|
||||||
|
WidgetsFlutterBinding.ensureInitialized();
|
||||||
|
runApp(const GcUiApp());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// GC-UI 前端:Flutter 桌面应用(Windows / macOS / Linux)。
|
||||||
|
///
|
||||||
|
/// 界面全部在这里;模型扫描、下载、更新、设置、模型窗口宿主都在后端
|
||||||
|
/// (GC-UI/backend/GC.UI.Server,本地 HTTP 服务)。
|
||||||
|
class GcUiApp extends StatefulWidget {
|
||||||
|
const GcUiApp({super.key});
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<GcUiApp> createState() => _GcUiAppState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _GcUiAppState extends State<GcUiApp> {
|
||||||
|
final ShellController _controller = ShellController();
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
// 语言、强调色、主题模式都会触发重建:只重建 MaterialApp 的主题层,
|
||||||
|
// 不触碰页面状态(页面由 ShellPage 自己持有)。
|
||||||
|
return ValueListenableBuilder<String>(
|
||||||
|
valueListenable: I18n.language,
|
||||||
|
builder: (context, language, _) {
|
||||||
|
return ValueListenableBuilder<Color>(
|
||||||
|
valueListenable: GcPalette.accent,
|
||||||
|
builder: (context, accent, _) {
|
||||||
|
return ValueListenableBuilder<ThemeMode>(
|
||||||
|
valueListenable: GcPalette.mode,
|
||||||
|
builder: (context, mode, _) {
|
||||||
|
return MaterialApp(
|
||||||
|
title: 'Morris GC',
|
||||||
|
debugShowCheckedModeBanner: false,
|
||||||
|
// 桌面端不要移动端那套拉伸回弹和边缘光晕。
|
||||||
|
scrollBehavior: const GcScrollBehavior(),
|
||||||
|
theme: buildGcTheme(Brightness.light),
|
||||||
|
darkTheme: buildGcTheme(Brightness.dark),
|
||||||
|
themeMode: mode,
|
||||||
|
// GcColors 是静态取值,必须按当前实际亮度(含跟随系统)绑定,
|
||||||
|
// 再用 key 强制子树重建,否则切主题后颜色仍是上一套。
|
||||||
|
builder: (context, child) {
|
||||||
|
final brightness = Theme.of(context).brightness;
|
||||||
|
GcColors.bind(brightness);
|
||||||
|
return KeyedSubtree(
|
||||||
|
key: ValueKey<bool>(brightness == Brightness.dark),
|
||||||
|
child: child ?? const SizedBox.shrink(),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
home: ShellPage(controller: _controller),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
// 页面聚合导出:四个页面按职责拆到 pages/ 子目录。
|
||||||
|
// 保留这个文件是为了让 shell.dart 等调用方的 import 路径不变。
|
||||||
|
|
||||||
|
export 'pages/home.dart';
|
||||||
|
export 'pages/download.dart';
|
||||||
|
export 'pages/settings.dart';
|
||||||
|
export 'pages/about.dart';
|
||||||
@@ -0,0 +1,405 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
import '../api_client.dart';
|
||||||
|
import '../controller.dart';
|
||||||
|
import '../i18n.dart';
|
||||||
|
import '../theme.dart';
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// 关于页(从原 pages.dart 拆出,公开类名不变)
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// 关于页
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
class AboutPageView extends StatefulWidget {
|
||||||
|
const AboutPageView({super.key, required this.controller, this.initialAbout});
|
||||||
|
|
||||||
|
final ShellController controller;
|
||||||
|
|
||||||
|
/// 预置数据(仅用于测试 / 截图,正常运行时为 null,由后端提供)。
|
||||||
|
final AboutInfo? initialAbout;
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<AboutPageView> createState() => _AboutPageViewState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _AboutPageViewState extends State<AboutPageView> {
|
||||||
|
AboutInfo? _about;
|
||||||
|
bool _loading = true;
|
||||||
|
String? _error;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
final preset = widget.initialAbout;
|
||||||
|
if (preset != null) {
|
||||||
|
_about = preset;
|
||||||
|
_loading = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
_load();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _load() async {
|
||||||
|
setState(() {
|
||||||
|
_loading = true;
|
||||||
|
_error = null;
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
final about = await widget.controller.api.about();
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() {
|
||||||
|
_about = about;
|
||||||
|
_loading = false;
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() {
|
||||||
|
_error = error.toString();
|
||||||
|
_loading = false;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return ListView(
|
||||||
|
padding: const EdgeInsets.fromLTRB(
|
||||||
|
GcSpace.xxl,
|
||||||
|
GcSpace.xxl,
|
||||||
|
GcSpace.xxl,
|
||||||
|
GcSpace.xxxl,
|
||||||
|
),
|
||||||
|
children: <Widget>[
|
||||||
|
GcPageHeader(
|
||||||
|
title: T('nav.about'),
|
||||||
|
subtitle: T('app.tagline'),
|
||||||
|
),
|
||||||
|
const SizedBox(height: GcSpace.xxl),
|
||||||
|
if (_loading)
|
||||||
|
const Padding(
|
||||||
|
padding: EdgeInsets.symmetric(vertical: 48),
|
||||||
|
child: Center(
|
||||||
|
child: SizedBox(
|
||||||
|
width: 22,
|
||||||
|
height: 22,
|
||||||
|
child: CircularProgressIndicator(strokeWidth: 2),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
else if (_error != null)
|
||||||
|
GcMessage(
|
||||||
|
title: T('common.error'),
|
||||||
|
message: _error,
|
||||||
|
icon: Icons.error_outline_rounded,
|
||||||
|
color: GcColors.danger,
|
||||||
|
action: OutlinedButton(
|
||||||
|
onPressed: _load,
|
||||||
|
child: Text(T('common.retry')),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
else ...<Widget>[
|
||||||
|
_versionCard(),
|
||||||
|
const SizedBox(height: GcSpace.lg),
|
||||||
|
_contributorsCard(),
|
||||||
|
const SizedBox(height: GcSpace.lg),
|
||||||
|
_thanksCard(),
|
||||||
|
],
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _versionCard() {
|
||||||
|
final about = _about;
|
||||||
|
|
||||||
|
// 左边身份卡、右边信息表:宽屏两栏,窄屏自动堆叠。
|
||||||
|
final identity = Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: <Widget>[
|
||||||
|
Row(
|
||||||
|
children: <Widget>[
|
||||||
|
Container(
|
||||||
|
width: 44,
|
||||||
|
height: 44,
|
||||||
|
alignment: Alignment.center,
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: GcColors.accentSoft,
|
||||||
|
borderRadius: BorderRadius.circular(GcRadius.card),
|
||||||
|
),
|
||||||
|
child: Text(
|
||||||
|
'◎',
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 22, height: 1.1, color: GcColors.accent),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(width: GcSpace.lg),
|
||||||
|
Expanded(
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: <Widget>[
|
||||||
|
Text(
|
||||||
|
about?.appName ?? 'Morris GC',
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 20,
|
||||||
|
height: 1.3,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
color: GcColors.ink,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 2),
|
||||||
|
Text(
|
||||||
|
T('app.tagline'),
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 12.5,
|
||||||
|
height: 1.5,
|
||||||
|
color: GcColors.faint,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
const SizedBox(height: GcSpace.lg),
|
||||||
|
Wrap(
|
||||||
|
spacing: GcSpace.sm,
|
||||||
|
runSpacing: GcSpace.sm,
|
||||||
|
children: <Widget>[
|
||||||
|
GcPill('v${about?.version ?? '—'}', color: GcColors.accent),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
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')),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
|
final details = Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: <Widget>[
|
||||||
|
GcFieldRow(
|
||||||
|
label: T('set.platform'),
|
||||||
|
value: about?.platform ?? '—',
|
||||||
|
),
|
||||||
|
GcFieldRow(
|
||||||
|
label: T('about.architecture'),
|
||||||
|
value: T('about.architectureValue'),
|
||||||
|
),
|
||||||
|
GcFieldRow(
|
||||||
|
label: T('about.sourceLanguage'),
|
||||||
|
value: about?.sourceLanguage ?? 'C#',
|
||||||
|
),
|
||||||
|
GcFieldRow(
|
||||||
|
label: T('about.frontend'),
|
||||||
|
value: about?.frontend ?? 'Flutter',
|
||||||
|
),
|
||||||
|
GcFieldRow(
|
||||||
|
label: T('about.gitService'),
|
||||||
|
value: 'itxiaohui',
|
||||||
|
),
|
||||||
|
GcFieldRow(
|
||||||
|
label: T('set.license'),
|
||||||
|
value: T('set.licenseValue'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
|
return GcCard(
|
||||||
|
padding: const EdgeInsets.all(GcSpace.xxl),
|
||||||
|
child: LayoutBuilder(
|
||||||
|
builder: (context, constraints) {
|
||||||
|
if (constraints.maxWidth < 720) {
|
||||||
|
return Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: <Widget>[
|
||||||
|
identity,
|
||||||
|
const GcDivider(verticalPadding: GcSpace.lg),
|
||||||
|
details,
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return Row(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: <Widget>[
|
||||||
|
Expanded(flex: 4, child: identity),
|
||||||
|
const SizedBox(width: GcSpace.xxxl),
|
||||||
|
Expanded(flex: 5, child: details),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _contributorsCard() {
|
||||||
|
final contributors = _about?.contributors ?? const <ContributorInfo>[];
|
||||||
|
return GcCard(
|
||||||
|
padding: const EdgeInsets.all(GcSpace.xxl),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: <Widget>[
|
||||||
|
GcSectionTitle(
|
||||||
|
T('about.developers'),
|
||||||
|
subtitle: T('about.contributorsHint'),
|
||||||
|
),
|
||||||
|
const SizedBox(height: GcSpace.lg),
|
||||||
|
if (contributors.isEmpty)
|
||||||
|
GcHint(T('about.noContributors'))
|
||||||
|
else
|
||||||
|
Wrap(
|
||||||
|
spacing: GcSpace.xl,
|
||||||
|
runSpacing: GcSpace.md,
|
||||||
|
children: <Widget>[
|
||||||
|
for (final contributor in contributors)
|
||||||
|
SizedBox(
|
||||||
|
width: 220,
|
||||||
|
child: Row(
|
||||||
|
children: <Widget>[
|
||||||
|
CircleAvatar(
|
||||||
|
radius: 18,
|
||||||
|
backgroundColor: GcColors.surfaceAlt,
|
||||||
|
backgroundImage: contributor.avatarUrl == null
|
||||||
|
? null
|
||||||
|
: NetworkImage(contributor.avatarUrl!),
|
||||||
|
child: contributor.avatarUrl == null
|
||||||
|
? Text(
|
||||||
|
'◎',
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 14,
|
||||||
|
color: GcColors.accent,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
: null,
|
||||||
|
),
|
||||||
|
const SizedBox(width: GcSpace.md),
|
||||||
|
Expanded(
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: <Widget>[
|
||||||
|
Text(
|
||||||
|
contributor.name,
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 13,
|
||||||
|
height: 1.4,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
color: GcColors.ink,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Text(
|
||||||
|
T(
|
||||||
|
'about.contributions',
|
||||||
|
<Object?>[contributor.contributions],
|
||||||
|
),
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 11.5,
|
||||||
|
height: 1.4,
|
||||||
|
color: GcColors.faint,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 特别感谢:与「开发者」分开列 —— 提供 Git 服务不等于往仓库提交代码,
|
||||||
|
/// 混进贡献者列表会让提交数失去意义。
|
||||||
|
Widget _thanksCard() {
|
||||||
|
return GcCard(
|
||||||
|
padding: const EdgeInsets.all(GcSpace.xxl),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: <Widget>[
|
||||||
|
GcSectionTitle(
|
||||||
|
T('about.thanks'),
|
||||||
|
subtitle: T('about.thanksHint'),
|
||||||
|
),
|
||||||
|
const SizedBox(height: GcSpace.lg),
|
||||||
|
Wrap(
|
||||||
|
spacing: GcSpace.xl,
|
||||||
|
runSpacing: GcSpace.md,
|
||||||
|
children: <Widget>[
|
||||||
|
_creditTile('地理洪老师', 'about.thanksGeo'),
|
||||||
|
_creditTile('itxiaohui', 'about.thanksGit'),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _creditTile(String name, String roleKey) {
|
||||||
|
return SizedBox(
|
||||||
|
width: 220,
|
||||||
|
child: Row(
|
||||||
|
children: <Widget>[
|
||||||
|
CircleAvatar(
|
||||||
|
radius: 18,
|
||||||
|
backgroundColor: GcColors.surfaceAlt,
|
||||||
|
child: Text(
|
||||||
|
'◎',
|
||||||
|
style: TextStyle(fontSize: 14, color: GcColors.accent),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(width: GcSpace.md),
|
||||||
|
Expanded(
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: <Widget>[
|
||||||
|
Text(
|
||||||
|
name,
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 13,
|
||||||
|
height: 1.4,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
color: GcColors.ink,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Text(
|
||||||
|
T(roleKey),
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 11.5,
|
||||||
|
height: 1.4,
|
||||||
|
color: GcColors.faint,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,579 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
import '../api_client.dart';
|
||||||
|
import '../controller.dart';
|
||||||
|
import '../i18n.dart';
|
||||||
|
import '../theme.dart';
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// 下载页(从原 pages.dart 拆出,公开类名不变)
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// 下载页
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
class DownloadPageView extends StatefulWidget {
|
||||||
|
const DownloadPageView({
|
||||||
|
super.key,
|
||||||
|
required this.controller,
|
||||||
|
this.initialSources,
|
||||||
|
this.initialIndex,
|
||||||
|
this.initialJobs,
|
||||||
|
});
|
||||||
|
|
||||||
|
final ShellController controller;
|
||||||
|
|
||||||
|
/// 预置数据(仅用于测试 / 截图,正常运行时为 null,由后端提供)。
|
||||||
|
final List<SourceInfo>? initialSources;
|
||||||
|
final SourceIndexInfo? initialIndex;
|
||||||
|
final List<JobInfo>? initialJobs;
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<DownloadPageView> createState() => _DownloadPageViewState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _DownloadPageViewState extends State<DownloadPageView> {
|
||||||
|
List<SourceInfo> _sources = const <SourceInfo>[];
|
||||||
|
SourceIndexInfo? _index;
|
||||||
|
List<JobInfo> _jobs = const <JobInfo>[];
|
||||||
|
String? _selectedSourceId;
|
||||||
|
bool _loading = true;
|
||||||
|
String? _error;
|
||||||
|
Timer? _poll;
|
||||||
|
|
||||||
|
/// 页面是否可见(被切走后仍保活,但没必要继续请求后端)。
|
||||||
|
bool _visible = true;
|
||||||
|
|
||||||
|
/// 上一次轮询时是否有活跃任务,用来判断「刚刚全部结束」。
|
||||||
|
bool _hadActive = false;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
final presetSources = widget.initialSources;
|
||||||
|
if (presetSources != null) {
|
||||||
|
_sources = presetSources;
|
||||||
|
_index = widget.initialIndex;
|
||||||
|
_jobs = widget.initialJobs ?? const <JobInfo>[];
|
||||||
|
_selectedSourceId = presetSources.isEmpty ? null : presetSources.first.id;
|
||||||
|
_loading = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
_load();
|
||||||
|
_schedulePoll(const Duration(seconds: 2));
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void didChangeDependencies() {
|
||||||
|
super.didChangeDependencies();
|
||||||
|
// TickerMode 由外壳的 Offstage 控制:切到别的页时变 false。
|
||||||
|
_visible = TickerMode.of(context);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
_poll?.cancel();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 单次 Timer 链:有活跃任务时 1 秒一次,空闲时降到 5 秒,不可见时 10 秒。
|
||||||
|
///
|
||||||
|
/// 以前是 `Timer.periodic(1s)` 且永不停止 —— 只要进过下载页,之后每秒都
|
||||||
|
/// 在请求 `/api/download/jobs`,哪怕没有任何任务、页面也早就切走了。
|
||||||
|
void _schedulePoll(Duration delay) {
|
||||||
|
_poll?.cancel();
|
||||||
|
_poll = Timer(delay, _pollOnce);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _pollOnce() async {
|
||||||
|
if (!mounted) return;
|
||||||
|
|
||||||
|
if (!_visible) {
|
||||||
|
_schedulePoll(const Duration(seconds: 10));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_hadActive = _jobs.any((job) => job.isActive);
|
||||||
|
await _refreshJobs();
|
||||||
|
if (!mounted) return;
|
||||||
|
|
||||||
|
final active = _jobs.any((job) => job.isActive);
|
||||||
|
// 活跃 → 空闲:这一轮里下载结束了,首页的模型列表已经过期。
|
||||||
|
if (_hadActive && !active) widget.controller.modelsChanged();
|
||||||
|
_hadActive = active;
|
||||||
|
|
||||||
|
_schedulePoll(Duration(seconds: active ? 1 : 5));
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _load() async {
|
||||||
|
setState(() {
|
||||||
|
_loading = true;
|
||||||
|
_error = null;
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
final sources = await widget.controller.api.sources();
|
||||||
|
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) return;
|
||||||
|
setState(() {
|
||||||
|
_sources = sources;
|
||||||
|
_selectedSourceId = selected;
|
||||||
|
_index = index;
|
||||||
|
_loading = false;
|
||||||
|
});
|
||||||
|
await _refreshJobs();
|
||||||
|
} catch (error) {
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() {
|
||||||
|
_error = error.toString();
|
||||||
|
_loading = false;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _refreshJobs() async {
|
||||||
|
try {
|
||||||
|
final jobs = await widget.controller.api.jobs();
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() => _jobs = jobs);
|
||||||
|
} catch (_) {
|
||||||
|
// 轮询失败不打扰用户,下一次再试
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _selectSource(String id) async {
|
||||||
|
setState(() {
|
||||||
|
_selectedSourceId = id;
|
||||||
|
_loading = true;
|
||||||
|
_error = null;
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
final index = await widget.controller.api.remoteModels(sourceId: id);
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() {
|
||||||
|
_index = index;
|
||||||
|
_loading = false;
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() {
|
||||||
|
_error = error.toString();
|
||||||
|
_loading = false;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _download(RemoteModelInfo model) async {
|
||||||
|
final sourceId = _selectedSourceId;
|
||||||
|
if (sourceId == null) return;
|
||||||
|
try {
|
||||||
|
await widget.controller.api.startDownload(sourceId, model.id);
|
||||||
|
await _refreshJobs();
|
||||||
|
} catch (error) {
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() => _error = error.toString());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _jobAction(
|
||||||
|
Future<JobInfo> Function(String id) action, String id) async {
|
||||||
|
try {
|
||||||
|
await action(id);
|
||||||
|
await _refreshJobs();
|
||||||
|
} catch (error) {
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() => _error = error.toString());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return Padding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(
|
||||||
|
GcSpace.xxl, GcSpace.xxl, GcSpace.xxl, GcSpace.xl),
|
||||||
|
child: Row(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: <Widget>[
|
||||||
|
SizedBox(width: 268, child: _sourcePanel()),
|
||||||
|
const SizedBox(width: GcSpace.xl),
|
||||||
|
Expanded(child: _modelPanel()),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _sourcePanel() {
|
||||||
|
return GcCard(
|
||||||
|
padding: const EdgeInsets.all(GcSpace.lg),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: <Widget>[
|
||||||
|
GcSectionTitle(T('dl.sources')),
|
||||||
|
const SizedBox(height: GcSpace.xs + 2),
|
||||||
|
GcHint(T('dl.subtitle')),
|
||||||
|
const SizedBox(height: GcSpace.md),
|
||||||
|
for (final source in _sources)
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.only(bottom: GcSpace.xs + 2),
|
||||||
|
child: _sourceTile(source),
|
||||||
|
),
|
||||||
|
const SizedBox(height: GcSpace.sm),
|
||||||
|
SizedBox(
|
||||||
|
width: double.infinity,
|
||||||
|
child: OutlinedButton.icon(
|
||||||
|
onPressed: _load,
|
||||||
|
icon: const Icon(Icons.refresh_rounded, size: 18),
|
||||||
|
label: Text(T('dl.refresh')),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _sourceTile(SourceInfo source) {
|
||||||
|
final selected = source.id == _selectedSourceId;
|
||||||
|
return Material(
|
||||||
|
color: selected ? GcColors.accentSoft : Colors.transparent,
|
||||||
|
borderRadius: BorderRadius.circular(GcRadius.control),
|
||||||
|
child: InkWell(
|
||||||
|
borderRadius: BorderRadius.circular(GcRadius.control),
|
||||||
|
hoverColor: GcColors.surfaceAlt,
|
||||||
|
onTap: () => _selectSource(source.id),
|
||||||
|
child: Container(
|
||||||
|
padding: const EdgeInsets.symmetric(
|
||||||
|
horizontal: GcSpace.md,
|
||||||
|
vertical: GcSpace.md - 2,
|
||||||
|
),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
borderRadius: BorderRadius.circular(GcRadius.control),
|
||||||
|
border: Border.all(
|
||||||
|
color: selected
|
||||||
|
? GcColors.accent.withOpacity(0.45)
|
||||||
|
: Colors.transparent,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: Row(
|
||||||
|
children: <Widget>[
|
||||||
|
Icon(
|
||||||
|
selected
|
||||||
|
? Icons.radio_button_checked_rounded
|
||||||
|
: Icons.radio_button_unchecked_rounded,
|
||||||
|
size: 16,
|
||||||
|
color: selected ? GcColors.accent : GcColors.ghost,
|
||||||
|
),
|
||||||
|
const SizedBox(width: GcSpace.sm + 2),
|
||||||
|
Expanded(
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: <Widget>[
|
||||||
|
Text(
|
||||||
|
source.name,
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 13,
|
||||||
|
height: 1.35,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
color: selected ? GcColors.accent : GcColors.ink,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 1),
|
||||||
|
Text(
|
||||||
|
source.host,
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 11.5,
|
||||||
|
height: 1.35,
|
||||||
|
color: GcColors.faint,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
if (!source.enabled) const GcPill('off', subtle: true),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _modelPanel() {
|
||||||
|
final models = _index?.models ?? const <RemoteModelInfo>[];
|
||||||
|
return Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: <Widget>[
|
||||||
|
GcPageHeader(
|
||||||
|
title: T('dl.available'),
|
||||||
|
subtitle: _index == null
|
||||||
|
? null
|
||||||
|
: (_index!.fromCache
|
||||||
|
? '${T('dl.ready', <Object?>[
|
||||||
|
models.length
|
||||||
|
])} · ${T('dl.fromCache')}'
|
||||||
|
: T('dl.ready', <Object?>[models.length])),
|
||||||
|
trailing: IconButton(
|
||||||
|
tooltip: T('common.refresh'),
|
||||||
|
onPressed: _load,
|
||||||
|
icon: const Icon(Icons.refresh_rounded, size: 18),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: GcSpace.lg),
|
||||||
|
Expanded(
|
||||||
|
child: ListView(
|
||||||
|
padding: const EdgeInsets.only(bottom: GcSpace.sm),
|
||||||
|
children: <Widget>[
|
||||||
|
if (_loading)
|
||||||
|
const Padding(
|
||||||
|
padding: EdgeInsets.symmetric(vertical: 48),
|
||||||
|
child: Center(
|
||||||
|
child: SizedBox(
|
||||||
|
width: 22,
|
||||||
|
height: 22,
|
||||||
|
child: CircularProgressIndicator(strokeWidth: 2),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
else if (_error != null)
|
||||||
|
GcMessage(
|
||||||
|
title: T('common.error'),
|
||||||
|
message: _error,
|
||||||
|
icon: Icons.cloud_off_rounded,
|
||||||
|
color: GcColors.danger,
|
||||||
|
action: OutlinedButton(
|
||||||
|
onPressed: _load,
|
||||||
|
child: Text(T('common.retry')),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
else if (models.isEmpty)
|
||||||
|
GcMessage(
|
||||||
|
title: T('dl.empty'),
|
||||||
|
message: T('dl.emptyHint'),
|
||||||
|
icon: Icons.inbox_rounded,
|
||||||
|
)
|
||||||
|
else
|
||||||
|
for (final model in models)
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.only(bottom: GcSpace.md),
|
||||||
|
child: _remoteRow(model),
|
||||||
|
),
|
||||||
|
const SizedBox(height: GcSpace.sm),
|
||||||
|
_jobsPanel(),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _remoteRow(RemoteModelInfo model) {
|
||||||
|
return GcCard(
|
||||||
|
padding: const EdgeInsets.fromLTRB(
|
||||||
|
GcSpace.lg,
|
||||||
|
GcSpace.md + 2,
|
||||||
|
GcSpace.lg,
|
||||||
|
GcSpace.md + 2,
|
||||||
|
),
|
||||||
|
child: Row(
|
||||||
|
children: <Widget>[
|
||||||
|
Expanded(
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: <Widget>[
|
||||||
|
Row(
|
||||||
|
children: <Widget>[
|
||||||
|
Flexible(
|
||||||
|
child: Text(
|
||||||
|
model.name,
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 14,
|
||||||
|
height: 1.35,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
color: GcColors.ink,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(width: GcSpace.sm),
|
||||||
|
Text(
|
||||||
|
'v${model.version} · ${model.sizeText}',
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 12,
|
||||||
|
height: 1.35,
|
||||||
|
color: GcColors.faint,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
if (model.installed) ...<Widget>[
|
||||||
|
const SizedBox(width: GcSpace.sm),
|
||||||
|
GcPill(T('dl.installed'), color: GcColors.ok),
|
||||||
|
],
|
||||||
|
],
|
||||||
|
),
|
||||||
|
const SizedBox(height: GcSpace.xs + 1),
|
||||||
|
Text(
|
||||||
|
model.description,
|
||||||
|
maxLines: 2,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 12.5,
|
||||||
|
height: 1.5,
|
||||||
|
color: GcColors.muted,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
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')),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _jobsPanel() {
|
||||||
|
return GcCard(
|
||||||
|
padding: const EdgeInsets.all(GcSpace.lg),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: <Widget>[
|
||||||
|
GcSectionTitle(
|
||||||
|
T('dl.background'),
|
||||||
|
trailing: TextButton(
|
||||||
|
onPressed: () async {
|
||||||
|
try {
|
||||||
|
await widget.controller.api.clearFinished();
|
||||||
|
await _refreshJobs();
|
||||||
|
} catch (_) {
|
||||||
|
// 忽略
|
||||||
|
}
|
||||||
|
},
|
||||||
|
child: Text(T('dl.clearDone')),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: GcSpace.md),
|
||||||
|
if (_jobs.isEmpty)
|
||||||
|
GcHint(T('dl.bgEmpty'))
|
||||||
|
else
|
||||||
|
for (final job in _jobs)
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.only(bottom: GcSpace.md),
|
||||||
|
child: _jobRow(job),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _jobRow(JobInfo job) {
|
||||||
|
return Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: <Widget>[
|
||||||
|
Row(
|
||||||
|
children: <Widget>[
|
||||||
|
Expanded(
|
||||||
|
child: Text(
|
||||||
|
'${job.name} v${job.version}',
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 13,
|
||||||
|
height: 1.35,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
color: GcColors.ink,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
GcPill(
|
||||||
|
_stateLabel(job.state),
|
||||||
|
color: job.state == 'Failed'
|
||||||
|
? GcColors.danger
|
||||||
|
: job.state == 'Completed'
|
||||||
|
? GcColors.ok
|
||||||
|
: GcColors.accent,
|
||||||
|
),
|
||||||
|
const SizedBox(width: GcSpace.sm),
|
||||||
|
if (job.isActive)
|
||||||
|
TextButton(
|
||||||
|
onPressed: () =>
|
||||||
|
_jobAction(widget.controller.api.cancelJob, job.id),
|
||||||
|
child: Text(T('dl.cancel')),
|
||||||
|
)
|
||||||
|
else if (job.canRetry)
|
||||||
|
TextButton(
|
||||||
|
onPressed: () =>
|
||||||
|
_jobAction(widget.controller.api.retryJob, job.id),
|
||||||
|
child: Text(T('dl.retry')),
|
||||||
|
)
|
||||||
|
else
|
||||||
|
TextButton(
|
||||||
|
onPressed: () =>
|
||||||
|
_jobAction(widget.controller.api.removeJob, job.id),
|
||||||
|
child: Text(T('dl.removeTask')),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
const SizedBox(height: GcSpace.sm - 2),
|
||||||
|
ClipRRect(
|
||||||
|
borderRadius: BorderRadius.circular(2),
|
||||||
|
child: LinearProgressIndicator(
|
||||||
|
value: job.progress.clamp(0, 1).toDouble(),
|
||||||
|
minHeight: 4,
|
||||||
|
backgroundColor: GcColors.surfaceAlt,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: GcSpace.xs + 1),
|
||||||
|
Text(
|
||||||
|
job.error ?? job.detailText,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 11.5,
|
||||||
|
height: 1.4,
|
||||||
|
color: GcColors.faint,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
String _stateLabel(String state) {
|
||||||
|
switch (state) {
|
||||||
|
case 'Queued':
|
||||||
|
return T('dl.status.queued');
|
||||||
|
case 'Running':
|
||||||
|
case 'Downloading':
|
||||||
|
return T('dl.status.downloading');
|
||||||
|
case 'Completed':
|
||||||
|
return T('dl.status.done');
|
||||||
|
case 'Failed':
|
||||||
|
return T('dl.status.failed');
|
||||||
|
case 'Canceled':
|
||||||
|
return T('dl.status.canceled');
|
||||||
|
default:
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,690 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
import '../api_client.dart';
|
||||||
|
import '../controller.dart';
|
||||||
|
import '../i18n.dart';
|
||||||
|
import '../theme.dart';
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// 首页:模型库(从原 pages.dart 拆出,公开类名不变)
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// 首页:模型库
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
class HomePageView extends StatefulWidget {
|
||||||
|
const HomePageView({super.key, required this.controller, this.initialModels});
|
||||||
|
|
||||||
|
final ShellController controller;
|
||||||
|
|
||||||
|
/// 预置模型列表(仅用于测试 / 截图,正常运行时为 null,由后端提供)。
|
||||||
|
final List<ModelInfo>? initialModels;
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<HomePageView> createState() => _HomePageViewState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _HomePageViewState extends State<HomePageView> {
|
||||||
|
List<ModelInfo> _models = const <ModelInfo>[];
|
||||||
|
bool _loading = true;
|
||||||
|
String? _error;
|
||||||
|
String? _notice;
|
||||||
|
int _lastRevision = 0;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
widget.controller.addListener(_onControllerChanged);
|
||||||
|
_lastRevision = widget.controller.modelsRevision;
|
||||||
|
|
||||||
|
final preset = widget.initialModels;
|
||||||
|
if (preset != null) {
|
||||||
|
_models = preset;
|
||||||
|
_loading = false;
|
||||||
|
} else {
|
||||||
|
_load();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
widget.controller.removeListener(_onControllerChanged);
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 下载完成 / 删除模型后重新拉列表:页面被 Offstage 保活,不会自己重建。
|
||||||
|
void _onControllerChanged() {
|
||||||
|
if (!mounted) return;
|
||||||
|
final revision = widget.controller.modelsRevision;
|
||||||
|
if (revision == _lastRevision) return;
|
||||||
|
_lastRevision = revision;
|
||||||
|
if (widget.initialModels != null) return; // 截图 / 测试用的预置数据
|
||||||
|
_load();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _load() async {
|
||||||
|
setState(() {
|
||||||
|
_loading = true;
|
||||||
|
_error = null;
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
final models = await widget.controller.api.models();
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() {
|
||||||
|
_models = models;
|
||||||
|
_loading = false;
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() {
|
||||||
|
_error = error.toString();
|
||||||
|
_loading = false;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _launch(ModelInfo model) async {
|
||||||
|
setState(() => _notice = null);
|
||||||
|
try {
|
||||||
|
final result = await widget.controller.api.launchModel(model.id);
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() => _notice = result.message);
|
||||||
|
} catch (error) {
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() => _notice = error.toString());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _delete(ModelInfo model) async {
|
||||||
|
final confirmed = await showDialog<bool>(
|
||||||
|
context: context,
|
||||||
|
builder: (context) => AlertDialog(
|
||||||
|
backgroundColor: GcColors.surface,
|
||||||
|
title: Text(T('common.confirmTitle')),
|
||||||
|
content: Text(T('home.deleteConfirm', <Object?>[model.name])),
|
||||||
|
actions: <Widget>[
|
||||||
|
TextButton(
|
||||||
|
onPressed: () => Navigator.of(context).pop(false),
|
||||||
|
child: Text(T('common.cancel')),
|
||||||
|
),
|
||||||
|
FilledButton(
|
||||||
|
onPressed: () => Navigator.of(context).pop(true),
|
||||||
|
child: Text(T('common.delete')),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
if (confirmed != true) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
await widget.controller.api.deleteModel(model.id);
|
||||||
|
await _load();
|
||||||
|
} catch (error) {
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() => _notice = error.toString());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _openFolder(String path) async {
|
||||||
|
try {
|
||||||
|
await widget.controller.api.openFolder(path);
|
||||||
|
} catch (error) {
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() => _notice = error.toString());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final settings = widget.controller.settings;
|
||||||
|
return RefreshIndicator(
|
||||||
|
onRefresh: _load,
|
||||||
|
color: GcColors.accent,
|
||||||
|
backgroundColor: GcColors.surface,
|
||||||
|
child: ListView(
|
||||||
|
physics: const AlwaysScrollableScrollPhysics(),
|
||||||
|
padding: const EdgeInsets.fromLTRB(
|
||||||
|
GcSpace.xxl, GcSpace.xxl, GcSpace.xxl, GcSpace.xxxl),
|
||||||
|
children: <Widget>[
|
||||||
|
_hero(settings),
|
||||||
|
const SizedBox(height: GcSpace.xxl),
|
||||||
|
_sectionHeader(),
|
||||||
|
if (_notice != null) ...<Widget>[
|
||||||
|
const SizedBox(height: GcSpace.md),
|
||||||
|
GcMessage(
|
||||||
|
title: _notice!,
|
||||||
|
icon: Icons.info_outline_rounded,
|
||||||
|
color: GcColors.warn,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
const SizedBox(height: GcSpace.lg),
|
||||||
|
if (_loading)
|
||||||
|
const Padding(
|
||||||
|
padding: EdgeInsets.symmetric(vertical: 48),
|
||||||
|
child: Center(
|
||||||
|
child: SizedBox(
|
||||||
|
width: 22,
|
||||||
|
height: 22,
|
||||||
|
child: CircularProgressIndicator(strokeWidth: 2),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
else if (_error != null)
|
||||||
|
GcMessage(
|
||||||
|
title: T('common.error'),
|
||||||
|
message: _error,
|
||||||
|
icon: Icons.cloud_off_rounded,
|
||||||
|
color: GcColors.danger,
|
||||||
|
action: OutlinedButton(
|
||||||
|
onPressed: _load,
|
||||||
|
child: Text(T('common.retry')),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
else if (_models.isEmpty)
|
||||||
|
_emptyState()
|
||||||
|
else
|
||||||
|
LayoutBuilder(
|
||||||
|
builder: (context, constraints) {
|
||||||
|
const spacing = GcSpace.lg;
|
||||||
|
final columns =
|
||||||
|
(constraints.maxWidth / 320).floor().clamp(1, 4);
|
||||||
|
final cardWidth =
|
||||||
|
(constraints.maxWidth - spacing * (columns - 1)) / columns;
|
||||||
|
return Wrap(
|
||||||
|
spacing: spacing,
|
||||||
|
runSpacing: spacing,
|
||||||
|
children: <Widget>[
|
||||||
|
for (final model in _models)
|
||||||
|
SizedBox(
|
||||||
|
width: cardWidth,
|
||||||
|
child: _ModelCard(
|
||||||
|
model: model,
|
||||||
|
previewUrl: widget.controller.api.previewUrl(model),
|
||||||
|
onLaunch: () => _launch(model),
|
||||||
|
onOpenFolder: () => _openFolder(model.directory),
|
||||||
|
onDelete: () => _delete(model),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 顶部横幅:产品定位 + 主操作 + 关键指标。
|
||||||
|
///
|
||||||
|
/// 不用渐变:深色主题下的低对比渐变会让整块区域发灰,看起来就是「糊」。
|
||||||
|
Widget _hero(SettingsInfo? settings) {
|
||||||
|
final enabledSources =
|
||||||
|
settings?.sources.where((s) => s.enabled).length ?? 0;
|
||||||
|
return GcCard(
|
||||||
|
padding: const EdgeInsets.all(GcSpace.xxl + 2),
|
||||||
|
child: Row(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: <Widget>[
|
||||||
|
Expanded(
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: <Widget>[
|
||||||
|
Text(
|
||||||
|
'MODEL LIBRARY',
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 11,
|
||||||
|
height: 1.2,
|
||||||
|
letterSpacing: 1.4,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
color: GcColors.accent,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: GcSpace.md),
|
||||||
|
Text(
|
||||||
|
T('home.title'),
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 26,
|
||||||
|
height: 1.25,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
letterSpacing: -0.2,
|
||||||
|
color: GcColors.ink,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: GcSpace.sm),
|
||||||
|
ConstrainedBox(
|
||||||
|
constraints: const BoxConstraints(maxWidth: 460),
|
||||||
|
child: Text(
|
||||||
|
T('home.subtitle'),
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 13,
|
||||||
|
height: 1.65,
|
||||||
|
color: GcColors.muted,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: GcSpace.xl),
|
||||||
|
Row(
|
||||||
|
children: <Widget>[
|
||||||
|
FilledButton.icon(
|
||||||
|
onPressed:
|
||||||
|
_models.isEmpty ? null : () => _launch(_models.first),
|
||||||
|
icon: const Icon(Icons.play_arrow_rounded, size: 18),
|
||||||
|
label: Text(T('home.launch')),
|
||||||
|
),
|
||||||
|
const SizedBox(width: GcSpace.md),
|
||||||
|
OutlinedButton(
|
||||||
|
onPressed: () => widget.controller.goTo(1),
|
||||||
|
child: Text(T('home.download')),
|
||||||
|
),
|
||||||
|
const SizedBox(width: GcSpace.xs),
|
||||||
|
TextButton(
|
||||||
|
onPressed: () => widget.controller.goTo(2),
|
||||||
|
child: Text(T('home.settings')),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
const SizedBox(height: GcSpace.md),
|
||||||
|
Text(
|
||||||
|
T('home.launchHint'),
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 12,
|
||||||
|
height: 1.55,
|
||||||
|
color: GcColors.faint,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(width: GcSpace.xxl),
|
||||||
|
Container(
|
||||||
|
padding: const EdgeInsets.symmetric(
|
||||||
|
horizontal: GcSpace.xl,
|
||||||
|
vertical: GcSpace.lg,
|
||||||
|
),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: GcColors.surfaceAlt,
|
||||||
|
borderRadius: BorderRadius.circular(GcRadius.control),
|
||||||
|
border: Border.all(color: GcColors.line),
|
||||||
|
),
|
||||||
|
child: Row(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: <Widget>[
|
||||||
|
GcMetric(
|
||||||
|
value: '${_models.length}',
|
||||||
|
label: T('home.stats.models'),
|
||||||
|
),
|
||||||
|
_metricDivider(),
|
||||||
|
GcMetric(
|
||||||
|
value: '$enabledSources',
|
||||||
|
label: T('home.stats.sources'),
|
||||||
|
),
|
||||||
|
_metricDivider(),
|
||||||
|
GcMetric(
|
||||||
|
value: '${settings?.memoryBudgetMb ?? 0}',
|
||||||
|
label: T('home.stats.memory'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _metricDivider() {
|
||||||
|
return Container(
|
||||||
|
width: 1,
|
||||||
|
height: 34,
|
||||||
|
margin: const EdgeInsets.symmetric(horizontal: GcSpace.xl),
|
||||||
|
color: GcColors.line,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _sectionHeader() {
|
||||||
|
return Row(
|
||||||
|
children: <Widget>[
|
||||||
|
Text(
|
||||||
|
T('home.installed'),
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 16,
|
||||||
|
height: 1.4,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
color: GcColors.ink,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(width: GcSpace.sm),
|
||||||
|
GcPill(T('home.count', <Object?>[_models.length]), subtle: true),
|
||||||
|
const Spacer(),
|
||||||
|
IconButton(
|
||||||
|
tooltip: T('common.refresh'),
|
||||||
|
onPressed: _load,
|
||||||
|
icon: const Icon(Icons.refresh_rounded, size: 18),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _emptyState() {
|
||||||
|
return GcCard(
|
||||||
|
padding: const EdgeInsets.symmetric(
|
||||||
|
horizontal: GcSpace.xxxl,
|
||||||
|
vertical: 40,
|
||||||
|
),
|
||||||
|
child: Column(
|
||||||
|
children: <Widget>[
|
||||||
|
Container(
|
||||||
|
width: 52,
|
||||||
|
height: 52,
|
||||||
|
alignment: Alignment.center,
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: GcColors.accentSoft,
|
||||||
|
borderRadius: BorderRadius.circular(GcRadius.panel),
|
||||||
|
),
|
||||||
|
child: Icon(
|
||||||
|
Icons.travel_explore_rounded,
|
||||||
|
size: 26,
|
||||||
|
color: GcColors.accent,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: GcSpace.lg),
|
||||||
|
Text(
|
||||||
|
T('home.empty'),
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 16,
|
||||||
|
height: 1.4,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
color: GcColors.ink,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: GcSpace.sm),
|
||||||
|
ConstrainedBox(
|
||||||
|
constraints: const BoxConstraints(maxWidth: 420),
|
||||||
|
child: Text(
|
||||||
|
T('home.emptyHint'),
|
||||||
|
textAlign: TextAlign.center,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 12.5,
|
||||||
|
height: 1.7,
|
||||||
|
color: GcColors.muted,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: GcSpace.xl),
|
||||||
|
FilledButton(
|
||||||
|
onPressed: () => widget.controller.goTo(1),
|
||||||
|
child: Text(T('home.emptyAction')),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _ModelCard extends StatefulWidget {
|
||||||
|
const _ModelCard({
|
||||||
|
required this.model,
|
||||||
|
required this.previewUrl,
|
||||||
|
required this.onLaunch,
|
||||||
|
required this.onOpenFolder,
|
||||||
|
required this.onDelete,
|
||||||
|
});
|
||||||
|
|
||||||
|
final ModelInfo model;
|
||||||
|
final String previewUrl;
|
||||||
|
final VoidCallback onLaunch;
|
||||||
|
final VoidCallback onOpenFolder;
|
||||||
|
final VoidCallback onDelete;
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<_ModelCard> createState() => _ModelCardState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _ModelCardState extends State<_ModelCard> {
|
||||||
|
bool _hover = false;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final model = widget.model;
|
||||||
|
return MouseRegion(
|
||||||
|
onEnter: (_) => setState(() => _hover = true),
|
||||||
|
onExit: (_) => setState(() => _hover = false),
|
||||||
|
cursor: SystemMouseCursors.click,
|
||||||
|
child: GcCard(
|
||||||
|
padding: EdgeInsets.zero,
|
||||||
|
clip: true,
|
||||||
|
borderColor: _hover ? GcColors.lineStrong : GcColors.line,
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: <Widget>[
|
||||||
|
_cover(model),
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(
|
||||||
|
GcSpace.lg,
|
||||||
|
GcSpace.md + 2,
|
||||||
|
GcSpace.lg,
|
||||||
|
GcSpace.md,
|
||||||
|
),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: <Widget>[
|
||||||
|
Row(
|
||||||
|
children: <Widget>[
|
||||||
|
Expanded(
|
||||||
|
child: Text(
|
||||||
|
model.name,
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 14.5,
|
||||||
|
height: 1.35,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
color: GcColors.ink,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(width: GcSpace.sm),
|
||||||
|
Text(
|
||||||
|
model.sizeText,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 12,
|
||||||
|
height: 1.35,
|
||||||
|
color: GcColors.faint,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
const SizedBox(height: GcSpace.sm - 2),
|
||||||
|
SizedBox(
|
||||||
|
height: 36,
|
||||||
|
child: Text(
|
||||||
|
model.description.isEmpty
|
||||||
|
? T('home.noDescription')
|
||||||
|
: model.description,
|
||||||
|
maxLines: 2,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 12.5,
|
||||||
|
height: 1.45,
|
||||||
|
color: model.description.isEmpty
|
||||||
|
? GcColors.faint
|
||||||
|
: GcColors.muted,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
if (model.tags.isNotEmpty) ...<Widget>[
|
||||||
|
const SizedBox(height: GcSpace.sm + 2),
|
||||||
|
SizedBox(
|
||||||
|
height: 20,
|
||||||
|
child: Wrap(
|
||||||
|
spacing: 6,
|
||||||
|
runSpacing: 6,
|
||||||
|
children: <Widget>[
|
||||||
|
for (final tag in model.tags.take(3))
|
||||||
|
GcPill(tag, subtle: true),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
const SizedBox(height: GcSpace.md + 2),
|
||||||
|
Row(
|
||||||
|
children: <Widget>[
|
||||||
|
FilledButton.icon(
|
||||||
|
onPressed: widget.onLaunch,
|
||||||
|
icon: const Icon(Icons.play_arrow_rounded, size: 18),
|
||||||
|
label: Text(T('home.launch')),
|
||||||
|
),
|
||||||
|
const Spacer(),
|
||||||
|
IconButton(
|
||||||
|
tooltip: T('home.open'),
|
||||||
|
onPressed: widget.onOpenFolder,
|
||||||
|
icon: const Icon(Icons.folder_open_rounded, size: 18),
|
||||||
|
),
|
||||||
|
IconButton(
|
||||||
|
tooltip: T('home.delete'),
|
||||||
|
onPressed: widget.onDelete,
|
||||||
|
icon:
|
||||||
|
const Icon(Icons.delete_outline_rounded, size: 18),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 封面:按卡片宽度和屏幕像素比解码,避免被放大后发虚。
|
||||||
|
Widget _cover(ModelInfo model) {
|
||||||
|
final dpr = MediaQuery.devicePixelRatioOf(context);
|
||||||
|
final decodeWidth =
|
||||||
|
(MediaQuery.sizeOf(context).width * dpr).clamp(320, 900).round();
|
||||||
|
return SizedBox(
|
||||||
|
height: 156,
|
||||||
|
width: double.infinity,
|
||||||
|
child: Stack(
|
||||||
|
fit: StackFit.expand,
|
||||||
|
children: <Widget>[
|
||||||
|
_PreviewFallback(model: model),
|
||||||
|
if (model.hasPreview)
|
||||||
|
Image.network(
|
||||||
|
widget.previewUrl,
|
||||||
|
fit: BoxFit.cover,
|
||||||
|
cacheWidth: decodeWidth,
|
||||||
|
filterQuality: FilterQuality.medium,
|
||||||
|
gaplessPlayback: true,
|
||||||
|
errorBuilder: (context, error, stack) => const SizedBox.shrink(),
|
||||||
|
),
|
||||||
|
DecoratedBox(
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
// 只用「透明 → 深色」的遮罩,别用 alphaBlend:叠加不透明底色
|
||||||
|
// 会把整张封面盖平,占位字母也跟着消失。
|
||||||
|
gradient: LinearGradient(
|
||||||
|
begin: Alignment.topCenter,
|
||||||
|
end: Alignment.bottomCenter,
|
||||||
|
colors: <Color>[
|
||||||
|
GcColors.appBg.withOpacity(0.0),
|
||||||
|
GcColors.appBg.withOpacity(0.32),
|
||||||
|
GcColors.appBg.withOpacity(0.88),
|
||||||
|
],
|
||||||
|
stops: const <double>[0.42, 0.72, 1.0],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Positioned(
|
||||||
|
left: GcSpace.md,
|
||||||
|
right: GcSpace.sm,
|
||||||
|
bottom: GcSpace.sm,
|
||||||
|
child: Row(
|
||||||
|
children: <Widget>[
|
||||||
|
if (model.version.isNotEmpty)
|
||||||
|
GcPill('v${model.version}', color: GcColors.accent),
|
||||||
|
if (model.author.isNotEmpty) ...<Widget>[
|
||||||
|
const SizedBox(width: GcSpace.sm),
|
||||||
|
Flexible(
|
||||||
|
child: Text(
|
||||||
|
model.author,
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 11.5,
|
||||||
|
height: 1.3,
|
||||||
|
color: GcColors.muted,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
const Spacer(),
|
||||||
|
AnimatedOpacity(
|
||||||
|
opacity: _hover ? 1 : 0,
|
||||||
|
duration: const Duration(milliseconds: 140),
|
||||||
|
child: Container(
|
||||||
|
width: 26,
|
||||||
|
height: 26,
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: GcColors.accentFill,
|
||||||
|
shape: BoxShape.circle,
|
||||||
|
),
|
||||||
|
child: Icon(
|
||||||
|
Icons.play_arrow_rounded,
|
||||||
|
size: 18,
|
||||||
|
color: GcColors.onAccent,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 没有封面时的占位:型号首字 + 淡淡的网格感,比一个大「◎」更像封面。
|
||||||
|
class _PreviewFallback extends StatelessWidget {
|
||||||
|
const _PreviewFallback({this.model});
|
||||||
|
|
||||||
|
final ModelInfo? model;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final label = (model?.name ?? '').characters.isEmpty
|
||||||
|
? '◎'
|
||||||
|
: model!.name.characters.first;
|
||||||
|
return DecoratedBox(
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
gradient: LinearGradient(
|
||||||
|
begin: Alignment.topLeft,
|
||||||
|
end: Alignment.bottomRight,
|
||||||
|
colors: <Color>[
|
||||||
|
Color.alphaBlend(
|
||||||
|
GcColors.accent.withOpacity(0.22),
|
||||||
|
GcColors.surfaceAlt,
|
||||||
|
),
|
||||||
|
GcColors.surfaceAlt,
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: Center(
|
||||||
|
child: Text(
|
||||||
|
label,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 46,
|
||||||
|
height: 1.0,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
color: Color.alphaBlend(
|
||||||
|
GcColors.accent.withOpacity(0.55),
|
||||||
|
GcColors.surfaceAlt,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,699 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
import '../api_client.dart';
|
||||||
|
import '../controller.dart';
|
||||||
|
import '../i18n.dart';
|
||||||
|
import '../theme.dart';
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// 设置页(从原 pages.dart 拆出,公开类名不变)
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// 设置页
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
class SettingsPageView extends StatefulWidget {
|
||||||
|
const SettingsPageView({super.key, required this.controller});
|
||||||
|
|
||||||
|
final ShellController controller;
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<SettingsPageView> createState() => _SettingsPageViewState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _SettingsPageViewState extends State<SettingsPageView> {
|
||||||
|
double _memory = 2048;
|
||||||
|
bool _memoryAuto = true;
|
||||||
|
int _fps = 120;
|
||||||
|
bool _autoUpdate = true;
|
||||||
|
String _language = 'auto';
|
||||||
|
ThemeMode _themeMode = ThemeMode.dark;
|
||||||
|
|
||||||
|
/// 上一次同步所用的设置对象。以前用的是 `bool _synced` —— 只同步一次,
|
||||||
|
/// 之后外部(更新状态条、其它页面)改了设置,本页仍显示旧值。
|
||||||
|
SettingsInfo? _syncedFrom;
|
||||||
|
String? _status;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
widget.controller.reloadSettings();
|
||||||
|
}
|
||||||
|
|
||||||
|
void _syncFrom(SettingsInfo settings) {
|
||||||
|
if (identical(_syncedFrom, settings)) return;
|
||||||
|
_syncedFrom = settings;
|
||||||
|
_memory = settings.memoryMb.toDouble();
|
||||||
|
_memoryAuto = settings.memoryAuto;
|
||||||
|
_fps = settings.renderFps;
|
||||||
|
_autoUpdate = settings.autoUpdateOnStartup;
|
||||||
|
_language = settings.language;
|
||||||
|
_themeMode = GcPalette.parseMode(settings.theme);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final settings = widget.controller.settings;
|
||||||
|
if (settings == null) {
|
||||||
|
return const Center(
|
||||||
|
child: SizedBox(
|
||||||
|
width: 22,
|
||||||
|
height: 22,
|
||||||
|
child: CircularProgressIndicator(strokeWidth: 2),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
_syncFrom(settings);
|
||||||
|
|
||||||
|
return LayoutBuilder(
|
||||||
|
builder: (context, constraints) {
|
||||||
|
final twoColumns = constraints.maxWidth >= 960;
|
||||||
|
final cards = <Widget>[
|
||||||
|
_generalCard(settings),
|
||||||
|
_appearanceCard(settings),
|
||||||
|
_memoryCard(settings),
|
||||||
|
_sourcesCard(settings),
|
||||||
|
_storageCard(settings),
|
||||||
|
_updateCard(settings),
|
||||||
|
_backendCard(settings),
|
||||||
|
];
|
||||||
|
|
||||||
|
Widget column(List<Widget> items) => Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
|
children: <Widget>[
|
||||||
|
for (var i = 0; i < items.length; i++) ...<Widget>[
|
||||||
|
if (i > 0) const SizedBox(height: GcSpace.lg),
|
||||||
|
items[i],
|
||||||
|
],
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
|
final left = <Widget>[];
|
||||||
|
final right = <Widget>[];
|
||||||
|
for (var i = 0; i < cards.length; i++) {
|
||||||
|
if (twoColumns && i.isOdd) {
|
||||||
|
right.add(cards[i]);
|
||||||
|
} else {
|
||||||
|
left.add(cards[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return SingleChildScrollView(
|
||||||
|
padding: const EdgeInsets.fromLTRB(
|
||||||
|
GcSpace.xxl,
|
||||||
|
GcSpace.xxl,
|
||||||
|
GcSpace.xxl,
|
||||||
|
GcSpace.xxxl,
|
||||||
|
),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
|
children: <Widget>[
|
||||||
|
GcPageHeader(
|
||||||
|
title: T('set.title'),
|
||||||
|
subtitle: T('set.subtitle'),
|
||||||
|
trailing: _status == null
|
||||||
|
? null
|
||||||
|
: GcPill(
|
||||||
|
_status!,
|
||||||
|
color: GcColors.ok,
|
||||||
|
icon: Icons.check_rounded,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: GcSpace.xxl),
|
||||||
|
if (twoColumns)
|
||||||
|
Row(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: <Widget>[
|
||||||
|
Expanded(child: column(left)),
|
||||||
|
const SizedBox(width: GcSpace.lg),
|
||||||
|
Expanded(child: column(right)),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
else
|
||||||
|
column(cards),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _label(String text) {
|
||||||
|
return Text(
|
||||||
|
text,
|
||||||
|
style: TextStyle(fontSize: 13, height: 1.5, color: GcColors.muted),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _cardRow(String label, Widget control) {
|
||||||
|
return Padding(
|
||||||
|
padding: const EdgeInsets.symmetric(vertical: GcSpace.sm),
|
||||||
|
child: Row(
|
||||||
|
children: <Widget>[
|
||||||
|
SizedBox(width: 124, child: _label(label)),
|
||||||
|
Expanded(child: control),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _generalCard(SettingsInfo settings) {
|
||||||
|
return GcCard(
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: <Widget>[
|
||||||
|
GcSectionTitle(T('set.general')),
|
||||||
|
const SizedBox(height: GcSpace.lg),
|
||||||
|
_cardRow(
|
||||||
|
T('set.language'),
|
||||||
|
Align(
|
||||||
|
alignment: Alignment.centerLeft,
|
||||||
|
child: DropdownButton<String>(
|
||||||
|
value: _language,
|
||||||
|
dropdownColor: GcColors.surfaceAlt,
|
||||||
|
underline: const SizedBox.shrink(),
|
||||||
|
borderRadius: BorderRadius.circular(GcRadius.control),
|
||||||
|
// 从主题样式派生,才能继承字体族(自建 TextStyle 会丢掉
|
||||||
|
// fontFamily,中文就回退成系统兜底字体)。
|
||||||
|
style: Theme.of(context).textTheme.bodyLarge!.copyWith(
|
||||||
|
fontSize: 13,
|
||||||
|
height: 1.4,
|
||||||
|
fontWeight: FontWeight.w400,
|
||||||
|
color: GcColors.ink,
|
||||||
|
),
|
||||||
|
items: <DropdownMenuItem<String>>[
|
||||||
|
DropdownMenuItem<String>(
|
||||||
|
value: 'auto',
|
||||||
|
child: Text(T('set.language.auto')),
|
||||||
|
),
|
||||||
|
for (final language in settings.languages)
|
||||||
|
DropdownMenuItem<String>(
|
||||||
|
value: language.code,
|
||||||
|
child: Text(language.label),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
onChanged: (value) async {
|
||||||
|
if (value == null) return;
|
||||||
|
setState(() => _language = value);
|
||||||
|
await widget.controller
|
||||||
|
.saveSettings(SettingsPatch(language: value));
|
||||||
|
},
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
_cardRow(
|
||||||
|
T('set.fps'),
|
||||||
|
Row(
|
||||||
|
children: <Widget>[
|
||||||
|
Expanded(
|
||||||
|
child: Slider(
|
||||||
|
value: _fps.toDouble(),
|
||||||
|
min: 24,
|
||||||
|
max: 120,
|
||||||
|
divisions: 4,
|
||||||
|
label: '$_fps',
|
||||||
|
onChanged: (value) => setState(() => _fps = value.round()),
|
||||||
|
onChangeEnd: (value) async {
|
||||||
|
await widget.controller.saveSettings(
|
||||||
|
SettingsPatch(renderFps: value.round()));
|
||||||
|
if (mounted) {
|
||||||
|
setState(() => _status = T('common.applied'));
|
||||||
|
}
|
||||||
|
},
|
||||||
|
),
|
||||||
|
),
|
||||||
|
SizedBox(
|
||||||
|
width: 48,
|
||||||
|
child: Text(
|
||||||
|
'$_fps',
|
||||||
|
textAlign: TextAlign.end,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 13,
|
||||||
|
height: 1.4,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
color: GcColors.ink,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
GcHint(T('set.fps.desc')),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _appearanceCard(SettingsInfo settings) {
|
||||||
|
final current =
|
||||||
|
GcPalette.parseHex(settings.accentColor) ?? GcPalette.defaultAccent;
|
||||||
|
return GcCard(
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: <Widget>[
|
||||||
|
GcSectionTitle(T('set.appearance')),
|
||||||
|
const SizedBox(height: GcSpace.md),
|
||||||
|
GcHint(T('set.theme.desc')),
|
||||||
|
const SizedBox(height: GcSpace.md),
|
||||||
|
SegmentedButton<ThemeMode>(
|
||||||
|
segments: <ButtonSegment<ThemeMode>>[
|
||||||
|
ButtonSegment<ThemeMode>(
|
||||||
|
value: ThemeMode.dark,
|
||||||
|
label: Text(T('set.theme.dark')),
|
||||||
|
icon: const Icon(Icons.dark_mode_outlined, size: 16),
|
||||||
|
),
|
||||||
|
ButtonSegment<ThemeMode>(
|
||||||
|
value: ThemeMode.light,
|
||||||
|
label: Text(T('set.theme.light')),
|
||||||
|
icon: const Icon(Icons.light_mode_outlined, size: 16),
|
||||||
|
),
|
||||||
|
ButtonSegment<ThemeMode>(
|
||||||
|
value: ThemeMode.system,
|
||||||
|
label: Text(T('set.theme.system')),
|
||||||
|
icon: const Icon(Icons.brightness_auto_outlined, size: 16),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
selected: <ThemeMode>{_themeMode},
|
||||||
|
showSelectedIcon: false,
|
||||||
|
onSelectionChanged: (selection) async {
|
||||||
|
final mode = selection.first;
|
||||||
|
setState(() => _themeMode = mode);
|
||||||
|
GcPalette.mode.value = mode; // 立即预览
|
||||||
|
await widget.controller.saveSettings(
|
||||||
|
SettingsPatch(theme: GcPalette.modeToName(mode)));
|
||||||
|
if (mounted) setState(() => _status = T('common.applied'));
|
||||||
|
},
|
||||||
|
),
|
||||||
|
const SizedBox(height: GcSpace.xl),
|
||||||
|
GcHint(T('set.accent.desc')),
|
||||||
|
const SizedBox(height: GcSpace.md + 2),
|
||||||
|
Wrap(
|
||||||
|
spacing: GcSpace.sm + 2,
|
||||||
|
runSpacing: GcSpace.sm + 2,
|
||||||
|
children: <Widget>[
|
||||||
|
for (final color in GcPalette.presets)
|
||||||
|
_accentSwatch(color, current),
|
||||||
|
_customAccentChip(),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
const SizedBox(height: GcSpace.md),
|
||||||
|
Text(
|
||||||
|
'${T('set.accent')}: ${GcPalette.toHex(current)}',
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 11.5,
|
||||||
|
height: 1.4,
|
||||||
|
color: GcColors.faint,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _accentSwatch(Color color, Color current) {
|
||||||
|
final selected = color.value == current.value;
|
||||||
|
return Tooltip(
|
||||||
|
message: GcPalette.toHex(color),
|
||||||
|
child: GestureDetector(
|
||||||
|
onTap: () => _applyAccent(GcPalette.toHex(color)),
|
||||||
|
child: Container(
|
||||||
|
width: 34,
|
||||||
|
height: 34,
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: color,
|
||||||
|
borderRadius: BorderRadius.circular(GcRadius.control),
|
||||||
|
border: Border.all(
|
||||||
|
color: selected ? GcColors.ink : Colors.transparent,
|
||||||
|
width: 2,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: selected
|
||||||
|
? Icon(
|
||||||
|
Icons.check_rounded,
|
||||||
|
size: 18,
|
||||||
|
color: color.computeLuminance() > 0.42
|
||||||
|
? const Color(0xFF0A1226)
|
||||||
|
: Colors.white,
|
||||||
|
)
|
||||||
|
: null,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _customAccentChip() {
|
||||||
|
return MouseRegion(
|
||||||
|
cursor: SystemMouseCursors.click,
|
||||||
|
child: GestureDetector(
|
||||||
|
onTap: _pickCustomAccent,
|
||||||
|
child: Container(
|
||||||
|
height: 34,
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: GcSpace.md),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: GcColors.surfaceAlt,
|
||||||
|
borderRadius: BorderRadius.circular(GcRadius.control),
|
||||||
|
border: Border.all(color: GcColors.line),
|
||||||
|
),
|
||||||
|
child: Row(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: <Widget>[
|
||||||
|
Icon(Icons.colorize_rounded, size: 16, color: GcColors.faint),
|
||||||
|
const SizedBox(width: GcSpace.xs + 2),
|
||||||
|
Text(
|
||||||
|
T('set.accent.custom'),
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 12,
|
||||||
|
height: 1.3,
|
||||||
|
color: GcColors.muted,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _pickCustomAccent() async {
|
||||||
|
final controller = TextEditingController(
|
||||||
|
text: GcPalette.toHex(GcPalette.accent.value),
|
||||||
|
);
|
||||||
|
final hex = await showDialog<String>(
|
||||||
|
context: context,
|
||||||
|
builder: (context) => AlertDialog(
|
||||||
|
backgroundColor: GcColors.surface,
|
||||||
|
title: Text(T('set.accent.custom')),
|
||||||
|
content: TextField(
|
||||||
|
controller: controller,
|
||||||
|
autofocus: true,
|
||||||
|
style: Theme.of(context).textTheme.bodyLarge!.copyWith(fontSize: 13),
|
||||||
|
decoration: InputDecoration(
|
||||||
|
hintText: '#8FB6FF',
|
||||||
|
helperText: T('set.accent.hexHint'),
|
||||||
|
),
|
||||||
|
onSubmitted: (value) => Navigator.of(context).pop(value),
|
||||||
|
),
|
||||||
|
actions: <Widget>[
|
||||||
|
TextButton(
|
||||||
|
onPressed: () => Navigator.of(context).pop(),
|
||||||
|
child: Text(T('common.cancel')),
|
||||||
|
),
|
||||||
|
FilledButton(
|
||||||
|
onPressed: () => Navigator.of(context).pop(controller.text),
|
||||||
|
child: Text(T('common.confirm')),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
controller.dispose();
|
||||||
|
if (hex != null) await _applyAccent(hex);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _applyAccent(String hex) async {
|
||||||
|
final parsed = GcPalette.parseHex(hex);
|
||||||
|
if (parsed == null) {
|
||||||
|
if (mounted) setState(() => _status = T('set.accent.invalid'));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
final normalized = GcPalette.toHex(parsed);
|
||||||
|
GcPalette.apply(normalized); // 立即预览
|
||||||
|
await widget.controller
|
||||||
|
.saveSettings(SettingsPatch(accentColor: normalized));
|
||||||
|
if (mounted) setState(() => _status = T('common.applied'));
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _memoryCard(SettingsInfo settings) {
|
||||||
|
return GcCard(
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: <Widget>[
|
||||||
|
GcSectionTitle(T('set.memory')),
|
||||||
|
const SizedBox(height: GcSpace.md),
|
||||||
|
GcHint(T('set.memory.desc')),
|
||||||
|
const SizedBox(height: GcSpace.lg),
|
||||||
|
Row(
|
||||||
|
children: <Widget>[
|
||||||
|
Switch(
|
||||||
|
value: _memoryAuto,
|
||||||
|
onChanged: (value) async {
|
||||||
|
setState(() => _memoryAuto = value);
|
||||||
|
await widget.controller
|
||||||
|
.saveSettings(SettingsPatch(memoryAuto: value));
|
||||||
|
},
|
||||||
|
),
|
||||||
|
const SizedBox(width: GcSpace.md),
|
||||||
|
Expanded(
|
||||||
|
child: Text(
|
||||||
|
T('set.memory.auto'),
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 13,
|
||||||
|
height: 1.5,
|
||||||
|
color: GcColors.muted,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
const SizedBox(height: GcSpace.xs),
|
||||||
|
Row(
|
||||||
|
children: <Widget>[
|
||||||
|
Expanded(
|
||||||
|
child: Slider(
|
||||||
|
value: _memory,
|
||||||
|
min: 512,
|
||||||
|
max: 16384,
|
||||||
|
divisions: 62,
|
||||||
|
label: '${_memory.round()} MB',
|
||||||
|
onChanged: _memoryAuto
|
||||||
|
? null
|
||||||
|
: (value) => setState(() => _memory = value),
|
||||||
|
onChangeEnd: (value) async {
|
||||||
|
await widget.controller
|
||||||
|
.saveSettings(SettingsPatch(memoryMb: value.round()));
|
||||||
|
if (mounted) setState(() => _status = T('common.applied'));
|
||||||
|
},
|
||||||
|
),
|
||||||
|
),
|
||||||
|
SizedBox(
|
||||||
|
width: 104,
|
||||||
|
child: Text(
|
||||||
|
'${_memory.round()} MB',
|
||||||
|
textAlign: TextAlign.end,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 13,
|
||||||
|
height: 1.4,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
color: GcColors.ink,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
const SizedBox(height: GcSpace.xs),
|
||||||
|
GcHint('${T('set.memory.current')}: ${settings.memoryUsageText}'),
|
||||||
|
const SizedBox(height: GcSpace.xs),
|
||||||
|
GcHint(T('set.memory.hint')),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _sourcesCard(SettingsInfo settings) {
|
||||||
|
return GcCard(
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: <Widget>[
|
||||||
|
GcSectionTitle(T('set.sources')),
|
||||||
|
const SizedBox(height: GcSpace.md),
|
||||||
|
GcHint(T('set.sources.desc')),
|
||||||
|
const SizedBox(height: GcSpace.md),
|
||||||
|
for (final source in settings.sources)
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.only(bottom: GcSpace.md),
|
||||||
|
child: Row(
|
||||||
|
children: <Widget>[
|
||||||
|
Expanded(
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: <Widget>[
|
||||||
|
Text(
|
||||||
|
source.name,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 13,
|
||||||
|
height: 1.4,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
color: GcColors.ink,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 1),
|
||||||
|
Text(
|
||||||
|
source.url,
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 11.5,
|
||||||
|
height: 1.4,
|
||||||
|
color: GcColors.faint,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(width: GcSpace.sm),
|
||||||
|
if (source.enabled)
|
||||||
|
GcPill(T('set.sourceEnabled'), color: GcColors.ok)
|
||||||
|
else
|
||||||
|
const GcPill('—', subtle: true),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _storageCard(SettingsInfo settings) {
|
||||||
|
return GcCard(
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: <Widget>[
|
||||||
|
GcSectionTitle(T('set.storage')),
|
||||||
|
const SizedBox(height: GcSpace.md),
|
||||||
|
GcFieldRow(
|
||||||
|
label: T('set.modelDir'),
|
||||||
|
value: settings.modelRoot,
|
||||||
|
selectable: true,
|
||||||
|
valueColor: GcColors.muted,
|
||||||
|
),
|
||||||
|
GcFieldRow(
|
||||||
|
label: T('set.dataDir'),
|
||||||
|
value: settings.dataRoot,
|
||||||
|
selectable: true,
|
||||||
|
valueColor: GcColors.muted,
|
||||||
|
),
|
||||||
|
const SizedBox(height: GcSpace.md),
|
||||||
|
Wrap(
|
||||||
|
spacing: GcSpace.sm + 2,
|
||||||
|
runSpacing: GcSpace.sm + 2,
|
||||||
|
children: <Widget>[
|
||||||
|
OutlinedButton(
|
||||||
|
onPressed: () async {
|
||||||
|
try {
|
||||||
|
await widget.controller.api.openFolder(settings.modelRoot);
|
||||||
|
} catch (error) {
|
||||||
|
if (mounted) setState(() => _status = error.toString());
|
||||||
|
}
|
||||||
|
},
|
||||||
|
child: Text(T('set.openFolder')),
|
||||||
|
),
|
||||||
|
OutlinedButton(
|
||||||
|
onPressed: () async {
|
||||||
|
await widget.controller.checkUpdate(force: true);
|
||||||
|
if (mounted) setState(() => _status = T('set.cacheCleared'));
|
||||||
|
},
|
||||||
|
child: Text(T('set.clearCache')),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _updateCard(SettingsInfo settings) {
|
||||||
|
return GcCard(
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: <Widget>[
|
||||||
|
GcSectionTitle(T('update.title')),
|
||||||
|
const SizedBox(height: GcSpace.md),
|
||||||
|
GcHint(T('set.checkUpdate.desc')),
|
||||||
|
const SizedBox(height: GcSpace.md),
|
||||||
|
Row(
|
||||||
|
children: <Widget>[
|
||||||
|
Switch(
|
||||||
|
value: _autoUpdate,
|
||||||
|
onChanged: (value) async {
|
||||||
|
setState(() => _autoUpdate = value);
|
||||||
|
await widget.controller
|
||||||
|
.saveSettings(SettingsPatch(autoUpdateOnStartup: value));
|
||||||
|
},
|
||||||
|
),
|
||||||
|
const SizedBox(width: GcSpace.md),
|
||||||
|
Expanded(
|
||||||
|
child: Text(
|
||||||
|
T('update.auto'),
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 13,
|
||||||
|
height: 1.5,
|
||||||
|
color: GcColors.muted,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
const SizedBox(height: GcSpace.sm),
|
||||||
|
GcFieldRow(
|
||||||
|
label: T('update.source'),
|
||||||
|
value: settings.updateRepository,
|
||||||
|
selectable: true,
|
||||||
|
valueColor: GcColors.muted,
|
||||||
|
),
|
||||||
|
const SizedBox(height: GcSpace.md),
|
||||||
|
FilledButton(
|
||||||
|
onPressed: () => widget.controller.checkUpdate(force: true),
|
||||||
|
child: Text(T('update.checkNow')),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _backendCard(SettingsInfo settings) {
|
||||||
|
final health = widget.controller.health;
|
||||||
|
return GcCard(
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: <Widget>[
|
||||||
|
GcSectionTitle(T('set.backend')),
|
||||||
|
const SizedBox(height: GcSpace.md),
|
||||||
|
GcHint(T('set.backend.desc')),
|
||||||
|
const SizedBox(height: GcSpace.md),
|
||||||
|
GcFieldRow(
|
||||||
|
label: 'API',
|
||||||
|
value: widget.controller.api.baseUrl,
|
||||||
|
selectable: true,
|
||||||
|
valueColor: GcColors.muted,
|
||||||
|
),
|
||||||
|
GcFieldRow(
|
||||||
|
label: T('set.version'),
|
||||||
|
value: settings.version,
|
||||||
|
valueColor: GcColors.muted,
|
||||||
|
),
|
||||||
|
GcFieldRow(
|
||||||
|
label: T('set.platform'),
|
||||||
|
value: settings.platform,
|
||||||
|
valueColor: GcColors.muted,
|
||||||
|
),
|
||||||
|
GcFieldRow(
|
||||||
|
label: T('set.backend.ui'),
|
||||||
|
value: health == null
|
||||||
|
? '—'
|
||||||
|
: health.uiAvailable
|
||||||
|
? T('set.backend.uiOk')
|
||||||
|
: '${T('set.backend.uiBad')}${health.uiError == null ? '' : ' · ${health.uiError}'}',
|
||||||
|
valueColor: health == null
|
||||||
|
? GcColors.muted
|
||||||
|
: health.uiAvailable
|
||||||
|
? GcColors.ok
|
||||||
|
: GcColors.danger,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,453 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
import 'controller.dart';
|
||||||
|
import 'i18n.dart';
|
||||||
|
import 'pages.dart';
|
||||||
|
import 'theme.dart';
|
||||||
|
|
||||||
|
/// 侧边栏导航项。
|
||||||
|
class _NavItem {
|
||||||
|
const _NavItem(this.icon, this.labelKey);
|
||||||
|
|
||||||
|
final IconData icon;
|
||||||
|
final String labelKey;
|
||||||
|
}
|
||||||
|
|
||||||
|
const List<_NavItem> _navItems = <_NavItem>[
|
||||||
|
_NavItem(Icons.dashboard_rounded, 'nav.home'),
|
||||||
|
_NavItem(Icons.download_rounded, 'nav.download'),
|
||||||
|
_NavItem(Icons.tune_rounded, 'nav.settings'),
|
||||||
|
_NavItem(Icons.info_outline_rounded, 'nav.about'),
|
||||||
|
];
|
||||||
|
|
||||||
|
/// 桌面端滚动行为:去掉移动端的拉伸回弹和边缘光晕,滚轮更跟手。
|
||||||
|
class GcScrollBehavior extends MaterialScrollBehavior {
|
||||||
|
const GcScrollBehavior();
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget buildOverscrollIndicator(
|
||||||
|
BuildContext context,
|
||||||
|
Widget child,
|
||||||
|
ScrollableDetails details,
|
||||||
|
) {
|
||||||
|
return child;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
ScrollPhysics getScrollPhysics(BuildContext context) {
|
||||||
|
return const ClampingScrollPhysics(parent: AlwaysScrollableScrollPhysics());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 应用外壳:左侧导航 + 右侧内容 + 底部更新状态条。
|
||||||
|
class ShellPage extends StatefulWidget {
|
||||||
|
const ShellPage({super.key, required this.controller});
|
||||||
|
|
||||||
|
final ShellController controller;
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<ShellPage> createState() => _ShellPageState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _ShellPageState extends State<ShellPage> {
|
||||||
|
/// 页面缓存:键为「索引:语言」。同一个页面只构建一次,切走时用
|
||||||
|
/// [Offstage] 保活(不参与布局/绘制),切回来无需重建、状态也不丢。
|
||||||
|
final Map<String, Widget> _pages = <String, Widget>{};
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
widget.controller.bootstrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return AnimatedBuilder(
|
||||||
|
animation: widget.controller,
|
||||||
|
builder: (context, _) {
|
||||||
|
final controller = widget.controller;
|
||||||
|
return Scaffold(
|
||||||
|
backgroundColor: GcColors.appBg,
|
||||||
|
body: Row(
|
||||||
|
children: <Widget>[
|
||||||
|
_Sidebar(controller: controller),
|
||||||
|
Container(width: 1, color: GcColors.line),
|
||||||
|
Expanded(
|
||||||
|
child: Column(
|
||||||
|
children: <Widget>[
|
||||||
|
Expanded(child: _content(controller)),
|
||||||
|
if (controller.updateBarVisible)
|
||||||
|
_UpdateBar(controller: controller),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _content(ShellController controller) {
|
||||||
|
if (!controller.backendReady) {
|
||||||
|
if (controller.loadError != null) {
|
||||||
|
return _BackendDown(controller: controller);
|
||||||
|
}
|
||||||
|
return const Center(
|
||||||
|
child: SizedBox(
|
||||||
|
width: 22,
|
||||||
|
height: 22,
|
||||||
|
child: CircularProgressIndicator(strokeWidth: 2),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 只构建当前页;其余已访问页面保留在树上但处于 Offstage。
|
||||||
|
final key = '${controller.index}:${I18n.language.value}';
|
||||||
|
_pages.putIfAbsent(key, () => _buildPage(controller, controller.index));
|
||||||
|
|
||||||
|
final visibleKey = key;
|
||||||
|
return Stack(
|
||||||
|
children: <Widget>[
|
||||||
|
for (final entry in _pages.entries)
|
||||||
|
Offstage(
|
||||||
|
offstage: entry.key != visibleKey,
|
||||||
|
child: TickerMode(
|
||||||
|
enabled: entry.key == visibleKey,
|
||||||
|
child: entry.value,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _buildPage(ShellController controller, int index) {
|
||||||
|
switch (index) {
|
||||||
|
case 1:
|
||||||
|
return DownloadPageView(controller: controller);
|
||||||
|
case 2:
|
||||||
|
return SettingsPageView(controller: controller);
|
||||||
|
case 3:
|
||||||
|
return AboutPageView(controller: controller);
|
||||||
|
default:
|
||||||
|
return HomePageView(controller: controller);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _Sidebar extends StatelessWidget {
|
||||||
|
const _Sidebar({required this.controller});
|
||||||
|
|
||||||
|
final ShellController controller;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final settings = controller.settings;
|
||||||
|
return Container(
|
||||||
|
width: GcSize.sidebar,
|
||||||
|
color: GcColors.sideBg,
|
||||||
|
padding: const EdgeInsets.fromLTRB(
|
||||||
|
GcSpace.xl, GcSpace.xxl, GcSpace.lg, GcSpace.lg),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: <Widget>[
|
||||||
|
_brand(),
|
||||||
|
const SizedBox(height: GcSpace.xxxl),
|
||||||
|
const Padding(
|
||||||
|
padding: EdgeInsets.only(left: 10, bottom: GcSpace.sm),
|
||||||
|
child: Text(
|
||||||
|
'MENU',
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 11,
|
||||||
|
height: 1.2,
|
||||||
|
letterSpacing: 1.4,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
color: Color(0xFF5C6A80),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
for (var i = 0; i < _navItems.length; i++)
|
||||||
|
_NavButton(
|
||||||
|
item: _navItems[i],
|
||||||
|
active: controller.index == i,
|
||||||
|
onTap: () => controller.goTo(i),
|
||||||
|
),
|
||||||
|
const Spacer(),
|
||||||
|
Container(height: 1, color: GcColors.line),
|
||||||
|
const SizedBox(height: GcSpace.md),
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.only(left: 10),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: <Widget>[
|
||||||
|
Text(
|
||||||
|
'v${settings?.version ?? '—'}',
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 12,
|
||||||
|
height: 1.4,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
color: GcColors.muted,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 2),
|
||||||
|
Text(
|
||||||
|
settings?.platform ?? '—',
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 11.5,
|
||||||
|
height: 1.4,
|
||||||
|
color: GcColors.ghost,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 品牌区:一个渐变圆角标 + 名称 + 一句定位。
|
||||||
|
Widget _brand() {
|
||||||
|
return Row(
|
||||||
|
children: <Widget>[
|
||||||
|
Container(
|
||||||
|
width: 32,
|
||||||
|
height: 32,
|
||||||
|
alignment: Alignment.center,
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: GcColors.accentSoft,
|
||||||
|
borderRadius: BorderRadius.circular(9),
|
||||||
|
border: Border.all(
|
||||||
|
color: Color.alphaBlend(
|
||||||
|
GcColors.accent.withOpacity(0.35), GcColors.sideBg),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: Text(
|
||||||
|
'◎',
|
||||||
|
style: TextStyle(fontSize: 16, height: 1.1, color: GcColors.accent),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(width: GcSpace.md),
|
||||||
|
Expanded(
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: <Widget>[
|
||||||
|
Text(
|
||||||
|
'Morris GC',
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 14,
|
||||||
|
height: 1.3,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
color: GcColors.ink,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 1),
|
||||||
|
Text(
|
||||||
|
'SCIENCE · CLASSROOM',
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 10,
|
||||||
|
height: 1.3,
|
||||||
|
letterSpacing: 0.9,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
color: GcColors.ghost,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _NavButton extends StatelessWidget {
|
||||||
|
const _NavButton({
|
||||||
|
required this.item,
|
||||||
|
required this.active,
|
||||||
|
required this.onTap,
|
||||||
|
});
|
||||||
|
|
||||||
|
final _NavItem item;
|
||||||
|
final bool active;
|
||||||
|
final VoidCallback onTap;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return Padding(
|
||||||
|
padding: const EdgeInsets.only(bottom: GcSpace.xs),
|
||||||
|
child: Material(
|
||||||
|
color: active ? GcColors.accentSoft : Colors.transparent,
|
||||||
|
borderRadius: BorderRadius.circular(GcRadius.control),
|
||||||
|
child: InkWell(
|
||||||
|
borderRadius: BorderRadius.circular(GcRadius.control),
|
||||||
|
onTap: onTap,
|
||||||
|
hoverColor: GcColors.surfaceHover,
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.symmetric(
|
||||||
|
horizontal: GcSpace.md,
|
||||||
|
vertical: 11,
|
||||||
|
),
|
||||||
|
child: Row(
|
||||||
|
children: <Widget>[
|
||||||
|
Icon(
|
||||||
|
item.icon,
|
||||||
|
size: 17,
|
||||||
|
color: active ? GcColors.accent : GcColors.faint,
|
||||||
|
),
|
||||||
|
const SizedBox(width: GcSpace.md),
|
||||||
|
Text(
|
||||||
|
T(item.labelKey),
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 13.5,
|
||||||
|
height: 1.2,
|
||||||
|
fontWeight: active ? FontWeight.w600 : FontWeight.w400,
|
||||||
|
color: active ? GcColors.accent : GcColors.muted,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _UpdateBar extends StatelessWidget {
|
||||||
|
const _UpdateBar({required this.controller});
|
||||||
|
|
||||||
|
final ShellController controller;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return Container(
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: GcColors.surface,
|
||||||
|
border: Border(top: BorderSide(color: GcColors.line)),
|
||||||
|
),
|
||||||
|
padding: const EdgeInsets.symmetric(
|
||||||
|
horizontal: GcSpace.xxl,
|
||||||
|
vertical: GcSpace.md,
|
||||||
|
),
|
||||||
|
child: Row(
|
||||||
|
children: <Widget>[
|
||||||
|
Icon(
|
||||||
|
Icons.sync_rounded,
|
||||||
|
size: 18,
|
||||||
|
color: GcColors.accent,
|
||||||
|
),
|
||||||
|
const SizedBox(width: GcSpace.md),
|
||||||
|
Expanded(
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: <Widget>[
|
||||||
|
Text(
|
||||||
|
controller.updateStatus,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 13,
|
||||||
|
height: 1.35,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
color: GcColors.ink,
|
||||||
|
),
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
),
|
||||||
|
if (controller.updateDetail.isNotEmpty)
|
||||||
|
Text(
|
||||||
|
controller.updateDetail,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 12,
|
||||||
|
height: 1.4,
|
||||||
|
color: GcColors.faint,
|
||||||
|
),
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
),
|
||||||
|
if (controller.launcherNotice.isNotEmpty)
|
||||||
|
Text(
|
||||||
|
controller.launcherNotice,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 12,
|
||||||
|
height: 1.4,
|
||||||
|
color: GcColors.warn,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
if (controller.updateBusy) ...<Widget>[
|
||||||
|
const SizedBox(width: GcSpace.lg),
|
||||||
|
SizedBox(
|
||||||
|
width: 140,
|
||||||
|
child: ClipRRect(
|
||||||
|
borderRadius: BorderRadius.circular(3),
|
||||||
|
child: LinearProgressIndicator(
|
||||||
|
value: controller.updateProgress > 0
|
||||||
|
? controller.updateProgress.clamp(0, 1).toDouble()
|
||||||
|
: null,
|
||||||
|
minHeight: 4,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
const SizedBox(width: GcSpace.lg),
|
||||||
|
TextButton(
|
||||||
|
onPressed: controller.updateBusy
|
||||||
|
? null
|
||||||
|
: () => controller.checkUpdate(force: true),
|
||||||
|
child: Text(T('update.checkNow')),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _BackendDown extends StatelessWidget {
|
||||||
|
const _BackendDown({required this.controller});
|
||||||
|
|
||||||
|
final ShellController controller;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return Center(
|
||||||
|
child: ConstrainedBox(
|
||||||
|
constraints: const BoxConstraints(maxWidth: 520),
|
||||||
|
child: GcCard(
|
||||||
|
padding: const EdgeInsets.all(GcSpace.xxl),
|
||||||
|
child: Column(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: <Widget>[
|
||||||
|
Row(
|
||||||
|
children: <Widget>[
|
||||||
|
Icon(Icons.error_outline_rounded,
|
||||||
|
size: 20, color: GcColors.danger),
|
||||||
|
const SizedBox(width: GcSpace.sm),
|
||||||
|
Text(
|
||||||
|
T('common.error'),
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 16,
|
||||||
|
height: 1.35,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
color: GcColors.ink,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
const SizedBox(height: GcSpace.md),
|
||||||
|
GcHint(controller.loadError ?? ''),
|
||||||
|
const SizedBox(height: GcSpace.xs),
|
||||||
|
GcHint('${T('set.backend')}: ${controller.api.baseUrl}'),
|
||||||
|
const SizedBox(height: GcSpace.lg),
|
||||||
|
FilledButton(
|
||||||
|
onPressed: controller.bootstrap,
|
||||||
|
child: Text(T('common.retry')),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
flutter/ephemeral
|
||||||
@@ -0,0 +1,146 @@
|
|||||||
|
# Project-level configuration.
|
||||||
|
cmake_minimum_required(VERSION 3.10)
|
||||||
|
project(runner LANGUAGES CXX)
|
||||||
|
|
||||||
|
# The name of the executable created for the application. Change this to change
|
||||||
|
# the on-disk name of your application.
|
||||||
|
set(BINARY_NAME "GC-UI")
|
||||||
|
# The unique GTK application identifier for this application. See:
|
||||||
|
# https://wiki.gnome.org/HowDoI/ChooseApplicationID
|
||||||
|
set(APPLICATION_ID "com.xhmcl.GC")
|
||||||
|
|
||||||
|
# Explicitly opt in to modern CMake behaviors to avoid warnings with recent
|
||||||
|
# versions of CMake.
|
||||||
|
cmake_policy(SET CMP0063 NEW)
|
||||||
|
|
||||||
|
# Load bundled libraries from the lib/ directory relative to the binary.
|
||||||
|
set(CMAKE_INSTALL_RPATH "$ORIGIN/lib")
|
||||||
|
|
||||||
|
# Root filesystem for cross-building.
|
||||||
|
if(FLUTTER_TARGET_PLATFORM_SYSROOT)
|
||||||
|
set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT})
|
||||||
|
set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT})
|
||||||
|
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
|
||||||
|
set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)
|
||||||
|
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
|
||||||
|
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
# Define build configuration options.
|
||||||
|
if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
|
||||||
|
set(CMAKE_BUILD_TYPE "Debug" CACHE
|
||||||
|
STRING "Flutter build mode" FORCE)
|
||||||
|
set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS
|
||||||
|
"Debug" "Profile" "Release")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
# Compilation settings that should be applied to most targets.
|
||||||
|
#
|
||||||
|
# Be cautious about adding new options here, as plugins use this function by
|
||||||
|
# default. In most cases, you should add new options to specific targets instead
|
||||||
|
# of modifying this function.
|
||||||
|
function(APPLY_STANDARD_SETTINGS TARGET)
|
||||||
|
target_compile_features(${TARGET} PUBLIC cxx_std_14)
|
||||||
|
target_compile_options(${TARGET} PRIVATE -Wall -Werror)
|
||||||
|
target_compile_options(${TARGET} PRIVATE "$<$<NOT:$<CONFIG:Debug>>:-O3>")
|
||||||
|
target_compile_definitions(${TARGET} PRIVATE "$<$<NOT:$<CONFIG:Debug>>:NDEBUG>")
|
||||||
|
endfunction()
|
||||||
|
|
||||||
|
# Flutter library and tool build rules.
|
||||||
|
set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter")
|
||||||
|
add_subdirectory(${FLUTTER_MANAGED_DIR})
|
||||||
|
|
||||||
|
# System-level dependencies.
|
||||||
|
find_package(PkgConfig REQUIRED)
|
||||||
|
pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0)
|
||||||
|
|
||||||
|
add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}")
|
||||||
|
|
||||||
|
# Define the application target. To change its name, change BINARY_NAME above,
|
||||||
|
# not the value here, or `flutter run` will no longer work.
|
||||||
|
#
|
||||||
|
# Any new source files that you add to the application should be added here.
|
||||||
|
add_executable(${BINARY_NAME}
|
||||||
|
"main.cc"
|
||||||
|
"my_application.cc"
|
||||||
|
"${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Apply the standard set of build settings. This can be removed for applications
|
||||||
|
# that need different build settings.
|
||||||
|
apply_standard_settings(${BINARY_NAME})
|
||||||
|
|
||||||
|
# Add dependency libraries. Add any application-specific dependencies here.
|
||||||
|
target_link_libraries(${BINARY_NAME} PRIVATE flutter)
|
||||||
|
target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK)
|
||||||
|
|
||||||
|
# Run the Flutter tool portions of the build. This must not be removed.
|
||||||
|
add_dependencies(${BINARY_NAME} flutter_assemble)
|
||||||
|
|
||||||
|
# Only the install-generated bundle's copy of the executable will launch
|
||||||
|
# correctly, since the resources must in the right relative locations. To avoid
|
||||||
|
# people trying to run the unbundled copy, put it in a subdirectory instead of
|
||||||
|
# the default top-level location.
|
||||||
|
set_target_properties(${BINARY_NAME}
|
||||||
|
PROPERTIES
|
||||||
|
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# Generated plugin build rules, which manage building the plugins and adding
|
||||||
|
# them to the application.
|
||||||
|
include(flutter/generated_plugins.cmake)
|
||||||
|
|
||||||
|
|
||||||
|
# === Installation ===
|
||||||
|
# By default, "installing" just makes a relocatable bundle in the build
|
||||||
|
# directory.
|
||||||
|
set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle")
|
||||||
|
# 无条件强制安装到 build 目录下的 bundle:某些环境下 CMAKE_INSTALL_PREFIX
|
||||||
|
# 会被初始化成 /usr/local,导致 flutter build linux 声称成功、却把产物装进
|
||||||
|
# 系统目录,build/.../bundle 是空的。
|
||||||
|
set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "Flutter bundle 输出目录" FORCE)
|
||||||
|
|
||||||
|
# Start with a clean build bundle directory every time.
|
||||||
|
install(CODE "
|
||||||
|
file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\")
|
||||||
|
" COMPONENT Runtime)
|
||||||
|
|
||||||
|
set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data")
|
||||||
|
set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib")
|
||||||
|
|
||||||
|
install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}"
|
||||||
|
COMPONENT Runtime)
|
||||||
|
|
||||||
|
install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}"
|
||||||
|
COMPONENT Runtime)
|
||||||
|
|
||||||
|
install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
|
||||||
|
COMPONENT Runtime)
|
||||||
|
|
||||||
|
foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES})
|
||||||
|
install(FILES "${bundled_library}"
|
||||||
|
DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
|
||||||
|
COMPONENT Runtime)
|
||||||
|
endforeach(bundled_library)
|
||||||
|
|
||||||
|
# Copy the native assets provided by the build.dart from all packages.
|
||||||
|
set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/")
|
||||||
|
install(DIRECTORY "${NATIVE_ASSETS_DIR}"
|
||||||
|
DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
|
||||||
|
COMPONENT Runtime)
|
||||||
|
|
||||||
|
# Fully re-copy the assets directory on each build to avoid having stale files
|
||||||
|
# from a previous install.
|
||||||
|
set(FLUTTER_ASSET_DIR_NAME "flutter_assets")
|
||||||
|
install(CODE "
|
||||||
|
file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\")
|
||||||
|
" COMPONENT Runtime)
|
||||||
|
install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}"
|
||||||
|
DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime)
|
||||||
|
|
||||||
|
# Install the AOT library on non-Debug builds only.
|
||||||
|
if(NOT CMAKE_BUILD_TYPE MATCHES "Debug")
|
||||||
|
install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
|
||||||
|
COMPONENT Runtime)
|
||||||
|
endif()
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
# This file controls Flutter-level build steps. It should not be edited.
|
||||||
|
cmake_minimum_required(VERSION 3.10)
|
||||||
|
|
||||||
|
set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral")
|
||||||
|
|
||||||
|
# Configuration provided via flutter tool.
|
||||||
|
include(${EPHEMERAL_DIR}/generated_config.cmake)
|
||||||
|
|
||||||
|
# TODO: Move the rest of this into files in ephemeral. See
|
||||||
|
# https://github.com/flutter/flutter/issues/57146.
|
||||||
|
|
||||||
|
# Serves the same purpose as list(TRANSFORM ... PREPEND ...),
|
||||||
|
# which isn't available in 3.10.
|
||||||
|
function(list_prepend LIST_NAME PREFIX)
|
||||||
|
set(NEW_LIST "")
|
||||||
|
foreach(element ${${LIST_NAME}})
|
||||||
|
list(APPEND NEW_LIST "${PREFIX}${element}")
|
||||||
|
endforeach(element)
|
||||||
|
set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE)
|
||||||
|
endfunction()
|
||||||
|
|
||||||
|
# === Flutter Library ===
|
||||||
|
# System-level dependencies.
|
||||||
|
find_package(PkgConfig REQUIRED)
|
||||||
|
pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0)
|
||||||
|
pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0)
|
||||||
|
pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0)
|
||||||
|
|
||||||
|
set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so")
|
||||||
|
|
||||||
|
# Published to parent scope for install step.
|
||||||
|
set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE)
|
||||||
|
set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE)
|
||||||
|
set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE)
|
||||||
|
set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE)
|
||||||
|
|
||||||
|
list(APPEND FLUTTER_LIBRARY_HEADERS
|
||||||
|
"fl_basic_message_channel.h"
|
||||||
|
"fl_binary_codec.h"
|
||||||
|
"fl_binary_messenger.h"
|
||||||
|
"fl_dart_project.h"
|
||||||
|
"fl_engine.h"
|
||||||
|
"fl_json_message_codec.h"
|
||||||
|
"fl_json_method_codec.h"
|
||||||
|
"fl_message_codec.h"
|
||||||
|
"fl_method_call.h"
|
||||||
|
"fl_method_channel.h"
|
||||||
|
"fl_method_codec.h"
|
||||||
|
"fl_method_response.h"
|
||||||
|
"fl_plugin_registrar.h"
|
||||||
|
"fl_plugin_registry.h"
|
||||||
|
"fl_standard_message_codec.h"
|
||||||
|
"fl_standard_method_codec.h"
|
||||||
|
"fl_string_codec.h"
|
||||||
|
"fl_value.h"
|
||||||
|
"fl_view.h"
|
||||||
|
"flutter_linux.h"
|
||||||
|
)
|
||||||
|
list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/")
|
||||||
|
add_library(flutter INTERFACE)
|
||||||
|
target_include_directories(flutter INTERFACE
|
||||||
|
"${EPHEMERAL_DIR}"
|
||||||
|
)
|
||||||
|
target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}")
|
||||||
|
target_link_libraries(flutter INTERFACE
|
||||||
|
PkgConfig::GTK
|
||||||
|
PkgConfig::GLIB
|
||||||
|
PkgConfig::GIO
|
||||||
|
)
|
||||||
|
add_dependencies(flutter flutter_assemble)
|
||||||
|
|
||||||
|
# === Flutter tool backend ===
|
||||||
|
# _phony_ is a non-existent file to force this command to run every time,
|
||||||
|
# since currently there's no way to get a full input/output list from the
|
||||||
|
# flutter tool.
|
||||||
|
add_custom_command(
|
||||||
|
OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS}
|
||||||
|
${CMAKE_CURRENT_BINARY_DIR}/_phony_
|
||||||
|
COMMAND ${CMAKE_COMMAND} -E env
|
||||||
|
${FLUTTER_TOOL_ENVIRONMENT}
|
||||||
|
"${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh"
|
||||||
|
${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE}
|
||||||
|
VERBATIM
|
||||||
|
)
|
||||||
|
add_custom_target(flutter_assemble DEPENDS
|
||||||
|
"${FLUTTER_LIBRARY}"
|
||||||
|
${FLUTTER_LIBRARY_HEADERS}
|
||||||
|
)
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
#include "my_application.h"
|
||||||
|
|
||||||
|
int main(int argc, char** argv) {
|
||||||
|
g_autoptr(MyApplication) app = my_application_new();
|
||||||
|
return g_application_run(G_APPLICATION(app), argc, argv);
|
||||||
|
}
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
#include "my_application.h"
|
||||||
|
|
||||||
|
#include <flutter_linux/flutter_linux.h>
|
||||||
|
#ifdef GDK_WINDOWING_X11
|
||||||
|
#include <gdk/gdkx.h>
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#include "flutter/generated_plugin_registrant.h"
|
||||||
|
|
||||||
|
struct _MyApplication {
|
||||||
|
GtkApplication parent_instance;
|
||||||
|
char** dart_entrypoint_arguments;
|
||||||
|
};
|
||||||
|
|
||||||
|
G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION)
|
||||||
|
|
||||||
|
// Implements GApplication::activate.
|
||||||
|
static void my_application_activate(GApplication* application) {
|
||||||
|
MyApplication* self = MY_APPLICATION(application);
|
||||||
|
GtkWindow* window =
|
||||||
|
GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application)));
|
||||||
|
|
||||||
|
// Use a header bar when running in GNOME as this is the common style used
|
||||||
|
// by applications and is the setup most users will be using (e.g. Ubuntu
|
||||||
|
// desktop).
|
||||||
|
// If running on X and not using GNOME then just use a traditional title bar
|
||||||
|
// in case the window manager does more exotic layout, e.g. tiling.
|
||||||
|
// If running on Wayland assume the header bar will work (may need changing
|
||||||
|
// if future cases occur).
|
||||||
|
gboolean use_header_bar = TRUE;
|
||||||
|
#ifdef GDK_WINDOWING_X11
|
||||||
|
GdkScreen* screen = gtk_window_get_screen(window);
|
||||||
|
if (GDK_IS_X11_SCREEN(screen)) {
|
||||||
|
const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen);
|
||||||
|
if (g_strcmp0(wm_name, "GNOME Shell") != 0) {
|
||||||
|
use_header_bar = FALSE;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
if (use_header_bar) {
|
||||||
|
GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new());
|
||||||
|
gtk_widget_show(GTK_WIDGET(header_bar));
|
||||||
|
gtk_header_bar_set_title(header_bar, "Morris GC");
|
||||||
|
gtk_header_bar_set_show_close_button(header_bar, TRUE);
|
||||||
|
gtk_window_set_titlebar(window, GTK_WIDGET(header_bar));
|
||||||
|
} else {
|
||||||
|
gtk_window_set_title(window, "Morris GC");
|
||||||
|
}
|
||||||
|
|
||||||
|
gtk_window_set_default_size(window, 1280, 720);
|
||||||
|
gtk_widget_show(GTK_WIDGET(window));
|
||||||
|
|
||||||
|
g_autoptr(FlDartProject) project = fl_dart_project_new();
|
||||||
|
fl_dart_project_set_dart_entrypoint_arguments(project, self->dart_entrypoint_arguments);
|
||||||
|
|
||||||
|
FlView* view = fl_view_new(project);
|
||||||
|
gtk_widget_show(GTK_WIDGET(view));
|
||||||
|
gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view));
|
||||||
|
|
||||||
|
fl_register_plugins(FL_PLUGIN_REGISTRY(view));
|
||||||
|
|
||||||
|
gtk_widget_grab_focus(GTK_WIDGET(view));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Implements GApplication::local_command_line.
|
||||||
|
static gboolean my_application_local_command_line(GApplication* application, gchar*** arguments, int* exit_status) {
|
||||||
|
MyApplication* self = MY_APPLICATION(application);
|
||||||
|
// Strip out the first argument as it is the binary name.
|
||||||
|
self->dart_entrypoint_arguments = g_strdupv(*arguments + 1);
|
||||||
|
|
||||||
|
g_autoptr(GError) error = nullptr;
|
||||||
|
if (!g_application_register(application, nullptr, &error)) {
|
||||||
|
g_warning("Failed to register: %s", error->message);
|
||||||
|
*exit_status = 1;
|
||||||
|
return TRUE;
|
||||||
|
}
|
||||||
|
|
||||||
|
g_application_activate(application);
|
||||||
|
*exit_status = 0;
|
||||||
|
|
||||||
|
return TRUE;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Implements GApplication::startup.
|
||||||
|
static void my_application_startup(GApplication* application) {
|
||||||
|
//MyApplication* self = MY_APPLICATION(object);
|
||||||
|
|
||||||
|
// Perform any actions required at application startup.
|
||||||
|
|
||||||
|
G_APPLICATION_CLASS(my_application_parent_class)->startup(application);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Implements GApplication::shutdown.
|
||||||
|
static void my_application_shutdown(GApplication* application) {
|
||||||
|
//MyApplication* self = MY_APPLICATION(object);
|
||||||
|
|
||||||
|
// Perform any actions required at application shutdown.
|
||||||
|
|
||||||
|
G_APPLICATION_CLASS(my_application_parent_class)->shutdown(application);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Implements GObject::dispose.
|
||||||
|
static void my_application_dispose(GObject* object) {
|
||||||
|
MyApplication* self = MY_APPLICATION(object);
|
||||||
|
g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev);
|
||||||
|
G_OBJECT_CLASS(my_application_parent_class)->dispose(object);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void my_application_class_init(MyApplicationClass* klass) {
|
||||||
|
G_APPLICATION_CLASS(klass)->activate = my_application_activate;
|
||||||
|
G_APPLICATION_CLASS(klass)->local_command_line = my_application_local_command_line;
|
||||||
|
G_APPLICATION_CLASS(klass)->startup = my_application_startup;
|
||||||
|
G_APPLICATION_CLASS(klass)->shutdown = my_application_shutdown;
|
||||||
|
G_OBJECT_CLASS(klass)->dispose = my_application_dispose;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void my_application_init(MyApplication* self) {}
|
||||||
|
|
||||||
|
MyApplication* my_application_new() {
|
||||||
|
return MY_APPLICATION(g_object_new(my_application_get_type(),
|
||||||
|
"application-id", APPLICATION_ID,
|
||||||
|
"flags", G_APPLICATION_NON_UNIQUE,
|
||||||
|
nullptr));
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
#ifndef FLUTTER_MY_APPLICATION_H_
|
||||||
|
#define FLUTTER_MY_APPLICATION_H_
|
||||||
|
|
||||||
|
#include <gtk/gtk.h>
|
||||||
|
|
||||||
|
G_DECLARE_FINAL_TYPE(MyApplication, my_application, MY, APPLICATION,
|
||||||
|
GtkApplication)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* my_application_new:
|
||||||
|
*
|
||||||
|
* Creates a new Flutter-based application.
|
||||||
|
*
|
||||||
|
* Returns: a new #MyApplication.
|
||||||
|
*/
|
||||||
|
MyApplication* my_application_new();
|
||||||
|
|
||||||
|
#endif // FLUTTER_MY_APPLICATION_H_
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
# Flutter-related
|
||||||
|
**/Flutter/ephemeral/
|
||||||
|
**/Pods/
|
||||||
|
|
||||||
|
# Xcode-related
|
||||||
|
**/dgph
|
||||||
|
**/xcuserdata/
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
#include "ephemeral/Flutter-Generated.xcconfig"
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
#include "ephemeral/Flutter-Generated.xcconfig"
|
||||||
@@ -0,0 +1,705 @@
|
|||||||
|
// !$*UTF8*$!
|
||||||
|
{
|
||||||
|
archiveVersion = 1;
|
||||||
|
classes = {
|
||||||
|
};
|
||||||
|
objectVersion = 54;
|
||||||
|
objects = {
|
||||||
|
|
||||||
|
/* Begin PBXAggregateTarget section */
|
||||||
|
33CC111A2044C6BA0003C045 /* Flutter Assemble */ = {
|
||||||
|
isa = PBXAggregateTarget;
|
||||||
|
buildConfigurationList = 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */;
|
||||||
|
buildPhases = (
|
||||||
|
33CC111E2044C6BF0003C045 /* ShellScript */,
|
||||||
|
);
|
||||||
|
dependencies = (
|
||||||
|
);
|
||||||
|
name = "Flutter Assemble";
|
||||||
|
productName = FLX;
|
||||||
|
};
|
||||||
|
/* End PBXAggregateTarget section */
|
||||||
|
|
||||||
|
/* Begin PBXBuildFile section */
|
||||||
|
331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C80D7294CF71000263BE5 /* RunnerTests.swift */; };
|
||||||
|
335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */; };
|
||||||
|
33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC10F02044A3C60003C045 /* AppDelegate.swift */; };
|
||||||
|
33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F22044A3C60003C045 /* Assets.xcassets */; };
|
||||||
|
33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F42044A3C60003C045 /* MainMenu.xib */; };
|
||||||
|
33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */; };
|
||||||
|
/* End PBXBuildFile section */
|
||||||
|
|
||||||
|
/* Begin PBXContainerItemProxy section */
|
||||||
|
331C80D9294CF71000263BE5 /* PBXContainerItemProxy */ = {
|
||||||
|
isa = PBXContainerItemProxy;
|
||||||
|
containerPortal = 33CC10E52044A3C60003C045 /* Project object */;
|
||||||
|
proxyType = 1;
|
||||||
|
remoteGlobalIDString = 33CC10EC2044A3C60003C045;
|
||||||
|
remoteInfo = Runner;
|
||||||
|
};
|
||||||
|
33CC111F2044C79F0003C045 /* PBXContainerItemProxy */ = {
|
||||||
|
isa = PBXContainerItemProxy;
|
||||||
|
containerPortal = 33CC10E52044A3C60003C045 /* Project object */;
|
||||||
|
proxyType = 1;
|
||||||
|
remoteGlobalIDString = 33CC111A2044C6BA0003C045;
|
||||||
|
remoteInfo = FLX;
|
||||||
|
};
|
||||||
|
/* End PBXContainerItemProxy section */
|
||||||
|
|
||||||
|
/* Begin PBXCopyFilesBuildPhase section */
|
||||||
|
33CC110E2044A8840003C045 /* Bundle Framework */ = {
|
||||||
|
isa = PBXCopyFilesBuildPhase;
|
||||||
|
buildActionMask = 2147483647;
|
||||||
|
dstPath = "";
|
||||||
|
dstSubfolderSpec = 10;
|
||||||
|
files = (
|
||||||
|
);
|
||||||
|
name = "Bundle Framework";
|
||||||
|
runOnlyForDeploymentPostprocessing = 0;
|
||||||
|
};
|
||||||
|
/* End PBXCopyFilesBuildPhase section */
|
||||||
|
|
||||||
|
/* Begin PBXFileReference section */
|
||||||
|
331C80D5294CF71000263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||||
|
331C80D7294CF71000263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = "<group>"; };
|
||||||
|
333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = "<group>"; };
|
||||||
|
335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = "<group>"; };
|
||||||
|
33CC10ED2044A3C60003C045 /* gc_ui.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "gc_ui.app"; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||||
|
33CC10F02044A3C60003C045 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
|
||||||
|
33CC10F22044A3C60003C045 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Assets.xcassets; path = Runner/Assets.xcassets; sourceTree = "<group>"; };
|
||||||
|
33CC10F52044A3C60003C045 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/MainMenu.xib; sourceTree = "<group>"; };
|
||||||
|
33CC10F72044A3C60003C045 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = Info.plist; path = Runner/Info.plist; sourceTree = "<group>"; };
|
||||||
|
33CC11122044BFA00003C045 /* MainFlutterWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MainFlutterWindow.swift; sourceTree = "<group>"; };
|
||||||
|
33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Debug.xcconfig"; sourceTree = "<group>"; };
|
||||||
|
33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Release.xcconfig"; sourceTree = "<group>"; };
|
||||||
|
33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = "Flutter-Generated.xcconfig"; path = "ephemeral/Flutter-Generated.xcconfig"; sourceTree = "<group>"; };
|
||||||
|
33E51913231747F40026EE4D /* DebugProfile.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = DebugProfile.entitlements; sourceTree = "<group>"; };
|
||||||
|
33E51914231749380026EE4D /* Release.entitlements */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.entitlements; path = Release.entitlements; sourceTree = "<group>"; };
|
||||||
|
33E5194F232828860026EE4D /* AppInfo.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AppInfo.xcconfig; sourceTree = "<group>"; };
|
||||||
|
7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = "<group>"; };
|
||||||
|
9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = "<group>"; };
|
||||||
|
/* End PBXFileReference section */
|
||||||
|
|
||||||
|
/* Begin PBXFrameworksBuildPhase section */
|
||||||
|
331C80D2294CF70F00263BE5 /* Frameworks */ = {
|
||||||
|
isa = PBXFrameworksBuildPhase;
|
||||||
|
buildActionMask = 2147483647;
|
||||||
|
files = (
|
||||||
|
);
|
||||||
|
runOnlyForDeploymentPostprocessing = 0;
|
||||||
|
};
|
||||||
|
33CC10EA2044A3C60003C045 /* Frameworks */ = {
|
||||||
|
isa = PBXFrameworksBuildPhase;
|
||||||
|
buildActionMask = 2147483647;
|
||||||
|
files = (
|
||||||
|
);
|
||||||
|
runOnlyForDeploymentPostprocessing = 0;
|
||||||
|
};
|
||||||
|
/* End PBXFrameworksBuildPhase section */
|
||||||
|
|
||||||
|
/* Begin PBXGroup section */
|
||||||
|
331C80D6294CF71000263BE5 /* RunnerTests */ = {
|
||||||
|
isa = PBXGroup;
|
||||||
|
children = (
|
||||||
|
331C80D7294CF71000263BE5 /* RunnerTests.swift */,
|
||||||
|
);
|
||||||
|
path = RunnerTests;
|
||||||
|
sourceTree = "<group>";
|
||||||
|
};
|
||||||
|
33BA886A226E78AF003329D5 /* Configs */ = {
|
||||||
|
isa = PBXGroup;
|
||||||
|
children = (
|
||||||
|
33E5194F232828860026EE4D /* AppInfo.xcconfig */,
|
||||||
|
9740EEB21CF90195004384FC /* Debug.xcconfig */,
|
||||||
|
7AFA3C8E1D35360C0083082E /* Release.xcconfig */,
|
||||||
|
333000ED22D3DE5D00554162 /* Warnings.xcconfig */,
|
||||||
|
);
|
||||||
|
path = Configs;
|
||||||
|
sourceTree = "<group>";
|
||||||
|
};
|
||||||
|
33CC10E42044A3C60003C045 = {
|
||||||
|
isa = PBXGroup;
|
||||||
|
children = (
|
||||||
|
33FAB671232836740065AC1E /* Runner */,
|
||||||
|
33CEB47122A05771004F2AC0 /* Flutter */,
|
||||||
|
331C80D6294CF71000263BE5 /* RunnerTests */,
|
||||||
|
33CC10EE2044A3C60003C045 /* Products */,
|
||||||
|
D73912EC22F37F3D000D13A0 /* Frameworks */,
|
||||||
|
);
|
||||||
|
sourceTree = "<group>";
|
||||||
|
};
|
||||||
|
33CC10EE2044A3C60003C045 /* Products */ = {
|
||||||
|
isa = PBXGroup;
|
||||||
|
children = (
|
||||||
|
33CC10ED2044A3C60003C045 /* gc_ui.app */,
|
||||||
|
331C80D5294CF71000263BE5 /* RunnerTests.xctest */,
|
||||||
|
);
|
||||||
|
name = Products;
|
||||||
|
sourceTree = "<group>";
|
||||||
|
};
|
||||||
|
33CC11242044D66E0003C045 /* Resources */ = {
|
||||||
|
isa = PBXGroup;
|
||||||
|
children = (
|
||||||
|
33CC10F22044A3C60003C045 /* Assets.xcassets */,
|
||||||
|
33CC10F42044A3C60003C045 /* MainMenu.xib */,
|
||||||
|
33CC10F72044A3C60003C045 /* Info.plist */,
|
||||||
|
);
|
||||||
|
name = Resources;
|
||||||
|
path = ..;
|
||||||
|
sourceTree = "<group>";
|
||||||
|
};
|
||||||
|
33CEB47122A05771004F2AC0 /* Flutter */ = {
|
||||||
|
isa = PBXGroup;
|
||||||
|
children = (
|
||||||
|
335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */,
|
||||||
|
33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */,
|
||||||
|
33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */,
|
||||||
|
33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */,
|
||||||
|
);
|
||||||
|
path = Flutter;
|
||||||
|
sourceTree = "<group>";
|
||||||
|
};
|
||||||
|
33FAB671232836740065AC1E /* Runner */ = {
|
||||||
|
isa = PBXGroup;
|
||||||
|
children = (
|
||||||
|
33CC10F02044A3C60003C045 /* AppDelegate.swift */,
|
||||||
|
33CC11122044BFA00003C045 /* MainFlutterWindow.swift */,
|
||||||
|
33E51913231747F40026EE4D /* DebugProfile.entitlements */,
|
||||||
|
33E51914231749380026EE4D /* Release.entitlements */,
|
||||||
|
33CC11242044D66E0003C045 /* Resources */,
|
||||||
|
33BA886A226E78AF003329D5 /* Configs */,
|
||||||
|
);
|
||||||
|
path = Runner;
|
||||||
|
sourceTree = "<group>";
|
||||||
|
};
|
||||||
|
D73912EC22F37F3D000D13A0 /* Frameworks */ = {
|
||||||
|
isa = PBXGroup;
|
||||||
|
children = (
|
||||||
|
);
|
||||||
|
name = Frameworks;
|
||||||
|
sourceTree = "<group>";
|
||||||
|
};
|
||||||
|
/* End PBXGroup section */
|
||||||
|
|
||||||
|
/* Begin PBXNativeTarget section */
|
||||||
|
331C80D4294CF70F00263BE5 /* RunnerTests */ = {
|
||||||
|
isa = PBXNativeTarget;
|
||||||
|
buildConfigurationList = 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */;
|
||||||
|
buildPhases = (
|
||||||
|
331C80D1294CF70F00263BE5 /* Sources */,
|
||||||
|
331C80D2294CF70F00263BE5 /* Frameworks */,
|
||||||
|
331C80D3294CF70F00263BE5 /* Resources */,
|
||||||
|
);
|
||||||
|
buildRules = (
|
||||||
|
);
|
||||||
|
dependencies = (
|
||||||
|
331C80DA294CF71000263BE5 /* PBXTargetDependency */,
|
||||||
|
);
|
||||||
|
name = RunnerTests;
|
||||||
|
productName = RunnerTests;
|
||||||
|
productReference = 331C80D5294CF71000263BE5 /* RunnerTests.xctest */;
|
||||||
|
productType = "com.apple.product-type.bundle.unit-test";
|
||||||
|
};
|
||||||
|
33CC10EC2044A3C60003C045 /* Runner */ = {
|
||||||
|
isa = PBXNativeTarget;
|
||||||
|
buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */;
|
||||||
|
buildPhases = (
|
||||||
|
33CC10E92044A3C60003C045 /* Sources */,
|
||||||
|
33CC10EA2044A3C60003C045 /* Frameworks */,
|
||||||
|
33CC10EB2044A3C60003C045 /* Resources */,
|
||||||
|
33CC110E2044A8840003C045 /* Bundle Framework */,
|
||||||
|
3399D490228B24CF009A79C7 /* ShellScript */,
|
||||||
|
);
|
||||||
|
buildRules = (
|
||||||
|
);
|
||||||
|
dependencies = (
|
||||||
|
33CC11202044C79F0003C045 /* PBXTargetDependency */,
|
||||||
|
);
|
||||||
|
name = Runner;
|
||||||
|
productName = Runner;
|
||||||
|
productReference = 33CC10ED2044A3C60003C045 /* gc_ui.app */;
|
||||||
|
productType = "com.apple.product-type.application";
|
||||||
|
};
|
||||||
|
/* End PBXNativeTarget section */
|
||||||
|
|
||||||
|
/* Begin PBXProject section */
|
||||||
|
33CC10E52044A3C60003C045 /* Project object */ = {
|
||||||
|
isa = PBXProject;
|
||||||
|
attributes = {
|
||||||
|
BuildIndependentTargetsInParallel = YES;
|
||||||
|
LastSwiftUpdateCheck = 0920;
|
||||||
|
LastUpgradeCheck = 1510;
|
||||||
|
ORGANIZATIONNAME = "";
|
||||||
|
TargetAttributes = {
|
||||||
|
331C80D4294CF70F00263BE5 = {
|
||||||
|
CreatedOnToolsVersion = 14.0;
|
||||||
|
TestTargetID = 33CC10EC2044A3C60003C045;
|
||||||
|
};
|
||||||
|
33CC10EC2044A3C60003C045 = {
|
||||||
|
CreatedOnToolsVersion = 9.2;
|
||||||
|
LastSwiftMigration = 1100;
|
||||||
|
ProvisioningStyle = Automatic;
|
||||||
|
SystemCapabilities = {
|
||||||
|
com.apple.Sandbox = {
|
||||||
|
enabled = 1;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
33CC111A2044C6BA0003C045 = {
|
||||||
|
CreatedOnToolsVersion = 9.2;
|
||||||
|
ProvisioningStyle = Manual;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
buildConfigurationList = 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */;
|
||||||
|
compatibilityVersion = "Xcode 9.3";
|
||||||
|
developmentRegion = en;
|
||||||
|
hasScannedForEncodings = 0;
|
||||||
|
knownRegions = (
|
||||||
|
en,
|
||||||
|
Base,
|
||||||
|
);
|
||||||
|
mainGroup = 33CC10E42044A3C60003C045;
|
||||||
|
productRefGroup = 33CC10EE2044A3C60003C045 /* Products */;
|
||||||
|
projectDirPath = "";
|
||||||
|
projectRoot = "";
|
||||||
|
targets = (
|
||||||
|
33CC10EC2044A3C60003C045 /* Runner */,
|
||||||
|
331C80D4294CF70F00263BE5 /* RunnerTests */,
|
||||||
|
33CC111A2044C6BA0003C045 /* Flutter Assemble */,
|
||||||
|
);
|
||||||
|
};
|
||||||
|
/* End PBXProject section */
|
||||||
|
|
||||||
|
/* Begin PBXResourcesBuildPhase section */
|
||||||
|
331C80D3294CF70F00263BE5 /* Resources */ = {
|
||||||
|
isa = PBXResourcesBuildPhase;
|
||||||
|
buildActionMask = 2147483647;
|
||||||
|
files = (
|
||||||
|
);
|
||||||
|
runOnlyForDeploymentPostprocessing = 0;
|
||||||
|
};
|
||||||
|
33CC10EB2044A3C60003C045 /* Resources */ = {
|
||||||
|
isa = PBXResourcesBuildPhase;
|
||||||
|
buildActionMask = 2147483647;
|
||||||
|
files = (
|
||||||
|
33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */,
|
||||||
|
33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */,
|
||||||
|
);
|
||||||
|
runOnlyForDeploymentPostprocessing = 0;
|
||||||
|
};
|
||||||
|
/* End PBXResourcesBuildPhase section */
|
||||||
|
|
||||||
|
/* Begin PBXShellScriptBuildPhase section */
|
||||||
|
3399D490228B24CF009A79C7 /* ShellScript */ = {
|
||||||
|
isa = PBXShellScriptBuildPhase;
|
||||||
|
alwaysOutOfDate = 1;
|
||||||
|
buildActionMask = 2147483647;
|
||||||
|
files = (
|
||||||
|
);
|
||||||
|
inputFileListPaths = (
|
||||||
|
);
|
||||||
|
inputPaths = (
|
||||||
|
);
|
||||||
|
outputFileListPaths = (
|
||||||
|
);
|
||||||
|
outputPaths = (
|
||||||
|
);
|
||||||
|
runOnlyForDeploymentPostprocessing = 0;
|
||||||
|
shellPath = /bin/sh;
|
||||||
|
shellScript = "echo \"$PRODUCT_NAME.app\" > \"$PROJECT_DIR\"/Flutter/ephemeral/.app_filename && \"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh embed\n";
|
||||||
|
};
|
||||||
|
33CC111E2044C6BF0003C045 /* ShellScript */ = {
|
||||||
|
isa = PBXShellScriptBuildPhase;
|
||||||
|
buildActionMask = 2147483647;
|
||||||
|
files = (
|
||||||
|
);
|
||||||
|
inputFileListPaths = (
|
||||||
|
Flutter/ephemeral/FlutterInputs.xcfilelist,
|
||||||
|
);
|
||||||
|
inputPaths = (
|
||||||
|
Flutter/ephemeral/tripwire,
|
||||||
|
);
|
||||||
|
outputFileListPaths = (
|
||||||
|
Flutter/ephemeral/FlutterOutputs.xcfilelist,
|
||||||
|
);
|
||||||
|
outputPaths = (
|
||||||
|
);
|
||||||
|
runOnlyForDeploymentPostprocessing = 0;
|
||||||
|
shellPath = /bin/sh;
|
||||||
|
shellScript = "\"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh && touch Flutter/ephemeral/tripwire";
|
||||||
|
};
|
||||||
|
/* End PBXShellScriptBuildPhase section */
|
||||||
|
|
||||||
|
/* Begin PBXSourcesBuildPhase section */
|
||||||
|
331C80D1294CF70F00263BE5 /* Sources */ = {
|
||||||
|
isa = PBXSourcesBuildPhase;
|
||||||
|
buildActionMask = 2147483647;
|
||||||
|
files = (
|
||||||
|
331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */,
|
||||||
|
);
|
||||||
|
runOnlyForDeploymentPostprocessing = 0;
|
||||||
|
};
|
||||||
|
33CC10E92044A3C60003C045 /* Sources */ = {
|
||||||
|
isa = PBXSourcesBuildPhase;
|
||||||
|
buildActionMask = 2147483647;
|
||||||
|
files = (
|
||||||
|
33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */,
|
||||||
|
33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */,
|
||||||
|
335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */,
|
||||||
|
);
|
||||||
|
runOnlyForDeploymentPostprocessing = 0;
|
||||||
|
};
|
||||||
|
/* End PBXSourcesBuildPhase section */
|
||||||
|
|
||||||
|
/* Begin PBXTargetDependency section */
|
||||||
|
331C80DA294CF71000263BE5 /* PBXTargetDependency */ = {
|
||||||
|
isa = PBXTargetDependency;
|
||||||
|
target = 33CC10EC2044A3C60003C045 /* Runner */;
|
||||||
|
targetProxy = 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */;
|
||||||
|
};
|
||||||
|
33CC11202044C79F0003C045 /* PBXTargetDependency */ = {
|
||||||
|
isa = PBXTargetDependency;
|
||||||
|
target = 33CC111A2044C6BA0003C045 /* Flutter Assemble */;
|
||||||
|
targetProxy = 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */;
|
||||||
|
};
|
||||||
|
/* End PBXTargetDependency section */
|
||||||
|
|
||||||
|
/* Begin PBXVariantGroup section */
|
||||||
|
33CC10F42044A3C60003C045 /* MainMenu.xib */ = {
|
||||||
|
isa = PBXVariantGroup;
|
||||||
|
children = (
|
||||||
|
33CC10F52044A3C60003C045 /* Base */,
|
||||||
|
);
|
||||||
|
name = MainMenu.xib;
|
||||||
|
path = Runner;
|
||||||
|
sourceTree = "<group>";
|
||||||
|
};
|
||||||
|
/* End PBXVariantGroup section */
|
||||||
|
|
||||||
|
/* Begin XCBuildConfiguration section */
|
||||||
|
331C80DB294CF71000263BE5 /* Debug */ = {
|
||||||
|
isa = XCBuildConfiguration;
|
||||||
|
buildSettings = {
|
||||||
|
BUNDLE_LOADER = "$(TEST_HOST)";
|
||||||
|
CURRENT_PROJECT_VERSION = 1;
|
||||||
|
GENERATE_INFOPLIST_FILE = YES;
|
||||||
|
MARKETING_VERSION = 1.0;
|
||||||
|
PRODUCT_BUNDLE_IDENTIFIER = com.morris.gc.gcUi.RunnerTests;
|
||||||
|
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||||
|
SWIFT_VERSION = 5.0;
|
||||||
|
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/gc_ui.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/gc_ui";
|
||||||
|
};
|
||||||
|
name = Debug;
|
||||||
|
};
|
||||||
|
331C80DC294CF71000263BE5 /* Release */ = {
|
||||||
|
isa = XCBuildConfiguration;
|
||||||
|
buildSettings = {
|
||||||
|
BUNDLE_LOADER = "$(TEST_HOST)";
|
||||||
|
CURRENT_PROJECT_VERSION = 1;
|
||||||
|
GENERATE_INFOPLIST_FILE = YES;
|
||||||
|
MARKETING_VERSION = 1.0;
|
||||||
|
PRODUCT_BUNDLE_IDENTIFIER = com.morris.gc.gcUi.RunnerTests;
|
||||||
|
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||||
|
SWIFT_VERSION = 5.0;
|
||||||
|
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/gc_ui.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/gc_ui";
|
||||||
|
};
|
||||||
|
name = Release;
|
||||||
|
};
|
||||||
|
331C80DD294CF71000263BE5 /* Profile */ = {
|
||||||
|
isa = XCBuildConfiguration;
|
||||||
|
buildSettings = {
|
||||||
|
BUNDLE_LOADER = "$(TEST_HOST)";
|
||||||
|
CURRENT_PROJECT_VERSION = 1;
|
||||||
|
GENERATE_INFOPLIST_FILE = YES;
|
||||||
|
MARKETING_VERSION = 1.0;
|
||||||
|
PRODUCT_BUNDLE_IDENTIFIER = com.morris.gc.gcUi.RunnerTests;
|
||||||
|
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||||
|
SWIFT_VERSION = 5.0;
|
||||||
|
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/gc_ui.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/gc_ui";
|
||||||
|
};
|
||||||
|
name = Profile;
|
||||||
|
};
|
||||||
|
338D0CE9231458BD00FA5F75 /* Profile */ = {
|
||||||
|
isa = XCBuildConfiguration;
|
||||||
|
baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */;
|
||||||
|
buildSettings = {
|
||||||
|
ALWAYS_SEARCH_USER_PATHS = NO;
|
||||||
|
ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
|
||||||
|
CLANG_ANALYZER_NONNULL = YES;
|
||||||
|
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
|
||||||
|
CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
|
||||||
|
CLANG_CXX_LIBRARY = "libc++";
|
||||||
|
CLANG_ENABLE_MODULES = YES;
|
||||||
|
CLANG_ENABLE_OBJC_ARC = YES;
|
||||||
|
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
|
||||||
|
CLANG_WARN_BOOL_CONVERSION = YES;
|
||||||
|
CLANG_WARN_CONSTANT_CONVERSION = YES;
|
||||||
|
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
|
||||||
|
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
|
||||||
|
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
|
||||||
|
CLANG_WARN_EMPTY_BODY = YES;
|
||||||
|
CLANG_WARN_ENUM_CONVERSION = YES;
|
||||||
|
CLANG_WARN_INFINITE_RECURSION = YES;
|
||||||
|
CLANG_WARN_INT_CONVERSION = YES;
|
||||||
|
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
|
||||||
|
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
|
||||||
|
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
|
||||||
|
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
|
||||||
|
CLANG_WARN_SUSPICIOUS_MOVE = YES;
|
||||||
|
CODE_SIGN_IDENTITY = "-";
|
||||||
|
COPY_PHASE_STRIP = NO;
|
||||||
|
DEAD_CODE_STRIPPING = YES;
|
||||||
|
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
|
||||||
|
ENABLE_NS_ASSERTIONS = NO;
|
||||||
|
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||||
|
ENABLE_USER_SCRIPT_SANDBOXING = NO;
|
||||||
|
GCC_C_LANGUAGE_STANDARD = gnu11;
|
||||||
|
GCC_NO_COMMON_BLOCKS = YES;
|
||||||
|
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
|
||||||
|
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
|
||||||
|
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||||
|
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||||
|
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||||
|
MACOSX_DEPLOYMENT_TARGET = 10.14;
|
||||||
|
MTL_ENABLE_DEBUG_INFO = NO;
|
||||||
|
SDKROOT = macosx;
|
||||||
|
SWIFT_COMPILATION_MODE = wholemodule;
|
||||||
|
SWIFT_OPTIMIZATION_LEVEL = "-O";
|
||||||
|
};
|
||||||
|
name = Profile;
|
||||||
|
};
|
||||||
|
338D0CEA231458BD00FA5F75 /* Profile */ = {
|
||||||
|
isa = XCBuildConfiguration;
|
||||||
|
baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */;
|
||||||
|
buildSettings = {
|
||||||
|
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||||
|
CLANG_ENABLE_MODULES = YES;
|
||||||
|
CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements;
|
||||||
|
CODE_SIGN_STYLE = Automatic;
|
||||||
|
COMBINE_HIDPI_IMAGES = YES;
|
||||||
|
INFOPLIST_FILE = Runner/Info.plist;
|
||||||
|
LD_RUNPATH_SEARCH_PATHS = (
|
||||||
|
"$(inherited)",
|
||||||
|
"@executable_path/../Frameworks",
|
||||||
|
);
|
||||||
|
PROVISIONING_PROFILE_SPECIFIER = "";
|
||||||
|
SWIFT_VERSION = 5.0;
|
||||||
|
};
|
||||||
|
name = Profile;
|
||||||
|
};
|
||||||
|
338D0CEB231458BD00FA5F75 /* Profile */ = {
|
||||||
|
isa = XCBuildConfiguration;
|
||||||
|
buildSettings = {
|
||||||
|
CODE_SIGN_STYLE = Manual;
|
||||||
|
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||||
|
};
|
||||||
|
name = Profile;
|
||||||
|
};
|
||||||
|
33CC10F92044A3C60003C045 /* Debug */ = {
|
||||||
|
isa = XCBuildConfiguration;
|
||||||
|
baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */;
|
||||||
|
buildSettings = {
|
||||||
|
ALWAYS_SEARCH_USER_PATHS = NO;
|
||||||
|
ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
|
||||||
|
CLANG_ANALYZER_NONNULL = YES;
|
||||||
|
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
|
||||||
|
CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
|
||||||
|
CLANG_CXX_LIBRARY = "libc++";
|
||||||
|
CLANG_ENABLE_MODULES = YES;
|
||||||
|
CLANG_ENABLE_OBJC_ARC = YES;
|
||||||
|
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
|
||||||
|
CLANG_WARN_BOOL_CONVERSION = YES;
|
||||||
|
CLANG_WARN_CONSTANT_CONVERSION = YES;
|
||||||
|
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
|
||||||
|
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
|
||||||
|
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
|
||||||
|
CLANG_WARN_EMPTY_BODY = YES;
|
||||||
|
CLANG_WARN_ENUM_CONVERSION = YES;
|
||||||
|
CLANG_WARN_INFINITE_RECURSION = YES;
|
||||||
|
CLANG_WARN_INT_CONVERSION = YES;
|
||||||
|
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
|
||||||
|
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
|
||||||
|
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
|
||||||
|
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
|
||||||
|
CLANG_WARN_SUSPICIOUS_MOVE = YES;
|
||||||
|
CODE_SIGN_IDENTITY = "-";
|
||||||
|
COPY_PHASE_STRIP = NO;
|
||||||
|
DEAD_CODE_STRIPPING = YES;
|
||||||
|
DEBUG_INFORMATION_FORMAT = dwarf;
|
||||||
|
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||||
|
ENABLE_TESTABILITY = YES;
|
||||||
|
ENABLE_USER_SCRIPT_SANDBOXING = NO;
|
||||||
|
GCC_C_LANGUAGE_STANDARD = gnu11;
|
||||||
|
GCC_DYNAMIC_NO_PIC = NO;
|
||||||
|
GCC_NO_COMMON_BLOCKS = YES;
|
||||||
|
GCC_OPTIMIZATION_LEVEL = 0;
|
||||||
|
GCC_PREPROCESSOR_DEFINITIONS = (
|
||||||
|
"DEBUG=1",
|
||||||
|
"$(inherited)",
|
||||||
|
);
|
||||||
|
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
|
||||||
|
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
|
||||||
|
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||||
|
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||||
|
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||||
|
MACOSX_DEPLOYMENT_TARGET = 10.14;
|
||||||
|
MTL_ENABLE_DEBUG_INFO = YES;
|
||||||
|
ONLY_ACTIVE_ARCH = YES;
|
||||||
|
SDKROOT = macosx;
|
||||||
|
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
|
||||||
|
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||||
|
};
|
||||||
|
name = Debug;
|
||||||
|
};
|
||||||
|
33CC10FA2044A3C60003C045 /* Release */ = {
|
||||||
|
isa = XCBuildConfiguration;
|
||||||
|
baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */;
|
||||||
|
buildSettings = {
|
||||||
|
ALWAYS_SEARCH_USER_PATHS = NO;
|
||||||
|
ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
|
||||||
|
CLANG_ANALYZER_NONNULL = YES;
|
||||||
|
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
|
||||||
|
CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
|
||||||
|
CLANG_CXX_LIBRARY = "libc++";
|
||||||
|
CLANG_ENABLE_MODULES = YES;
|
||||||
|
CLANG_ENABLE_OBJC_ARC = YES;
|
||||||
|
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
|
||||||
|
CLANG_WARN_BOOL_CONVERSION = YES;
|
||||||
|
CLANG_WARN_CONSTANT_CONVERSION = YES;
|
||||||
|
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
|
||||||
|
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
|
||||||
|
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
|
||||||
|
CLANG_WARN_EMPTY_BODY = YES;
|
||||||
|
CLANG_WARN_ENUM_CONVERSION = YES;
|
||||||
|
CLANG_WARN_INFINITE_RECURSION = YES;
|
||||||
|
CLANG_WARN_INT_CONVERSION = YES;
|
||||||
|
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
|
||||||
|
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
|
||||||
|
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
|
||||||
|
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
|
||||||
|
CLANG_WARN_SUSPICIOUS_MOVE = YES;
|
||||||
|
CODE_SIGN_IDENTITY = "-";
|
||||||
|
COPY_PHASE_STRIP = NO;
|
||||||
|
DEAD_CODE_STRIPPING = YES;
|
||||||
|
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
|
||||||
|
ENABLE_NS_ASSERTIONS = NO;
|
||||||
|
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||||
|
ENABLE_USER_SCRIPT_SANDBOXING = NO;
|
||||||
|
GCC_C_LANGUAGE_STANDARD = gnu11;
|
||||||
|
GCC_NO_COMMON_BLOCKS = YES;
|
||||||
|
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
|
||||||
|
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
|
||||||
|
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||||
|
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||||
|
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||||
|
MACOSX_DEPLOYMENT_TARGET = 10.14;
|
||||||
|
MTL_ENABLE_DEBUG_INFO = NO;
|
||||||
|
SDKROOT = macosx;
|
||||||
|
SWIFT_COMPILATION_MODE = wholemodule;
|
||||||
|
SWIFT_OPTIMIZATION_LEVEL = "-O";
|
||||||
|
};
|
||||||
|
name = Release;
|
||||||
|
};
|
||||||
|
33CC10FC2044A3C60003C045 /* Debug */ = {
|
||||||
|
isa = XCBuildConfiguration;
|
||||||
|
baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */;
|
||||||
|
buildSettings = {
|
||||||
|
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||||
|
CLANG_ENABLE_MODULES = YES;
|
||||||
|
CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements;
|
||||||
|
CODE_SIGN_STYLE = Automatic;
|
||||||
|
COMBINE_HIDPI_IMAGES = YES;
|
||||||
|
INFOPLIST_FILE = Runner/Info.plist;
|
||||||
|
LD_RUNPATH_SEARCH_PATHS = (
|
||||||
|
"$(inherited)",
|
||||||
|
"@executable_path/../Frameworks",
|
||||||
|
);
|
||||||
|
PROVISIONING_PROFILE_SPECIFIER = "";
|
||||||
|
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||||
|
SWIFT_VERSION = 5.0;
|
||||||
|
};
|
||||||
|
name = Debug;
|
||||||
|
};
|
||||||
|
33CC10FD2044A3C60003C045 /* Release */ = {
|
||||||
|
isa = XCBuildConfiguration;
|
||||||
|
baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */;
|
||||||
|
buildSettings = {
|
||||||
|
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||||
|
CLANG_ENABLE_MODULES = YES;
|
||||||
|
CODE_SIGN_ENTITLEMENTS = Runner/Release.entitlements;
|
||||||
|
CODE_SIGN_STYLE = Automatic;
|
||||||
|
COMBINE_HIDPI_IMAGES = YES;
|
||||||
|
INFOPLIST_FILE = Runner/Info.plist;
|
||||||
|
LD_RUNPATH_SEARCH_PATHS = (
|
||||||
|
"$(inherited)",
|
||||||
|
"@executable_path/../Frameworks",
|
||||||
|
);
|
||||||
|
PROVISIONING_PROFILE_SPECIFIER = "";
|
||||||
|
SWIFT_VERSION = 5.0;
|
||||||
|
};
|
||||||
|
name = Release;
|
||||||
|
};
|
||||||
|
33CC111C2044C6BA0003C045 /* Debug */ = {
|
||||||
|
isa = XCBuildConfiguration;
|
||||||
|
buildSettings = {
|
||||||
|
CODE_SIGN_STYLE = Manual;
|
||||||
|
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||||
|
};
|
||||||
|
name = Debug;
|
||||||
|
};
|
||||||
|
33CC111D2044C6BA0003C045 /* Release */ = {
|
||||||
|
isa = XCBuildConfiguration;
|
||||||
|
buildSettings = {
|
||||||
|
CODE_SIGN_STYLE = Automatic;
|
||||||
|
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||||
|
};
|
||||||
|
name = Release;
|
||||||
|
};
|
||||||
|
/* End XCBuildConfiguration section */
|
||||||
|
|
||||||
|
/* Begin XCConfigurationList section */
|
||||||
|
331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = {
|
||||||
|
isa = XCConfigurationList;
|
||||||
|
buildConfigurations = (
|
||||||
|
331C80DB294CF71000263BE5 /* Debug */,
|
||||||
|
331C80DC294CF71000263BE5 /* Release */,
|
||||||
|
331C80DD294CF71000263BE5 /* Profile */,
|
||||||
|
);
|
||||||
|
defaultConfigurationIsVisible = 0;
|
||||||
|
defaultConfigurationName = Release;
|
||||||
|
};
|
||||||
|
33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */ = {
|
||||||
|
isa = XCConfigurationList;
|
||||||
|
buildConfigurations = (
|
||||||
|
33CC10F92044A3C60003C045 /* Debug */,
|
||||||
|
33CC10FA2044A3C60003C045 /* Release */,
|
||||||
|
338D0CE9231458BD00FA5F75 /* Profile */,
|
||||||
|
);
|
||||||
|
defaultConfigurationIsVisible = 0;
|
||||||
|
defaultConfigurationName = Release;
|
||||||
|
};
|
||||||
|
33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */ = {
|
||||||
|
isa = XCConfigurationList;
|
||||||
|
buildConfigurations = (
|
||||||
|
33CC10FC2044A3C60003C045 /* Debug */,
|
||||||
|
33CC10FD2044A3C60003C045 /* Release */,
|
||||||
|
338D0CEA231458BD00FA5F75 /* Profile */,
|
||||||
|
);
|
||||||
|
defaultConfigurationIsVisible = 0;
|
||||||
|
defaultConfigurationName = Release;
|
||||||
|
};
|
||||||
|
33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */ = {
|
||||||
|
isa = XCConfigurationList;
|
||||||
|
buildConfigurations = (
|
||||||
|
33CC111C2044C6BA0003C045 /* Debug */,
|
||||||
|
33CC111D2044C6BA0003C045 /* Release */,
|
||||||
|
338D0CEB231458BD00FA5F75 /* Profile */,
|
||||||
|
);
|
||||||
|
defaultConfigurationIsVisible = 0;
|
||||||
|
defaultConfigurationName = Release;
|
||||||
|
};
|
||||||
|
/* End XCConfigurationList section */
|
||||||
|
};
|
||||||
|
rootObject = 33CC10E52044A3C60003C045 /* Project object */;
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
<?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>IDEDidComputeMac32BitWarning</key>
|
||||||
|
<true/>
|
||||||
|
</dict>
|
||||||
|
</plist>
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<Scheme
|
||||||
|
LastUpgradeVersion = "1510"
|
||||||
|
version = "1.3">
|
||||||
|
<BuildAction
|
||||||
|
parallelizeBuildables = "YES"
|
||||||
|
buildImplicitDependencies = "YES">
|
||||||
|
<BuildActionEntries>
|
||||||
|
<BuildActionEntry
|
||||||
|
buildForTesting = "YES"
|
||||||
|
buildForRunning = "YES"
|
||||||
|
buildForProfiling = "YES"
|
||||||
|
buildForArchiving = "YES"
|
||||||
|
buildForAnalyzing = "YES">
|
||||||
|
<BuildableReference
|
||||||
|
BuildableIdentifier = "primary"
|
||||||
|
BlueprintIdentifier = "33CC10EC2044A3C60003C045"
|
||||||
|
BuildableName = "gc_ui.app"
|
||||||
|
BlueprintName = "Runner"
|
||||||
|
ReferencedContainer = "container:Runner.xcodeproj">
|
||||||
|
</BuildableReference>
|
||||||
|
</BuildActionEntry>
|
||||||
|
</BuildActionEntries>
|
||||||
|
</BuildAction>
|
||||||
|
<TestAction
|
||||||
|
buildConfiguration = "Debug"
|
||||||
|
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||||
|
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||||
|
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||||
|
<MacroExpansion>
|
||||||
|
<BuildableReference
|
||||||
|
BuildableIdentifier = "primary"
|
||||||
|
BlueprintIdentifier = "33CC10EC2044A3C60003C045"
|
||||||
|
BuildableName = "gc_ui.app"
|
||||||
|
BlueprintName = "Runner"
|
||||||
|
ReferencedContainer = "container:Runner.xcodeproj">
|
||||||
|
</BuildableReference>
|
||||||
|
</MacroExpansion>
|
||||||
|
<Testables>
|
||||||
|
<TestableReference
|
||||||
|
skipped = "NO"
|
||||||
|
parallelizable = "YES">
|
||||||
|
<BuildableReference
|
||||||
|
BuildableIdentifier = "primary"
|
||||||
|
BlueprintIdentifier = "331C80D4294CF70F00263BE5"
|
||||||
|
BuildableName = "RunnerTests.xctest"
|
||||||
|
BlueprintName = "RunnerTests"
|
||||||
|
ReferencedContainer = "container:Runner.xcodeproj">
|
||||||
|
</BuildableReference>
|
||||||
|
</TestableReference>
|
||||||
|
</Testables>
|
||||||
|
</TestAction>
|
||||||
|
<LaunchAction
|
||||||
|
buildConfiguration = "Debug"
|
||||||
|
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||||
|
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||||
|
launchStyle = "0"
|
||||||
|
useCustomWorkingDirectory = "NO"
|
||||||
|
ignoresPersistentStateOnLaunch = "NO"
|
||||||
|
debugDocumentVersioning = "YES"
|
||||||
|
debugServiceExtension = "internal"
|
||||||
|
allowLocationSimulation = "YES">
|
||||||
|
<BuildableProductRunnable
|
||||||
|
runnableDebuggingMode = "0">
|
||||||
|
<BuildableReference
|
||||||
|
BuildableIdentifier = "primary"
|
||||||
|
BlueprintIdentifier = "33CC10EC2044A3C60003C045"
|
||||||
|
BuildableName = "gc_ui.app"
|
||||||
|
BlueprintName = "Runner"
|
||||||
|
ReferencedContainer = "container:Runner.xcodeproj">
|
||||||
|
</BuildableReference>
|
||||||
|
</BuildableProductRunnable>
|
||||||
|
</LaunchAction>
|
||||||
|
<ProfileAction
|
||||||
|
buildConfiguration = "Profile"
|
||||||
|
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||||
|
savedToolIdentifier = ""
|
||||||
|
useCustomWorkingDirectory = "NO"
|
||||||
|
debugDocumentVersioning = "YES">
|
||||||
|
<BuildableProductRunnable
|
||||||
|
runnableDebuggingMode = "0">
|
||||||
|
<BuildableReference
|
||||||
|
BuildableIdentifier = "primary"
|
||||||
|
BlueprintIdentifier = "33CC10EC2044A3C60003C045"
|
||||||
|
BuildableName = "gc_ui.app"
|
||||||
|
BlueprintName = "Runner"
|
||||||
|
ReferencedContainer = "container:Runner.xcodeproj">
|
||||||
|
</BuildableReference>
|
||||||
|
</BuildableProductRunnable>
|
||||||
|
</ProfileAction>
|
||||||
|
<AnalyzeAction
|
||||||
|
buildConfiguration = "Debug">
|
||||||
|
</AnalyzeAction>
|
||||||
|
<ArchiveAction
|
||||||
|
buildConfiguration = "Release"
|
||||||
|
revealArchiveInOrganizer = "YES">
|
||||||
|
</ArchiveAction>
|
||||||
|
</Scheme>
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<Workspace
|
||||||
|
version = "1.0">
|
||||||
|
<FileRef
|
||||||
|
location = "group:Runner.xcodeproj">
|
||||||
|
</FileRef>
|
||||||
|
</Workspace>
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
<?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>IDEDidComputeMac32BitWarning</key>
|
||||||
|
<true/>
|
||||||
|
</dict>
|
||||||
|
</plist>
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import Cocoa
|
||||||
|
import FlutterMacOS
|
||||||
|
|
||||||
|
@main
|
||||||
|
class AppDelegate: FlutterAppDelegate {
|
||||||
|
override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
{
|
||||||
|
"images" : [
|
||||||
|
{
|
||||||
|
"size" : "16x16",
|
||||||
|
"idiom" : "mac",
|
||||||
|
"filename" : "app_icon_16.png",
|
||||||
|
"scale" : "1x"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"size" : "16x16",
|
||||||
|
"idiom" : "mac",
|
||||||
|
"filename" : "app_icon_32.png",
|
||||||
|
"scale" : "2x"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"size" : "32x32",
|
||||||
|
"idiom" : "mac",
|
||||||
|
"filename" : "app_icon_32.png",
|
||||||
|
"scale" : "1x"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"size" : "32x32",
|
||||||
|
"idiom" : "mac",
|
||||||
|
"filename" : "app_icon_64.png",
|
||||||
|
"scale" : "2x"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"size" : "128x128",
|
||||||
|
"idiom" : "mac",
|
||||||
|
"filename" : "app_icon_128.png",
|
||||||
|
"scale" : "1x"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"size" : "128x128",
|
||||||
|
"idiom" : "mac",
|
||||||
|
"filename" : "app_icon_256.png",
|
||||||
|
"scale" : "2x"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"size" : "256x256",
|
||||||
|
"idiom" : "mac",
|
||||||
|
"filename" : "app_icon_256.png",
|
||||||
|
"scale" : "1x"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"size" : "256x256",
|
||||||
|
"idiom" : "mac",
|
||||||
|
"filename" : "app_icon_512.png",
|
||||||
|
"scale" : "2x"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"size" : "512x512",
|
||||||
|
"idiom" : "mac",
|
||||||
|
"filename" : "app_icon_512.png",
|
||||||
|
"scale" : "1x"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"size" : "512x512",
|
||||||
|
"idiom" : "mac",
|
||||||
|
"filename" : "app_icon_1024.png",
|
||||||
|
"scale" : "2x"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"info" : {
|
||||||
|
"version" : 1,
|
||||||
|
"author" : "xcode"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
After Width: | Height: | Size: 101 KiB |
|
After Width: | Height: | Size: 5.5 KiB |
|
After Width: | Height: | Size: 520 B |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 1.0 KiB |
|
After Width: | Height: | Size: 36 KiB |
|
After Width: | Height: | Size: 2.2 KiB |
@@ -0,0 +1,343 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="14490.70" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES" customObjectInstantitationMethod="direct">
|
||||||
|
<dependencies>
|
||||||
|
<deployment identifier="macosx"/>
|
||||||
|
<plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="14490.70"/>
|
||||||
|
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
|
||||||
|
</dependencies>
|
||||||
|
<objects>
|
||||||
|
<customObject id="-2" userLabel="File's Owner" customClass="NSApplication">
|
||||||
|
<connections>
|
||||||
|
<outlet property="delegate" destination="Voe-Tx-rLC" id="GzC-gU-4Uq"/>
|
||||||
|
</connections>
|
||||||
|
</customObject>
|
||||||
|
<customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/>
|
||||||
|
<customObject id="-3" userLabel="Application" customClass="NSObject"/>
|
||||||
|
<customObject id="Voe-Tx-rLC" customClass="AppDelegate" customModule="Runner" customModuleProvider="target">
|
||||||
|
<connections>
|
||||||
|
<outlet property="applicationMenu" destination="uQy-DD-JDr" id="XBo-yE-nKs"/>
|
||||||
|
<outlet property="mainFlutterWindow" destination="QvC-M9-y7g" id="gIp-Ho-8D9"/>
|
||||||
|
</connections>
|
||||||
|
</customObject>
|
||||||
|
<customObject id="YLy-65-1bz" customClass="NSFontManager"/>
|
||||||
|
<menu title="Main Menu" systemMenu="main" id="AYu-sK-qS6">
|
||||||
|
<items>
|
||||||
|
<menuItem title="APP_NAME" id="1Xt-HY-uBw">
|
||||||
|
<modifierMask key="keyEquivalentModifierMask"/>
|
||||||
|
<menu key="submenu" title="APP_NAME" systemMenu="apple" id="uQy-DD-JDr">
|
||||||
|
<items>
|
||||||
|
<menuItem title="About APP_NAME" id="5kV-Vb-QxS">
|
||||||
|
<modifierMask key="keyEquivalentModifierMask"/>
|
||||||
|
<connections>
|
||||||
|
<action selector="orderFrontStandardAboutPanel:" target="-1" id="Exp-CZ-Vem"/>
|
||||||
|
</connections>
|
||||||
|
</menuItem>
|
||||||
|
<menuItem isSeparatorItem="YES" id="VOq-y0-SEH"/>
|
||||||
|
<menuItem title="Preferences…" keyEquivalent="," id="BOF-NM-1cW"/>
|
||||||
|
<menuItem isSeparatorItem="YES" id="wFC-TO-SCJ"/>
|
||||||
|
<menuItem title="Services" id="NMo-om-nkz">
|
||||||
|
<modifierMask key="keyEquivalentModifierMask"/>
|
||||||
|
<menu key="submenu" title="Services" systemMenu="services" id="hz9-B4-Xy5"/>
|
||||||
|
</menuItem>
|
||||||
|
<menuItem isSeparatorItem="YES" id="4je-JR-u6R"/>
|
||||||
|
<menuItem title="Hide APP_NAME" keyEquivalent="h" id="Olw-nP-bQN">
|
||||||
|
<connections>
|
||||||
|
<action selector="hide:" target="-1" id="PnN-Uc-m68"/>
|
||||||
|
</connections>
|
||||||
|
</menuItem>
|
||||||
|
<menuItem title="Hide Others" keyEquivalent="h" id="Vdr-fp-XzO">
|
||||||
|
<modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/>
|
||||||
|
<connections>
|
||||||
|
<action selector="hideOtherApplications:" target="-1" id="VT4-aY-XCT"/>
|
||||||
|
</connections>
|
||||||
|
</menuItem>
|
||||||
|
<menuItem title="Show All" id="Kd2-mp-pUS">
|
||||||
|
<modifierMask key="keyEquivalentModifierMask"/>
|
||||||
|
<connections>
|
||||||
|
<action selector="unhideAllApplications:" target="-1" id="Dhg-Le-xox"/>
|
||||||
|
</connections>
|
||||||
|
</menuItem>
|
||||||
|
<menuItem isSeparatorItem="YES" id="kCx-OE-vgT"/>
|
||||||
|
<menuItem title="Quit APP_NAME" keyEquivalent="q" id="4sb-4s-VLi">
|
||||||
|
<connections>
|
||||||
|
<action selector="terminate:" target="-1" id="Te7-pn-YzF"/>
|
||||||
|
</connections>
|
||||||
|
</menuItem>
|
||||||
|
</items>
|
||||||
|
</menu>
|
||||||
|
</menuItem>
|
||||||
|
<menuItem title="Edit" id="5QF-Oa-p0T">
|
||||||
|
<modifierMask key="keyEquivalentModifierMask"/>
|
||||||
|
<menu key="submenu" title="Edit" id="W48-6f-4Dl">
|
||||||
|
<items>
|
||||||
|
<menuItem title="Undo" keyEquivalent="z" id="dRJ-4n-Yzg">
|
||||||
|
<connections>
|
||||||
|
<action selector="undo:" target="-1" id="M6e-cu-g7V"/>
|
||||||
|
</connections>
|
||||||
|
</menuItem>
|
||||||
|
<menuItem title="Redo" keyEquivalent="Z" id="6dh-zS-Vam">
|
||||||
|
<connections>
|
||||||
|
<action selector="redo:" target="-1" id="oIA-Rs-6OD"/>
|
||||||
|
</connections>
|
||||||
|
</menuItem>
|
||||||
|
<menuItem isSeparatorItem="YES" id="WRV-NI-Exz"/>
|
||||||
|
<menuItem title="Cut" keyEquivalent="x" id="uRl-iY-unG">
|
||||||
|
<connections>
|
||||||
|
<action selector="cut:" target="-1" id="YJe-68-I9s"/>
|
||||||
|
</connections>
|
||||||
|
</menuItem>
|
||||||
|
<menuItem title="Copy" keyEquivalent="c" id="x3v-GG-iWU">
|
||||||
|
<connections>
|
||||||
|
<action selector="copy:" target="-1" id="G1f-GL-Joy"/>
|
||||||
|
</connections>
|
||||||
|
</menuItem>
|
||||||
|
<menuItem title="Paste" keyEquivalent="v" id="gVA-U4-sdL">
|
||||||
|
<connections>
|
||||||
|
<action selector="paste:" target="-1" id="UvS-8e-Qdg"/>
|
||||||
|
</connections>
|
||||||
|
</menuItem>
|
||||||
|
<menuItem title="Paste and Match Style" keyEquivalent="V" id="WeT-3V-zwk">
|
||||||
|
<modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/>
|
||||||
|
<connections>
|
||||||
|
<action selector="pasteAsPlainText:" target="-1" id="cEh-KX-wJQ"/>
|
||||||
|
</connections>
|
||||||
|
</menuItem>
|
||||||
|
<menuItem title="Delete" id="pa3-QI-u2k">
|
||||||
|
<modifierMask key="keyEquivalentModifierMask"/>
|
||||||
|
<connections>
|
||||||
|
<action selector="delete:" target="-1" id="0Mk-Ml-PaM"/>
|
||||||
|
</connections>
|
||||||
|
</menuItem>
|
||||||
|
<menuItem title="Select All" keyEquivalent="a" id="Ruw-6m-B2m">
|
||||||
|
<connections>
|
||||||
|
<action selector="selectAll:" target="-1" id="VNm-Mi-diN"/>
|
||||||
|
</connections>
|
||||||
|
</menuItem>
|
||||||
|
<menuItem isSeparatorItem="YES" id="uyl-h8-XO2"/>
|
||||||
|
<menuItem title="Find" id="4EN-yA-p0u">
|
||||||
|
<modifierMask key="keyEquivalentModifierMask"/>
|
||||||
|
<menu key="submenu" title="Find" id="1b7-l0-nxx">
|
||||||
|
<items>
|
||||||
|
<menuItem title="Find…" tag="1" keyEquivalent="f" id="Xz5-n4-O0W">
|
||||||
|
<connections>
|
||||||
|
<action selector="performFindPanelAction:" target="-1" id="cD7-Qs-BN4"/>
|
||||||
|
</connections>
|
||||||
|
</menuItem>
|
||||||
|
<menuItem title="Find and Replace…" tag="12" keyEquivalent="f" id="YEy-JH-Tfz">
|
||||||
|
<modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/>
|
||||||
|
<connections>
|
||||||
|
<action selector="performFindPanelAction:" target="-1" id="WD3-Gg-5AJ"/>
|
||||||
|
</connections>
|
||||||
|
</menuItem>
|
||||||
|
<menuItem title="Find Next" tag="2" keyEquivalent="g" id="q09-fT-Sye">
|
||||||
|
<connections>
|
||||||
|
<action selector="performFindPanelAction:" target="-1" id="NDo-RZ-v9R"/>
|
||||||
|
</connections>
|
||||||
|
</menuItem>
|
||||||
|
<menuItem title="Find Previous" tag="3" keyEquivalent="G" id="OwM-mh-QMV">
|
||||||
|
<connections>
|
||||||
|
<action selector="performFindPanelAction:" target="-1" id="HOh-sY-3ay"/>
|
||||||
|
</connections>
|
||||||
|
</menuItem>
|
||||||
|
<menuItem title="Use Selection for Find" tag="7" keyEquivalent="e" id="buJ-ug-pKt">
|
||||||
|
<connections>
|
||||||
|
<action selector="performFindPanelAction:" target="-1" id="U76-nv-p5D"/>
|
||||||
|
</connections>
|
||||||
|
</menuItem>
|
||||||
|
<menuItem title="Jump to Selection" keyEquivalent="j" id="S0p-oC-mLd">
|
||||||
|
<connections>
|
||||||
|
<action selector="centerSelectionInVisibleArea:" target="-1" id="IOG-6D-g5B"/>
|
||||||
|
</connections>
|
||||||
|
</menuItem>
|
||||||
|
</items>
|
||||||
|
</menu>
|
||||||
|
</menuItem>
|
||||||
|
<menuItem title="Spelling and Grammar" id="Dv1-io-Yv7">
|
||||||
|
<modifierMask key="keyEquivalentModifierMask"/>
|
||||||
|
<menu key="submenu" title="Spelling" id="3IN-sU-3Bg">
|
||||||
|
<items>
|
||||||
|
<menuItem title="Show Spelling and Grammar" keyEquivalent=":" id="HFo-cy-zxI">
|
||||||
|
<connections>
|
||||||
|
<action selector="showGuessPanel:" target="-1" id="vFj-Ks-hy3"/>
|
||||||
|
</connections>
|
||||||
|
</menuItem>
|
||||||
|
<menuItem title="Check Document Now" keyEquivalent=";" id="hz2-CU-CR7">
|
||||||
|
<connections>
|
||||||
|
<action selector="checkSpelling:" target="-1" id="fz7-VC-reM"/>
|
||||||
|
</connections>
|
||||||
|
</menuItem>
|
||||||
|
<menuItem isSeparatorItem="YES" id="bNw-od-mp5"/>
|
||||||
|
<menuItem title="Check Spelling While Typing" id="rbD-Rh-wIN">
|
||||||
|
<modifierMask key="keyEquivalentModifierMask"/>
|
||||||
|
<connections>
|
||||||
|
<action selector="toggleContinuousSpellChecking:" target="-1" id="7w6-Qz-0kB"/>
|
||||||
|
</connections>
|
||||||
|
</menuItem>
|
||||||
|
<menuItem title="Check Grammar With Spelling" id="mK6-2p-4JG">
|
||||||
|
<modifierMask key="keyEquivalentModifierMask"/>
|
||||||
|
<connections>
|
||||||
|
<action selector="toggleGrammarChecking:" target="-1" id="muD-Qn-j4w"/>
|
||||||
|
</connections>
|
||||||
|
</menuItem>
|
||||||
|
<menuItem title="Correct Spelling Automatically" id="78Y-hA-62v">
|
||||||
|
<modifierMask key="keyEquivalentModifierMask"/>
|
||||||
|
<connections>
|
||||||
|
<action selector="toggleAutomaticSpellingCorrection:" target="-1" id="2lM-Qi-WAP"/>
|
||||||
|
</connections>
|
||||||
|
</menuItem>
|
||||||
|
</items>
|
||||||
|
</menu>
|
||||||
|
</menuItem>
|
||||||
|
<menuItem title="Substitutions" id="9ic-FL-obx">
|
||||||
|
<modifierMask key="keyEquivalentModifierMask"/>
|
||||||
|
<menu key="submenu" title="Substitutions" id="FeM-D8-WVr">
|
||||||
|
<items>
|
||||||
|
<menuItem title="Show Substitutions" id="z6F-FW-3nz">
|
||||||
|
<modifierMask key="keyEquivalentModifierMask"/>
|
||||||
|
<connections>
|
||||||
|
<action selector="orderFrontSubstitutionsPanel:" target="-1" id="oku-mr-iSq"/>
|
||||||
|
</connections>
|
||||||
|
</menuItem>
|
||||||
|
<menuItem isSeparatorItem="YES" id="gPx-C9-uUO"/>
|
||||||
|
<menuItem title="Smart Copy/Paste" id="9yt-4B-nSM">
|
||||||
|
<modifierMask key="keyEquivalentModifierMask"/>
|
||||||
|
<connections>
|
||||||
|
<action selector="toggleSmartInsertDelete:" target="-1" id="3IJ-Se-DZD"/>
|
||||||
|
</connections>
|
||||||
|
</menuItem>
|
||||||
|
<menuItem title="Smart Quotes" id="hQb-2v-fYv">
|
||||||
|
<modifierMask key="keyEquivalentModifierMask"/>
|
||||||
|
<connections>
|
||||||
|
<action selector="toggleAutomaticQuoteSubstitution:" target="-1" id="ptq-xd-QOA"/>
|
||||||
|
</connections>
|
||||||
|
</menuItem>
|
||||||
|
<menuItem title="Smart Dashes" id="rgM-f4-ycn">
|
||||||
|
<modifierMask key="keyEquivalentModifierMask"/>
|
||||||
|
<connections>
|
||||||
|
<action selector="toggleAutomaticDashSubstitution:" target="-1" id="oCt-pO-9gS"/>
|
||||||
|
</connections>
|
||||||
|
</menuItem>
|
||||||
|
<menuItem title="Smart Links" id="cwL-P1-jid">
|
||||||
|
<modifierMask key="keyEquivalentModifierMask"/>
|
||||||
|
<connections>
|
||||||
|
<action selector="toggleAutomaticLinkDetection:" target="-1" id="Gip-E3-Fov"/>
|
||||||
|
</connections>
|
||||||
|
</menuItem>
|
||||||
|
<menuItem title="Data Detectors" id="tRr-pd-1PS">
|
||||||
|
<modifierMask key="keyEquivalentModifierMask"/>
|
||||||
|
<connections>
|
||||||
|
<action selector="toggleAutomaticDataDetection:" target="-1" id="R1I-Nq-Kbl"/>
|
||||||
|
</connections>
|
||||||
|
</menuItem>
|
||||||
|
<menuItem title="Text Replacement" id="HFQ-gK-NFA">
|
||||||
|
<modifierMask key="keyEquivalentModifierMask"/>
|
||||||
|
<connections>
|
||||||
|
<action selector="toggleAutomaticTextReplacement:" target="-1" id="DvP-Fe-Py6"/>
|
||||||
|
</connections>
|
||||||
|
</menuItem>
|
||||||
|
</items>
|
||||||
|
</menu>
|
||||||
|
</menuItem>
|
||||||
|
<menuItem title="Transformations" id="2oI-Rn-ZJC">
|
||||||
|
<modifierMask key="keyEquivalentModifierMask"/>
|
||||||
|
<menu key="submenu" title="Transformations" id="c8a-y6-VQd">
|
||||||
|
<items>
|
||||||
|
<menuItem title="Make Upper Case" id="vmV-6d-7jI">
|
||||||
|
<modifierMask key="keyEquivalentModifierMask"/>
|
||||||
|
<connections>
|
||||||
|
<action selector="uppercaseWord:" target="-1" id="sPh-Tk-edu"/>
|
||||||
|
</connections>
|
||||||
|
</menuItem>
|
||||||
|
<menuItem title="Make Lower Case" id="d9M-CD-aMd">
|
||||||
|
<modifierMask key="keyEquivalentModifierMask"/>
|
||||||
|
<connections>
|
||||||
|
<action selector="lowercaseWord:" target="-1" id="iUZ-b5-hil"/>
|
||||||
|
</connections>
|
||||||
|
</menuItem>
|
||||||
|
<menuItem title="Capitalize" id="UEZ-Bs-lqG">
|
||||||
|
<modifierMask key="keyEquivalentModifierMask"/>
|
||||||
|
<connections>
|
||||||
|
<action selector="capitalizeWord:" target="-1" id="26H-TL-nsh"/>
|
||||||
|
</connections>
|
||||||
|
</menuItem>
|
||||||
|
</items>
|
||||||
|
</menu>
|
||||||
|
</menuItem>
|
||||||
|
<menuItem title="Speech" id="xrE-MZ-jX0">
|
||||||
|
<modifierMask key="keyEquivalentModifierMask"/>
|
||||||
|
<menu key="submenu" title="Speech" id="3rS-ZA-NoH">
|
||||||
|
<items>
|
||||||
|
<menuItem title="Start Speaking" id="Ynk-f8-cLZ">
|
||||||
|
<modifierMask key="keyEquivalentModifierMask"/>
|
||||||
|
<connections>
|
||||||
|
<action selector="startSpeaking:" target="-1" id="654-Ng-kyl"/>
|
||||||
|
</connections>
|
||||||
|
</menuItem>
|
||||||
|
<menuItem title="Stop Speaking" id="Oyz-dy-DGm">
|
||||||
|
<modifierMask key="keyEquivalentModifierMask"/>
|
||||||
|
<connections>
|
||||||
|
<action selector="stopSpeaking:" target="-1" id="dX8-6p-jy9"/>
|
||||||
|
</connections>
|
||||||
|
</menuItem>
|
||||||
|
</items>
|
||||||
|
</menu>
|
||||||
|
</menuItem>
|
||||||
|
</items>
|
||||||
|
</menu>
|
||||||
|
</menuItem>
|
||||||
|
<menuItem title="View" id="H8h-7b-M4v">
|
||||||
|
<modifierMask key="keyEquivalentModifierMask"/>
|
||||||
|
<menu key="submenu" title="View" id="HyV-fh-RgO">
|
||||||
|
<items>
|
||||||
|
<menuItem title="Enter Full Screen" keyEquivalent="f" id="4J7-dP-txa">
|
||||||
|
<modifierMask key="keyEquivalentModifierMask" control="YES" command="YES"/>
|
||||||
|
<connections>
|
||||||
|
<action selector="toggleFullScreen:" target="-1" id="dU3-MA-1Rq"/>
|
||||||
|
</connections>
|
||||||
|
</menuItem>
|
||||||
|
</items>
|
||||||
|
</menu>
|
||||||
|
</menuItem>
|
||||||
|
<menuItem title="Window" id="aUF-d1-5bR">
|
||||||
|
<modifierMask key="keyEquivalentModifierMask"/>
|
||||||
|
<menu key="submenu" title="Window" systemMenu="window" id="Td7-aD-5lo">
|
||||||
|
<items>
|
||||||
|
<menuItem title="Minimize" keyEquivalent="m" id="OY7-WF-poV">
|
||||||
|
<connections>
|
||||||
|
<action selector="performMiniaturize:" target="-1" id="VwT-WD-YPe"/>
|
||||||
|
</connections>
|
||||||
|
</menuItem>
|
||||||
|
<menuItem title="Zoom" id="R4o-n2-Eq4">
|
||||||
|
<modifierMask key="keyEquivalentModifierMask"/>
|
||||||
|
<connections>
|
||||||
|
<action selector="performZoom:" target="-1" id="DIl-cC-cCs"/>
|
||||||
|
</connections>
|
||||||
|
</menuItem>
|
||||||
|
<menuItem isSeparatorItem="YES" id="eu3-7i-yIM"/>
|
||||||
|
<menuItem title="Bring All to Front" id="LE2-aR-0XJ">
|
||||||
|
<modifierMask key="keyEquivalentModifierMask"/>
|
||||||
|
<connections>
|
||||||
|
<action selector="arrangeInFront:" target="-1" id="DRN-fu-gQh"/>
|
||||||
|
</connections>
|
||||||
|
</menuItem>
|
||||||
|
</items>
|
||||||
|
</menu>
|
||||||
|
</menuItem>
|
||||||
|
<menuItem title="Help" id="EPT-qC-fAb">
|
||||||
|
<modifierMask key="keyEquivalentModifierMask"/>
|
||||||
|
<menu key="submenu" title="Help" systemMenu="help" id="rJ0-wn-3NY"/>
|
||||||
|
</menuItem>
|
||||||
|
</items>
|
||||||
|
<point key="canvasLocation" x="142" y="-258"/>
|
||||||
|
</menu>
|
||||||
|
<window title="APP_NAME" allowsToolTipsWhenApplicationIsInactive="NO" autorecalculatesKeyViewLoop="NO" releasedWhenClosed="NO" animationBehavior="default" id="QvC-M9-y7g" customClass="MainFlutterWindow" customModule="Runner" customModuleProvider="target">
|
||||||
|
<windowStyleMask key="styleMask" titled="YES" closable="YES" miniaturizable="YES" resizable="YES"/>
|
||||||
|
<rect key="contentRect" x="335" y="390" width="800" height="600"/>
|
||||||
|
<rect key="screenRect" x="0.0" y="0.0" width="2560" height="1577"/>
|
||||||
|
<view key="contentView" wantsLayer="YES" id="EiT-Mj-1SZ">
|
||||||
|
<rect key="frame" x="0.0" y="0.0" width="800" height="600"/>
|
||||||
|
<autoresizingMask key="autoresizingMask"/>
|
||||||
|
</view>
|
||||||
|
</window>
|
||||||
|
</objects>
|
||||||
|
</document>
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
// Application-level settings for the Runner target.
|
||||||
|
//
|
||||||
|
// This may be replaced with something auto-generated from metadata (e.g., pubspec.yaml) in the
|
||||||
|
// future. If not, the values below would default to using the project name when this becomes a
|
||||||
|
// 'flutter create' template.
|
||||||
|
|
||||||
|
// The application's name. By default this is also the title of the Flutter window.
|
||||||
|
PRODUCT_NAME = GC-UI
|
||||||
|
|
||||||
|
// The application's bundle identifier
|
||||||
|
PRODUCT_BUNDLE_IDENTIFIER = com.morris.gc.gcUi
|
||||||
|
|
||||||
|
// The copyright displayed in application information
|
||||||
|
PRODUCT_COPYRIGHT = Copyright © 2026 Morris. All rights reserved.
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
#include "../../Flutter/Flutter-Debug.xcconfig"
|
||||||
|
#include "Warnings.xcconfig"
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
#include "../../Flutter/Flutter-Release.xcconfig"
|
||||||
|
#include "Warnings.xcconfig"
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
WARNING_CFLAGS = -Wall -Wconditional-uninitialized -Wnullable-to-nonnull-conversion -Wmissing-method-return-type -Woverlength-strings
|
||||||
|
GCC_WARN_UNDECLARED_SELECTOR = YES
|
||||||
|
CLANG_UNDEFINED_BEHAVIOR_SANITIZER_NULLABILITY = YES
|
||||||
|
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE
|
||||||
|
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES
|
||||||
|
CLANG_WARN_PRAGMA_PACK = YES
|
||||||
|
CLANG_WARN_STRICT_PROTOTYPES = YES
|
||||||
|
CLANG_WARN_COMMA = YES
|
||||||
|
GCC_WARN_STRICT_SELECTOR_MATCH = YES
|
||||||
|
CLANG_WARN_OBJC_REPEATED_USE_OF_WEAK = YES
|
||||||
|
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES
|
||||||
|
GCC_WARN_SHADOW = YES
|
||||||
|
CLANG_WARN_UNREACHABLE_CODE = YES
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
<?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>com.apple.security.app-sandbox</key>
|
||||||
|
<true/>
|
||||||
|
<key>com.apple.security.cs.allow-jit</key>
|
||||||
|
<true/>
|
||||||
|
<key>com.apple.security.network.server</key>
|
||||||
|
<true/>
|
||||||
|
</dict>
|
||||||
|
</plist>
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
<?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>CFBundleDevelopmentRegion</key>
|
||||||
|
<string>$(DEVELOPMENT_LANGUAGE)</string>
|
||||||
|
<key>CFBundleExecutable</key>
|
||||||
|
<string>$(EXECUTABLE_NAME)</string>
|
||||||
|
<key>CFBundleIconFile</key>
|
||||||
|
<string></string>
|
||||||
|
<key>CFBundleIdentifier</key>
|
||||||
|
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
||||||
|
<key>CFBundleInfoDictionaryVersion</key>
|
||||||
|
<string>6.0</string>
|
||||||
|
<key>CFBundleName</key>
|
||||||
|
<string>$(PRODUCT_NAME)</string>
|
||||||
|
<key>CFBundlePackageType</key>
|
||||||
|
<string>APPL</string>
|
||||||
|
<key>CFBundleShortVersionString</key>
|
||||||
|
<string>$(FLUTTER_BUILD_NAME)</string>
|
||||||
|
<key>CFBundleVersion</key>
|
||||||
|
<string>$(FLUTTER_BUILD_NUMBER)</string>
|
||||||
|
<key>LSMinimumSystemVersion</key>
|
||||||
|
<string>$(MACOSX_DEPLOYMENT_TARGET)</string>
|
||||||
|
<key>NSHumanReadableCopyright</key>
|
||||||
|
<string>$(PRODUCT_COPYRIGHT)</string>
|
||||||
|
<key>NSMainNibFile</key>
|
||||||
|
<string>MainMenu</string>
|
||||||
|
<key>NSPrincipalClass</key>
|
||||||
|
<string>NSApplication</string>
|
||||||
|
</dict>
|
||||||
|
</plist>
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
import Cocoa
|
||||||
|
import FlutterMacOS
|
||||||
|
|
||||||
|
class MainFlutterWindow: NSWindow {
|
||||||
|
override func awakeFromNib() {
|
||||||
|
let flutterViewController = FlutterViewController()
|
||||||
|
let windowFrame = self.frame
|
||||||
|
self.contentViewController = flutterViewController
|
||||||
|
self.setFrame(windowFrame, display: true)
|
||||||
|
|
||||||
|
RegisterGeneratedPlugins(registry: flutterViewController)
|
||||||
|
|
||||||
|
super.awakeFromNib()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
<?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>com.apple.security.app-sandbox</key>
|
||||||
|
<true/>
|
||||||
|
</dict>
|
||||||
|
</plist>
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
import Cocoa
|
||||||
|
import FlutterMacOS
|
||||||
|
import XCTest
|
||||||
|
|
||||||
|
class RunnerTests: XCTestCase {
|
||||||
|
|
||||||
|
func testExample() {
|
||||||
|
// If you add code to the Runner application, consider adding tests here.
|
||||||
|
// See https://developer.apple.com/documentation/xctest for more information about using XCTest.
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,245 @@
|
|||||||
|
# Generated by pub
|
||||||
|
# See https://dart.dev/tools/pub/glossary#lockfile
|
||||||
|
packages:
|
||||||
|
async:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: async
|
||||||
|
sha256: "947bfcf187f74dbc5e146c9eb9c0f10c9f8b30743e341481c1e2ed3ecc18c20c"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "2.11.0"
|
||||||
|
boolean_selector:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: boolean_selector
|
||||||
|
sha256: "6cfb5af12253eaf2b368f07bacc5a80d1301a071c73360d746b7f2e32d762c66"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "2.1.1"
|
||||||
|
characters:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: characters
|
||||||
|
sha256: "04a925763edad70e8443c99234dc3328f442e811f1d8fd1a72f1c8ad0f69a605"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "1.3.0"
|
||||||
|
clock:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: clock
|
||||||
|
sha256: cb6d7f03e1de671e34607e909a7213e31d7752be4fb66a86d29fe1eb14bfb5cf
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "1.1.1"
|
||||||
|
collection:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: collection
|
||||||
|
sha256: ee67cb0715911d28db6bf4af1026078bd6f0128b07a5f66fb2ed94ec6783c09a
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "1.18.0"
|
||||||
|
cupertino_icons:
|
||||||
|
dependency: "direct main"
|
||||||
|
description:
|
||||||
|
name: cupertino_icons
|
||||||
|
sha256: ba631d1c7f7bef6b729a622b7b752645a2d076dba9976925b8f25725a30e1ee6
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "1.0.8"
|
||||||
|
fake_async:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: fake_async
|
||||||
|
sha256: "511392330127add0b769b75a987850d136345d9227c6b94c96a04cf4a391bf78"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "1.3.1"
|
||||||
|
flutter:
|
||||||
|
dependency: "direct main"
|
||||||
|
description: flutter
|
||||||
|
source: sdk
|
||||||
|
version: "0.0.0"
|
||||||
|
flutter_lints:
|
||||||
|
dependency: "direct dev"
|
||||||
|
description:
|
||||||
|
name: flutter_lints
|
||||||
|
sha256: "3f41d009ba7172d5ff9be5f6e6e6abb4300e263aab8866d2a0842ed2a70f8f0c"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "4.0.0"
|
||||||
|
flutter_test:
|
||||||
|
dependency: "direct dev"
|
||||||
|
description: flutter
|
||||||
|
source: sdk
|
||||||
|
version: "0.0.0"
|
||||||
|
http:
|
||||||
|
dependency: "direct main"
|
||||||
|
description:
|
||||||
|
name: http
|
||||||
|
sha256: "87721a4a50b19c7f1d49001e51409bddc46303966ce89a65af4f4e6004896412"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "1.6.0"
|
||||||
|
http_parser:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: http_parser
|
||||||
|
sha256: "2aa08ce0341cc9b354a498388e30986515406668dbcc4f7c950c3e715496693b"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "4.0.2"
|
||||||
|
leak_tracker:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: leak_tracker
|
||||||
|
sha256: "3f87a60e8c63aecc975dda1ceedbc8f24de75f09e4856ea27daf8958f2f0ce05"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "10.0.5"
|
||||||
|
leak_tracker_flutter_testing:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: leak_tracker_flutter_testing
|
||||||
|
sha256: "932549fb305594d82d7183ecd9fa93463e9914e1b67cacc34bc40906594a1806"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "3.0.5"
|
||||||
|
leak_tracker_testing:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: leak_tracker_testing
|
||||||
|
sha256: "6ba465d5d76e67ddf503e1161d1f4a6bc42306f9d66ca1e8f079a47290fb06d3"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "3.0.1"
|
||||||
|
lints:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: lints
|
||||||
|
sha256: "976c774dd944a42e83e2467f4cc670daef7eed6295b10b36ae8c85bcbf828235"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "4.0.0"
|
||||||
|
matcher:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: matcher
|
||||||
|
sha256: d2323aa2060500f906aa31a895b4030b6da3ebdcc5619d14ce1aada65cd161cb
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "0.12.16+1"
|
||||||
|
material_color_utilities:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: material_color_utilities
|
||||||
|
sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "0.11.1"
|
||||||
|
meta:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: meta
|
||||||
|
sha256: bdb68674043280c3428e9ec998512fb681678676b3c54e773629ffe74419f8c7
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "1.15.0"
|
||||||
|
path:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: path
|
||||||
|
sha256: "087ce49c3f0dc39180befefc60fdb4acd8f8620e5682fe2476afd0b3688bb4af"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "1.9.0"
|
||||||
|
sky_engine:
|
||||||
|
dependency: transitive
|
||||||
|
description: flutter
|
||||||
|
source: sdk
|
||||||
|
version: "0.0.99"
|
||||||
|
source_span:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: source_span
|
||||||
|
sha256: "53e943d4206a5e30df338fd4c6e7a077e02254531b138a15aec3bd143c1a8b3c"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "1.10.0"
|
||||||
|
stack_trace:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: stack_trace
|
||||||
|
sha256: "73713990125a6d93122541237550ee3352a2d84baad52d375a4cad2eb9b7ce0b"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "1.11.1"
|
||||||
|
stream_channel:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: stream_channel
|
||||||
|
sha256: ba2aa5d8cc609d96bbb2899c28934f9e1af5cddbd60a827822ea467161eb54e7
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "2.1.2"
|
||||||
|
string_scanner:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: string_scanner
|
||||||
|
sha256: "556692adab6cfa87322a115640c11f13cb77b3f076ddcc5d6ae3c20242bedcde"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "1.2.0"
|
||||||
|
term_glyph:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: term_glyph
|
||||||
|
sha256: a29248a84fbb7c79282b40b8c72a1209db169a2e0542bce341da992fe1bc7e84
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "1.2.1"
|
||||||
|
test_api:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: test_api
|
||||||
|
sha256: "5b8a98dafc4d5c4c9c72d8b31ab2b23fc13422348d2997120294d3bac86b4ddb"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "0.7.2"
|
||||||
|
typed_data:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: typed_data
|
||||||
|
sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "1.4.0"
|
||||||
|
vector_math:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: vector_math
|
||||||
|
sha256: "80b3257d1492ce4d091729e3a67a60407d227c27241d6927be0130c98e741803"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "2.1.4"
|
||||||
|
vm_service:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: vm_service
|
||||||
|
sha256: "5c5f338a667b4c644744b661f309fb8080bb94b18a7e91ef1dbd343bed00ed6d"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "14.2.5"
|
||||||
|
web:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: web
|
||||||
|
sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "1.1.1"
|
||||||
|
sdks:
|
||||||
|
dart: ">=3.5.4 <4.0.0"
|
||||||
|
flutter: ">=3.18.0-18.0.pre.54"
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
name: gc_ui
|
||||||
|
description: "GC launcher UI (Flutter frontend)"
|
||||||
|
# The following line prevents the package from being accidentally published to
|
||||||
|
# pub.dev using `flutter pub publish`. This is preferred for private packages.
|
||||||
|
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
|
||||||
|
|
||||||
|
# The following defines the version and build number for your application.
|
||||||
|
# A version number is three numbers separated by dots, like 1.2.43
|
||||||
|
# followed by an optional build number separated by a +.
|
||||||
|
# Both the version and the builder number may be overridden in flutter
|
||||||
|
# build by specifying --build-name and --build-number, respectively.
|
||||||
|
# In Android, build-name is used as versionName while build-number used as versionCode.
|
||||||
|
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
|
||||||
|
# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion.
|
||||||
|
# Read more about iOS versioning at
|
||||||
|
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
|
||||||
|
# In Windows, build-name is used as the major, minor, and patch parts
|
||||||
|
# of the product and file versions while build-number is used as the build suffix.
|
||||||
|
version: 1.1.0+1
|
||||||
|
|
||||||
|
environment:
|
||||||
|
sdk: ^3.5.4
|
||||||
|
|
||||||
|
# Dependencies specify other packages that your package needs in order to work.
|
||||||
|
# To automatically upgrade your package dependencies to the latest versions
|
||||||
|
# consider running `flutter pub upgrade --major-versions`. Alternatively,
|
||||||
|
# dependencies can be manually updated by changing the version numbers below to
|
||||||
|
# the latest version available on pub.dev. To see which dependencies have newer
|
||||||
|
# versions available, run `flutter pub outdated`.
|
||||||
|
dependencies:
|
||||||
|
flutter:
|
||||||
|
sdk: flutter
|
||||||
|
|
||||||
|
# 与 GC-UI 后端(本地 HTTP 服务)通信
|
||||||
|
http: ^1.2.2
|
||||||
|
|
||||||
|
# The following adds the Cupertino Icons font to your application.
|
||||||
|
# Use with the CupertinoIcons class for iOS style icons.
|
||||||
|
cupertino_icons: ^1.0.8
|
||||||
|
|
||||||
|
dev_dependencies:
|
||||||
|
flutter_test:
|
||||||
|
sdk: flutter
|
||||||
|
|
||||||
|
# The "flutter_lints" package below contains a set of recommended lints to
|
||||||
|
# encourage good coding practices. The lint set provided by the package is
|
||||||
|
# activated in the `analysis_options.yaml` file located at the root of your
|
||||||
|
# package. See that file for information about deactivating specific lint
|
||||||
|
# rules and activating additional ones.
|
||||||
|
flutter_lints: ^4.0.0
|
||||||
|
|
||||||
|
# For information on the generic Dart part of this file, see the
|
||||||
|
# following page: https://dart.dev/tools/pub/pubspec
|
||||||
|
|
||||||
|
# The following section is specific to Flutter packages.
|
||||||
|
flutter:
|
||||||
|
|
||||||
|
# The following line ensures that the Material Icons font is
|
||||||
|
# included with your application, so that you can use the icons in
|
||||||
|
# the material Icons class.
|
||||||
|
uses-material-design: true
|
||||||
|
|
||||||
|
# To add assets to your application, add an assets section, like this:
|
||||||
|
# assets:
|
||||||
|
# - images/a_dot_burr.jpeg
|
||||||
|
# - images/a_dot_ham.jpeg
|
||||||
|
|
||||||
|
# An image asset can refer to one or more resolution-specific "variants", see
|
||||||
|
# https://flutter.dev/to/resolution-aware-images
|
||||||
|
|
||||||
|
# For details regarding adding assets from package dependencies, see
|
||||||
|
# https://flutter.dev/to/asset-from-package
|
||||||
|
|
||||||
|
# To add custom fonts to your application, add a fonts section here,
|
||||||
|
# in this "flutter" section. Each entry in this list should have a
|
||||||
|
# "family" key with the font family name, and a "fonts" key with a
|
||||||
|
# list giving the asset and other descriptors for the font. For
|
||||||
|
# example:
|
||||||
|
# fonts:
|
||||||
|
# - family: Schyler
|
||||||
|
# fonts:
|
||||||
|
# - asset: fonts/Schyler-Regular.ttf
|
||||||
|
# - asset: fonts/Schyler-Italic.ttf
|
||||||
|
# style: italic
|
||||||
|
# - family: Trajan Pro
|
||||||
|
# fonts:
|
||||||
|
# - asset: fonts/TrajanPro.ttf
|
||||||
|
# - asset: fonts/TrajanPro_Bold.ttf
|
||||||
|
# weight: 700
|
||||||
|
#
|
||||||
|
# For details regarding fonts from package dependencies,
|
||||||
|
# see https://flutter.dev/to/font-from-package
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:gc_ui/api_client.dart';
|
||||||
|
|
||||||
|
/// 前后端契约联调测试。
|
||||||
|
///
|
||||||
|
/// 需要 GC-UI 后端正在运行(`dotnet run --project GC-UI/backend/GC.UI.Server`)。
|
||||||
|
/// 后端没起时整组跳过,不会让 CI 变红。
|
||||||
|
///
|
||||||
|
/// 注意:flutter_test 默认把所有 HTTP 请求拦成 400,这里显式放开真实网络。
|
||||||
|
void main() {
|
||||||
|
setUpAll(() {
|
||||||
|
HttpOverrides.global = null;
|
||||||
|
});
|
||||||
|
|
||||||
|
final api = GcApi(
|
||||||
|
baseUrl: const String.fromEnvironment(
|
||||||
|
'GC_UI_BASE_URL',
|
||||||
|
defaultValue: 'http://127.0.0.1:17890',
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
Future<bool> backendUp() async {
|
||||||
|
try {
|
||||||
|
await api.health();
|
||||||
|
return true;
|
||||||
|
} catch (_) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
test('health / settings / models / sources / jobs 都能解析', () async {
|
||||||
|
if (!await backendUp()) {
|
||||||
|
markTestSkipped('后端未运行,跳过联调测试');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
final health = await api.health();
|
||||||
|
expect(health.ok, isTrue);
|
||||||
|
expect(health.version, isNotEmpty);
|
||||||
|
expect(health.platform, isNotEmpty);
|
||||||
|
|
||||||
|
final settings = await api.settings();
|
||||||
|
expect(settings.modelRoot, isNotEmpty);
|
||||||
|
expect(settings.dataRoot, isNotEmpty);
|
||||||
|
expect(settings.renderFps, greaterThan(0));
|
||||||
|
expect(settings.memoryMb, greaterThan(0));
|
||||||
|
expect(settings.languages, isNotEmpty);
|
||||||
|
expect(settings.sources, isNotEmpty);
|
||||||
|
|
||||||
|
final models = await api.models();
|
||||||
|
for (final model in models) {
|
||||||
|
expect(model.id, isNotEmpty);
|
||||||
|
expect(model.name, isNotEmpty);
|
||||||
|
}
|
||||||
|
|
||||||
|
final sources = await api.sources();
|
||||||
|
expect(sources, isNotEmpty);
|
||||||
|
expect(sources.first.id, isNotEmpty);
|
||||||
|
|
||||||
|
final jobs = await api.jobs();
|
||||||
|
expect(jobs, isA<List<JobInfo>>());
|
||||||
|
});
|
||||||
|
|
||||||
|
test('设置补丁能写回并读出一致', () async {
|
||||||
|
if (!await backendUp()) {
|
||||||
|
markTestSkipped('后端未运行,跳过联调测试');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
final before = await api.settings();
|
||||||
|
final updated = await api.saveSettings(
|
||||||
|
SettingsPatch(renderFps: before.renderFps == 60 ? 90 : 60),
|
||||||
|
);
|
||||||
|
expect(updated.renderFps, before.renderFps == 60 ? 90 : 60);
|
||||||
|
|
||||||
|
final restored = await api.saveSettings(
|
||||||
|
SettingsPatch(renderFps: before.renderFps),
|
||||||
|
);
|
||||||
|
expect(restored.renderFps, before.renderFps);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('越界路径被后端拒绝', () async {
|
||||||
|
if (!await backendUp()) {
|
||||||
|
markTestSkipped('后端未运行,跳过联调测试');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await expectLater(
|
||||||
|
api.openFolder('/etc'),
|
||||||
|
throwsA(isA<ApiException>()),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:gc_ui/api_client.dart';
|
||||||
|
import 'package:gc_ui/i18n.dart';
|
||||||
|
import 'package:gc_ui/theme.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
group('I18n', () {
|
||||||
|
test('resolves auto to a supported language', () {
|
||||||
|
expect(I18n.supported.contains(I18n.resolve('auto')), isTrue);
|
||||||
|
expect(I18n.resolve('en-US'), 'en');
|
||||||
|
expect(I18n.resolve('zh-CN'), 'zh-CN');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('translates keys and fills placeholders', () {
|
||||||
|
I18n.language.value = 'zh-CN';
|
||||||
|
expect(T('nav.home'), '主页');
|
||||||
|
expect(T('home.count', <Object?>[3]), '3 个模型');
|
||||||
|
|
||||||
|
I18n.language.value = 'en';
|
||||||
|
expect(T('nav.home'), 'Home');
|
||||||
|
expect(T('home.count', <Object?>[3]), '3 models');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('falls back to the key for unknown entries', () {
|
||||||
|
expect(T('does.not.exist'), 'does.not.exist');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
group('SettingsPatch', () {
|
||||||
|
test('only serialises the fields that were set', () {
|
||||||
|
const patch = SettingsPatch(renderFps: 60, memoryAuto: false);
|
||||||
|
expect(patch.toJson(), <String, dynamic>{
|
||||||
|
'renderFps': 60,
|
||||||
|
'memoryAuto': false,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('empty patch serialises to an empty map', () {
|
||||||
|
expect(const SettingsPatch().toJson(), isEmpty);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
group('GcApi', () {
|
||||||
|
test('builds model preview urls from the base url', () {
|
||||||
|
final api = GcApi(baseUrl: 'http://127.0.0.1:17890');
|
||||||
|
final model = ModelInfo.fromJson(<String, dynamic>{
|
||||||
|
'id': 'solar-system',
|
||||||
|
'name': '太阳系',
|
||||||
|
'previewUrl': '/api/models/solar-system/preview',
|
||||||
|
});
|
||||||
|
expect(api.previewUrl(model),
|
||||||
|
'http://127.0.0.1:17890/api/models/solar-system/preview');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('parses a model payload', () {
|
||||||
|
final model = ModelInfo.fromJson(<String, dynamic>{
|
||||||
|
'id': 'earth',
|
||||||
|
'name': '地球',
|
||||||
|
'version': '1.2.0',
|
||||||
|
'sizeBytes': 1048576,
|
||||||
|
'sizeText': '1.0 MB',
|
||||||
|
'tags': <dynamic>['天文', '地球'],
|
||||||
|
'hasPreview': true,
|
||||||
|
});
|
||||||
|
expect(model.id, 'earth');
|
||||||
|
expect(model.tags, <String>['天文', '地球']);
|
||||||
|
expect(model.metaText, 'v1.2.0 · 1.0 MB');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
group('theme', () {
|
||||||
|
testWidgets('renders a card with its child', (tester) async {
|
||||||
|
await tester.pumpWidget(
|
||||||
|
MaterialApp(
|
||||||
|
theme: buildGcTheme(Brightness.dark),
|
||||||
|
home: const Scaffold(
|
||||||
|
body: GcCard(child: Text('hello')),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
expect(find.text('hello'), findsOneWidget);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,443 @@
|
|||||||
|
import 'dart:io';
|
||||||
|
import 'dart:ui' as ui;
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter/rendering.dart';
|
||||||
|
import 'package:flutter/services.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:gc_ui/api_client.dart';
|
||||||
|
import 'package:gc_ui/controller.dart';
|
||||||
|
import 'package:gc_ui/i18n.dart';
|
||||||
|
import 'package:gc_ui/pages.dart';
|
||||||
|
import 'package:gc_ui/shell.dart';
|
||||||
|
import 'package:gc_ui/theme.dart';
|
||||||
|
|
||||||
|
/// 视觉检查:把真实页面渲染成 PNG 写到 test/shots/。
|
||||||
|
///
|
||||||
|
/// 用 RepaintBoundary 直接取像素,不走 golden 比较器(避免网络图片阻塞)。
|
||||||
|
/// 测试环境默认用 Ahem 占位字体,这里显式加载系统中文字体,否则中文全是方块。
|
||||||
|
///
|
||||||
|
/// 运行(需要后端已在 127.0.0.1:17890 上跑起来):
|
||||||
|
/// flutter test tool/render_shots_test.dart
|
||||||
|
void main() {
|
||||||
|
setUpAll(() async {
|
||||||
|
// 不要设置 HttpOverrides.global = null:那会打开真实网络,
|
||||||
|
// flutter_test 的假时钟下 HTTP 定时器永远悬着,用例结束时
|
||||||
|
// 会撞上「!timersPending」断言。保持 flutter_test 默认的 FakeHttpClient
|
||||||
|
// (所有请求立即返回 400),页面本身都用预置数据渲染,不需要后端。
|
||||||
|
// 测试环境默认用 Ahem 占位字体(所有字都是方块),必须显式加载一套真字体:
|
||||||
|
// Linux CI 用 Noto CJK,Windows 本机用 Noto Sans SC / 微软雅黑,macOS 用苹方。
|
||||||
|
const candidates = <String>[
|
||||||
|
r'C:\Windows\Fonts\Deng.ttf',
|
||||||
|
r'C:\Windows\Fonts\NotoSansSC-VF.ttf',
|
||||||
|
r'C:\Windows\Fonts\msyh.ttc',
|
||||||
|
r'C:\Windows\Fonts\simhei.ttf',
|
||||||
|
'/System/Library/Fonts/PingFang.ttc',
|
||||||
|
'/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc',
|
||||||
|
'/usr/share/fonts/truetype/noto/NotoSansCJK-Regular.ttc',
|
||||||
|
];
|
||||||
|
for (final path in candidates) {
|
||||||
|
final file = File(path);
|
||||||
|
if (!file.existsSync()) continue;
|
||||||
|
final bytes = file.readAsBytesSync();
|
||||||
|
final loader = FontLoader('Noto Sans CJK SC')
|
||||||
|
..addFont(Future<ByteData>.value(ByteData.view(bytes.buffer)));
|
||||||
|
await loader.load();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Material 图标字体:flutter_test 不会自动加载,不加载的话所有 Icon
|
||||||
|
// 都是方框,截图就没法检查图标。SDK 缓存里那份由 flutter test 通过
|
||||||
|
// FLUTTER_ROOT 指过来。
|
||||||
|
final flutterRoot = Platform.environment['FLUTTER_ROOT'];
|
||||||
|
if (flutterRoot != null) {
|
||||||
|
final icons = File(
|
||||||
|
'$flutterRoot/bin/cache/artifacts/material_fonts/materialicons-regular.otf',
|
||||||
|
);
|
||||||
|
if (icons.existsSync()) {
|
||||||
|
final bytes = icons.readAsBytesSync();
|
||||||
|
final loader = FontLoader('MaterialIcons')
|
||||||
|
..addFont(Future<ByteData>.value(ByteData.view(bytes.buffer)));
|
||||||
|
await loader.load();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
SettingsInfo sampleSettings() => SettingsInfo.fromJson(<String, dynamic>{
|
||||||
|
'language': 'zh-CN',
|
||||||
|
'theme': 'dark',
|
||||||
|
'renderFps': 120,
|
||||||
|
'memoryMb': 2048,
|
||||||
|
'memoryAuto': true,
|
||||||
|
'autoUpdateOnStartup': true,
|
||||||
|
'requireSignedManifest': true,
|
||||||
|
'updateRepository': 'https://git.xhmcl.com/Morris/GC',
|
||||||
|
'memoryBudgetMb': 2048,
|
||||||
|
'memoryUsageText': '512 MB / 2048 MB',
|
||||||
|
'modelRoot': '/Users/morris/.GC/model',
|
||||||
|
'dataRoot': '/Users/morris/.GC/data',
|
||||||
|
'settingsFile': '/Users/morris/.GC/settings.json',
|
||||||
|
'version': '1.0.7',
|
||||||
|
'platform': 'osx-arm64',
|
||||||
|
'sources': <dynamic>[
|
||||||
|
<String, dynamic>{
|
||||||
|
'id': 'github',
|
||||||
|
'name': 'GitHub',
|
||||||
|
'url': 'https://github.com/Morris-GC/GC',
|
||||||
|
'enabled': true,
|
||||||
|
'builtIn': true,
|
||||||
|
'host': 'github.com',
|
||||||
|
},
|
||||||
|
<String, dynamic>{
|
||||||
|
'id': 'gitee',
|
||||||
|
'name': 'Gitee',
|
||||||
|
'url': 'https://gitee.com/morris/gc',
|
||||||
|
'enabled': true,
|
||||||
|
'builtIn': true,
|
||||||
|
'host': 'gitee.com',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
'languages': <dynamic>[
|
||||||
|
<String, dynamic>{'code': 'zh-CN', 'label': '简体中文'},
|
||||||
|
<String, dynamic>{'code': 'en', 'label': 'English'},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
List<ModelInfo> sampleModels() => <ModelInfo>[
|
||||||
|
ModelInfo.fromJson(<String, dynamic>{
|
||||||
|
'id': 'contour-map',
|
||||||
|
'name': '等高线地图',
|
||||||
|
'description': '把三维地形与等高线对应起来,识别山峰、山脊、山谷、鞍部与陡崖。',
|
||||||
|
'version': '1.0',
|
||||||
|
'author': 'Morris GC',
|
||||||
|
'sizeBytes': 147351,
|
||||||
|
'sizeText': '143.9 KB',
|
||||||
|
'tags': <dynamic>['地理', '地图', '等高线', '地形'],
|
||||||
|
'hasPreview': false,
|
||||||
|
}),
|
||||||
|
ModelInfo.fromJson(<String, dynamic>{
|
||||||
|
'id': 'solar-system',
|
||||||
|
'name': '太阳系',
|
||||||
|
'description': '观察八大行星的公转轨道与相对大小,理解日地月系统的尺度关系。',
|
||||||
|
'version': '1.2',
|
||||||
|
'author': 'Morris GC',
|
||||||
|
'sizeBytes': 2411724,
|
||||||
|
'sizeText': '2.3 MB',
|
||||||
|
'tags': <dynamic>['天文', '太阳系', '公转'],
|
||||||
|
'hasPreview': false,
|
||||||
|
}),
|
||||||
|
ModelInfo.fromJson(<String, dynamic>{
|
||||||
|
'id': 'earth-rotation',
|
||||||
|
'name': '地球自转',
|
||||||
|
'description': '用可交互的三维地球演示自转方向、昼夜交替与地方时差。',
|
||||||
|
'version': '1.1',
|
||||||
|
'author': 'Morris GC',
|
||||||
|
'sizeBytes': 1887436,
|
||||||
|
'sizeText': '1.8 MB',
|
||||||
|
'tags': <dynamic>['天文', '地球', '自转'],
|
||||||
|
'hasPreview': false,
|
||||||
|
}),
|
||||||
|
];
|
||||||
|
|
||||||
|
ShellController sampleController() => ShellController(api: GcApi())
|
||||||
|
..settings = sampleSettings()
|
||||||
|
..health = HealthInfo.fromJson(<String, dynamic>{
|
||||||
|
'ok': true,
|
||||||
|
'version': '1.0.7',
|
||||||
|
'platform': 'osx-arm64',
|
||||||
|
'uiAvailable': true,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// 外壳用的 controller:bootstrap 直接返回,不去连后端。
|
||||||
|
///
|
||||||
|
/// 真 ShellPage 会在 initState 里 bootstrap,后端不在时会挂重试定时器,
|
||||||
|
/// 用例结束时报「!timersPending」。这里只把 bootstrap 换成空实现,
|
||||||
|
/// 页面里的数据请求仍会走 flutter_test 的假 HTTP(立即 400)。
|
||||||
|
ShellController shellController() => _StubShellController()
|
||||||
|
..settings = sampleSettings()
|
||||||
|
..health = HealthInfo.fromJson(<String, dynamic>{
|
||||||
|
'ok': true,
|
||||||
|
'version': '1.0.7',
|
||||||
|
'platform': 'osx-arm64',
|
||||||
|
'uiAvailable': true,
|
||||||
|
});
|
||||||
|
|
||||||
|
Future<void> shoot(WidgetTester tester, String name, Widget page,
|
||||||
|
{Brightness brightness = Brightness.dark,
|
||||||
|
Size size = const Size(1280, 860)}) async {
|
||||||
|
// 1280×860:与发布包窗口默认尺寸(1280×720)接近,再多留一点高度看得到
|
||||||
|
// 底部状态条。像素比 1.0,方便逐像素检查描边和文字。
|
||||||
|
tester.view.physicalSize = size;
|
||||||
|
tester.view.devicePixelRatio = 1.0;
|
||||||
|
addTearDown(tester.view.reset);
|
||||||
|
|
||||||
|
// GcColors 是静态取值,截图前先按目标亮度绑定,否则浅色截图仍是深色配色。
|
||||||
|
GcColors.bind(brightness);
|
||||||
|
|
||||||
|
final key = GlobalKey();
|
||||||
|
await tester.pumpWidget(
|
||||||
|
MaterialApp(
|
||||||
|
debugShowCheckedModeBanner: false,
|
||||||
|
// 四个页面都用预置数据渲染,不需要后端;字体统一换成测试里加载的
|
||||||
|
// 那一套,并且清空 fallback —— 否则主题里的按钮 / 输入框样式会去
|
||||||
|
// 找系统字体(测试环境没有),缺字处就画成方块。
|
||||||
|
theme: buildGcTheme(
|
||||||
|
brightness,
|
||||||
|
fontFamily: 'Noto Sans CJK SC',
|
||||||
|
fontFamilyFallback: const <String>[],
|
||||||
|
),
|
||||||
|
home: RepaintBoundary(
|
||||||
|
key: key,
|
||||||
|
child: Scaffold(backgroundColor: GcColors.appBg, body: page),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await tester.pump(const Duration(milliseconds: 200));
|
||||||
|
await tester.pump(const Duration(milliseconds: 300));
|
||||||
|
|
||||||
|
final boundary =
|
||||||
|
key.currentContext!.findRenderObject()! as RenderRepaintBoundary;
|
||||||
|
// toImage / toByteData 要走真实引擎的异步管线,必须放在 runAsync 里,
|
||||||
|
// 否则 fake async 时钟不会推进,Future 一直不完成(表现为每个用例卡
|
||||||
|
// 满 10 分钟超时才返回)。
|
||||||
|
final stopwatch = Stopwatch()..start();
|
||||||
|
final image = await tester.runAsync(
|
||||||
|
() => boundary.toImage(pixelRatio: 1.0),
|
||||||
|
);
|
||||||
|
final bytes = await tester.runAsync(
|
||||||
|
() => image!.toByteData(format: ui.ImageByteFormat.png),
|
||||||
|
);
|
||||||
|
|
||||||
|
final dir = Directory('test/shots')..createSync(recursive: true);
|
||||||
|
File('${dir.path}/$name.png').writeAsBytesSync(bytes!.buffer.asUint8List());
|
||||||
|
stopwatch.stop();
|
||||||
|
// ignore: avoid_print
|
||||||
|
print(
|
||||||
|
'[shots] $name (${brightness.name}) 耗时 ${stopwatch.elapsedMilliseconds} ms');
|
||||||
|
}
|
||||||
|
|
||||||
|
testWidgets('home', (tester) async {
|
||||||
|
I18n.language.value = 'zh-CN';
|
||||||
|
await shoot(
|
||||||
|
tester,
|
||||||
|
'home',
|
||||||
|
HomePageView(
|
||||||
|
controller: sampleController(), initialModels: sampleModels()),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('download', (tester) async {
|
||||||
|
I18n.language.value = 'zh-CN';
|
||||||
|
await shoot(
|
||||||
|
tester,
|
||||||
|
'download',
|
||||||
|
DownloadPageView(
|
||||||
|
controller: sampleController(),
|
||||||
|
initialSources: <SourceInfo>[
|
||||||
|
SourceInfo.fromJson(<String, dynamic>{
|
||||||
|
'id': 'github',
|
||||||
|
'name': 'GitHub',
|
||||||
|
'url': 'https://github.com/Morris-GC/GC',
|
||||||
|
'enabled': true,
|
||||||
|
'builtIn': true,
|
||||||
|
'host': 'github.com',
|
||||||
|
}),
|
||||||
|
SourceInfo.fromJson(<String, dynamic>{
|
||||||
|
'id': 'gitee',
|
||||||
|
'name': 'Gitee',
|
||||||
|
'url': 'https://gitee.com/morris/gc',
|
||||||
|
'enabled': true,
|
||||||
|
'builtIn': true,
|
||||||
|
'host': 'gitee.com',
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
initialIndex: SourceIndexInfo.fromJson(<String, dynamic>{
|
||||||
|
'sourceId': 'github',
|
||||||
|
'root': 'https://github.com/Morris-GC/GC',
|
||||||
|
'fromCache': false,
|
||||||
|
'resolvedFrom': 'version.json',
|
||||||
|
'models': <dynamic>[
|
||||||
|
<String, dynamic>{
|
||||||
|
'id': 'solar-system',
|
||||||
|
'name': '太阳系',
|
||||||
|
'description': '观察八大行星的公转轨道与相对大小。',
|
||||||
|
'version': '1.2',
|
||||||
|
'sizeBytes': 2411724,
|
||||||
|
'sizeText': '2.3 MB',
|
||||||
|
'sourceId': 'github',
|
||||||
|
'installed': true,
|
||||||
|
'installedVersion': '1.2',
|
||||||
|
},
|
||||||
|
<String, dynamic>{
|
||||||
|
'id': 'earth-revolution',
|
||||||
|
'name': '地球公转',
|
||||||
|
'description': '演示公转轨道、四季成因与太阳直射点移动。',
|
||||||
|
'version': '1.0',
|
||||||
|
'sizeBytes': 2097152,
|
||||||
|
'sizeText': '2.0 MB',
|
||||||
|
'sourceId': 'github',
|
||||||
|
'installed': false,
|
||||||
|
},
|
||||||
|
<String, dynamic>{
|
||||||
|
'id': 'earth-geography',
|
||||||
|
'name': '地球地理',
|
||||||
|
'description': '经纬网、海陆分布与大洲大洋的交互式讲解。',
|
||||||
|
'version': '1.1',
|
||||||
|
'sizeBytes': 3145728,
|
||||||
|
'sizeText': '3.0 MB',
|
||||||
|
'sourceId': 'github',
|
||||||
|
'installed': false,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
initialJobs: <JobInfo>[
|
||||||
|
JobInfo.fromJson(<String, dynamic>{
|
||||||
|
'id': 'job-1',
|
||||||
|
'modelId': 'earth-revolution',
|
||||||
|
'name': '地球公转',
|
||||||
|
'version': '1.0',
|
||||||
|
'state': 'Downloading',
|
||||||
|
'progress': 0.42,
|
||||||
|
'statusText': '正在下载 42%',
|
||||||
|
'detailText': '860 KB / 2.0 MB',
|
||||||
|
'isActive': true,
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('settings', (tester) async {
|
||||||
|
I18n.language.value = 'zh-CN';
|
||||||
|
await shoot(
|
||||||
|
tester, 'settings', SettingsPageView(controller: sampleController()));
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('about', (tester) async {
|
||||||
|
I18n.language.value = 'zh-CN';
|
||||||
|
await shoot(
|
||||||
|
tester,
|
||||||
|
'about',
|
||||||
|
AboutPageView(
|
||||||
|
controller: sampleController(),
|
||||||
|
initialAbout: AboutInfo.fromJson(<String, dynamic>{
|
||||||
|
'appName': 'Morris GC',
|
||||||
|
'version': '1.0.7',
|
||||||
|
'platform': 'osx-arm64',
|
||||||
|
'repository': 'https://git.xhmcl.com/Morris/GC',
|
||||||
|
'sourceLanguage': 'C#',
|
||||||
|
'frontend': 'Flutter',
|
||||||
|
'contributors': <dynamic>[
|
||||||
|
<String, dynamic>{
|
||||||
|
'name': 'Morris',
|
||||||
|
'contributions': 25,
|
||||||
|
'avatarUrl': null,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('shell', (tester) async {
|
||||||
|
I18n.language.value = 'zh-CN';
|
||||||
|
final controller = shellController()
|
||||||
|
..setUpdateStatus(
|
||||||
|
visible: true,
|
||||||
|
busy: false,
|
||||||
|
progress: 1,
|
||||||
|
status: '已更新 2 个模型,立即生效',
|
||||||
|
detail: '模型与启动器均为最新版',
|
||||||
|
notice: '',
|
||||||
|
);
|
||||||
|
await shoot(tester, 'shell', ShellPage(controller: controller));
|
||||||
|
});
|
||||||
|
|
||||||
|
/// 小窗口回归:1024×680 下不应出现溢出条纹或卡片挤压。
|
||||||
|
testWidgets('home-small', (tester) async {
|
||||||
|
I18n.language.value = 'zh-CN';
|
||||||
|
await shoot(
|
||||||
|
tester,
|
||||||
|
'home-small',
|
||||||
|
HomePageView(
|
||||||
|
controller: sampleController(), initialModels: sampleModels()),
|
||||||
|
size: const Size(1024, 680),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('download-small', (tester) async {
|
||||||
|
I18n.language.value = 'zh-CN';
|
||||||
|
await shoot(
|
||||||
|
tester,
|
||||||
|
'download-small',
|
||||||
|
DownloadPageView(
|
||||||
|
controller: sampleController(),
|
||||||
|
initialSources: <SourceInfo>[
|
||||||
|
SourceInfo.fromJson(<String, dynamic>{
|
||||||
|
'id': 'github',
|
||||||
|
'name': 'GitHub',
|
||||||
|
'url': 'https://github.com/Morris-GC/GC',
|
||||||
|
'enabled': true,
|
||||||
|
'builtIn': true,
|
||||||
|
'host': 'github.com',
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
initialIndex: SourceIndexInfo.fromJson(<String, dynamic>{
|
||||||
|
'sourceId': 'github',
|
||||||
|
'root': 'https://github.com/Morris-GC/GC',
|
||||||
|
'fromCache': false,
|
||||||
|
'resolvedFrom': 'version.json',
|
||||||
|
'models': <dynamic>[
|
||||||
|
<String, dynamic>{
|
||||||
|
'id': 'sun',
|
||||||
|
'name': '太阳系',
|
||||||
|
'description': '观察八大行星的公转轨道与相对大小。',
|
||||||
|
'version': '1.2',
|
||||||
|
'sizeText': '2.3 MB',
|
||||||
|
'installed': true,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
initialJobs: const <JobInfo>[],
|
||||||
|
),
|
||||||
|
size: const Size(1024, 680),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('settings-small', (tester) async {
|
||||||
|
I18n.language.value = 'zh-CN';
|
||||||
|
await shoot(
|
||||||
|
tester,
|
||||||
|
'settings-small',
|
||||||
|
SettingsPageView(controller: sampleController()),
|
||||||
|
size: const Size(1024, 680),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('home-light', (tester) async {
|
||||||
|
I18n.language.value = 'zh-CN';
|
||||||
|
await shoot(
|
||||||
|
tester,
|
||||||
|
'home-light',
|
||||||
|
HomePageView(
|
||||||
|
controller: sampleController(), initialModels: sampleModels()),
|
||||||
|
brightness: Brightness.light,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('settings-light', (tester) async {
|
||||||
|
I18n.language.value = 'zh-CN';
|
||||||
|
await shoot(
|
||||||
|
tester,
|
||||||
|
'settings-light',
|
||||||
|
SettingsPageView(controller: sampleController()),
|
||||||
|
brightness: Brightness.light,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 只用于截图的 controller:不连后端,避免挂上重试定时器。
|
||||||
|
class _StubShellController extends ShellController {
|
||||||
|
@override
|
||||||
|
Future<void> bootstrap() async {}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
flutter/ephemeral/
|
||||||
|
|
||||||
|
# Visual Studio user-specific files.
|
||||||
|
*.suo
|
||||||
|
*.user
|
||||||
|
*.userosscache
|
||||||
|
*.sln.docstates
|
||||||
|
|
||||||
|
# Visual Studio build-related files.
|
||||||
|
x64/
|
||||||
|
x86/
|
||||||
|
|
||||||
|
# Visual Studio cache files
|
||||||
|
# files ending in .cache can be ignored
|
||||||
|
*.[Cc]ache
|
||||||
|
# but keep track of directories ending in .cache
|
||||||
|
!*.[Cc]ache/
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
# Project-level configuration.
|
||||||
|
cmake_minimum_required(VERSION 3.14)
|
||||||
|
project(gc_ui LANGUAGES CXX)
|
||||||
|
|
||||||
|
# The name of the executable created for the application. Change this to change
|
||||||
|
# the on-disk name of your application.
|
||||||
|
set(BINARY_NAME "GC-UI")
|
||||||
|
|
||||||
|
# Explicitly opt in to modern CMake behaviors to avoid warnings with recent
|
||||||
|
# versions of CMake.
|
||||||
|
cmake_policy(VERSION 3.14...3.25)
|
||||||
|
|
||||||
|
# Define build configuration option.
|
||||||
|
get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG)
|
||||||
|
if(IS_MULTICONFIG)
|
||||||
|
set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release"
|
||||||
|
CACHE STRING "" FORCE)
|
||||||
|
else()
|
||||||
|
if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
|
||||||
|
set(CMAKE_BUILD_TYPE "Debug" CACHE
|
||||||
|
STRING "Flutter build mode" FORCE)
|
||||||
|
set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS
|
||||||
|
"Debug" "Profile" "Release")
|
||||||
|
endif()
|
||||||
|
endif()
|
||||||
|
# Define settings for the Profile build mode.
|
||||||
|
set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}")
|
||||||
|
set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}")
|
||||||
|
set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}")
|
||||||
|
set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}")
|
||||||
|
|
||||||
|
# Use Unicode for all projects.
|
||||||
|
add_definitions(-DUNICODE -D_UNICODE)
|
||||||
|
|
||||||
|
# Compilation settings that should be applied to most targets.
|
||||||
|
#
|
||||||
|
# Be cautious about adding new options here, as plugins use this function by
|
||||||
|
# default. In most cases, you should add new options to specific targets instead
|
||||||
|
# of modifying this function.
|
||||||
|
function(APPLY_STANDARD_SETTINGS TARGET)
|
||||||
|
target_compile_features(${TARGET} PUBLIC cxx_std_17)
|
||||||
|
target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100")
|
||||||
|
target_compile_options(${TARGET} PRIVATE /EHsc)
|
||||||
|
target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0")
|
||||||
|
target_compile_definitions(${TARGET} PRIVATE "$<$<CONFIG:Debug>:_DEBUG>")
|
||||||
|
endfunction()
|
||||||
|
|
||||||
|
# Flutter library and tool build rules.
|
||||||
|
set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter")
|
||||||
|
add_subdirectory(${FLUTTER_MANAGED_DIR})
|
||||||
|
|
||||||
|
# Application build; see runner/CMakeLists.txt.
|
||||||
|
add_subdirectory("runner")
|
||||||
|
|
||||||
|
|
||||||
|
# Generated plugin build rules, which manage building the plugins and adding
|
||||||
|
# them to the application.
|
||||||
|
include(flutter/generated_plugins.cmake)
|
||||||
|
|
||||||
|
|
||||||
|
# === Installation ===
|
||||||
|
# Support files are copied into place next to the executable, so that it can
|
||||||
|
# run in place. This is done instead of making a separate bundle (as on Linux)
|
||||||
|
# so that building and running from within Visual Studio will work.
|
||||||
|
set(BUILD_BUNDLE_DIR "$<TARGET_FILE_DIR:${BINARY_NAME}>")
|
||||||
|
# Make the "install" step default, as it's required to run.
|
||||||
|
set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1)
|
||||||
|
if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT)
|
||||||
|
set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data")
|
||||||
|
set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}")
|
||||||
|
|
||||||
|
install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}"
|
||||||
|
COMPONENT Runtime)
|
||||||
|
|
||||||
|
install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}"
|
||||||
|
COMPONENT Runtime)
|
||||||
|
|
||||||
|
install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
|
||||||
|
COMPONENT Runtime)
|
||||||
|
|
||||||
|
if(PLUGIN_BUNDLED_LIBRARIES)
|
||||||
|
install(FILES "${PLUGIN_BUNDLED_LIBRARIES}"
|
||||||
|
DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
|
||||||
|
COMPONENT Runtime)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
# Copy the native assets provided by the build.dart from all packages.
|
||||||
|
set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/")
|
||||||
|
install(DIRECTORY "${NATIVE_ASSETS_DIR}"
|
||||||
|
DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
|
||||||
|
COMPONENT Runtime)
|
||||||
|
|
||||||
|
# Fully re-copy the assets directory on each build to avoid having stale files
|
||||||
|
# from a previous install.
|
||||||
|
set(FLUTTER_ASSET_DIR_NAME "flutter_assets")
|
||||||
|
install(CODE "
|
||||||
|
file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\")
|
||||||
|
" COMPONENT Runtime)
|
||||||
|
install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}"
|
||||||
|
DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime)
|
||||||
|
|
||||||
|
# Install the AOT library on non-Debug builds only.
|
||||||
|
install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}"
|
||||||
|
CONFIGURATIONS Profile;Release
|
||||||
|
COMPONENT Runtime)
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
# This file controls Flutter-level build steps. It should not be edited.
|
||||||
|
cmake_minimum_required(VERSION 3.14)
|
||||||
|
|
||||||
|
set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral")
|
||||||
|
|
||||||
|
# Configuration provided via flutter tool.
|
||||||
|
include(${EPHEMERAL_DIR}/generated_config.cmake)
|
||||||
|
|
||||||
|
# TODO: Move the rest of this into files in ephemeral. See
|
||||||
|
# https://github.com/flutter/flutter/issues/57146.
|
||||||
|
set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper")
|
||||||
|
|
||||||
|
# Set fallback configurations for older versions of the flutter tool.
|
||||||
|
if (NOT DEFINED FLUTTER_TARGET_PLATFORM)
|
||||||
|
set(FLUTTER_TARGET_PLATFORM "windows-x64")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
# === Flutter Library ===
|
||||||
|
set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll")
|
||||||
|
|
||||||
|
# Published to parent scope for install step.
|
||||||
|
set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE)
|
||||||
|
set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE)
|
||||||
|
set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE)
|
||||||
|
set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE)
|
||||||
|
|
||||||
|
list(APPEND FLUTTER_LIBRARY_HEADERS
|
||||||
|
"flutter_export.h"
|
||||||
|
"flutter_windows.h"
|
||||||
|
"flutter_messenger.h"
|
||||||
|
"flutter_plugin_registrar.h"
|
||||||
|
"flutter_texture_registrar.h"
|
||||||
|
)
|
||||||
|
list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/")
|
||||||
|
add_library(flutter INTERFACE)
|
||||||
|
target_include_directories(flutter INTERFACE
|
||||||
|
"${EPHEMERAL_DIR}"
|
||||||
|
)
|
||||||
|
target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib")
|
||||||
|
add_dependencies(flutter flutter_assemble)
|
||||||
|
|
||||||
|
# === Wrapper ===
|
||||||
|
list(APPEND CPP_WRAPPER_SOURCES_CORE
|
||||||
|
"core_implementations.cc"
|
||||||
|
"standard_codec.cc"
|
||||||
|
)
|
||||||
|
list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/")
|
||||||
|
list(APPEND CPP_WRAPPER_SOURCES_PLUGIN
|
||||||
|
"plugin_registrar.cc"
|
||||||
|
)
|
||||||
|
list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/")
|
||||||
|
list(APPEND CPP_WRAPPER_SOURCES_APP
|
||||||
|
"flutter_engine.cc"
|
||||||
|
"flutter_view_controller.cc"
|
||||||
|
)
|
||||||
|
list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/")
|
||||||
|
|
||||||
|
# Wrapper sources needed for a plugin.
|
||||||
|
add_library(flutter_wrapper_plugin STATIC
|
||||||
|
${CPP_WRAPPER_SOURCES_CORE}
|
||||||
|
${CPP_WRAPPER_SOURCES_PLUGIN}
|
||||||
|
)
|
||||||
|
apply_standard_settings(flutter_wrapper_plugin)
|
||||||
|
set_target_properties(flutter_wrapper_plugin PROPERTIES
|
||||||
|
POSITION_INDEPENDENT_CODE ON)
|
||||||
|
set_target_properties(flutter_wrapper_plugin PROPERTIES
|
||||||
|
CXX_VISIBILITY_PRESET hidden)
|
||||||
|
target_link_libraries(flutter_wrapper_plugin PUBLIC flutter)
|
||||||
|
target_include_directories(flutter_wrapper_plugin PUBLIC
|
||||||
|
"${WRAPPER_ROOT}/include"
|
||||||
|
)
|
||||||
|
add_dependencies(flutter_wrapper_plugin flutter_assemble)
|
||||||
|
|
||||||
|
# Wrapper sources needed for the runner.
|
||||||
|
add_library(flutter_wrapper_app STATIC
|
||||||
|
${CPP_WRAPPER_SOURCES_CORE}
|
||||||
|
${CPP_WRAPPER_SOURCES_APP}
|
||||||
|
)
|
||||||
|
apply_standard_settings(flutter_wrapper_app)
|
||||||
|
target_link_libraries(flutter_wrapper_app PUBLIC flutter)
|
||||||
|
target_include_directories(flutter_wrapper_app PUBLIC
|
||||||
|
"${WRAPPER_ROOT}/include"
|
||||||
|
)
|
||||||
|
add_dependencies(flutter_wrapper_app flutter_assemble)
|
||||||
|
|
||||||
|
# === Flutter tool backend ===
|
||||||
|
# _phony_ is a non-existent file to force this command to run every time,
|
||||||
|
# since currently there's no way to get a full input/output list from the
|
||||||
|
# flutter tool.
|
||||||
|
set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_")
|
||||||
|
set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE)
|
||||||
|
add_custom_command(
|
||||||
|
OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS}
|
||||||
|
${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN}
|
||||||
|
${CPP_WRAPPER_SOURCES_APP}
|
||||||
|
${PHONY_OUTPUT}
|
||||||
|
COMMAND ${CMAKE_COMMAND} -E env
|
||||||
|
${FLUTTER_TOOL_ENVIRONMENT}
|
||||||
|
"${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat"
|
||||||
|
${FLUTTER_TARGET_PLATFORM} $<CONFIG>
|
||||||
|
VERBATIM
|
||||||
|
)
|
||||||
|
add_custom_target(flutter_assemble DEPENDS
|
||||||
|
"${FLUTTER_LIBRARY}"
|
||||||
|
${FLUTTER_LIBRARY_HEADERS}
|
||||||
|
${CPP_WRAPPER_SOURCES_CORE}
|
||||||
|
${CPP_WRAPPER_SOURCES_PLUGIN}
|
||||||
|
${CPP_WRAPPER_SOURCES_APP}
|
||||||
|
)
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
cmake_minimum_required(VERSION 3.14)
|
||||||
|
project(runner LANGUAGES CXX)
|
||||||
|
|
||||||
|
# Define the application target. To change its name, change BINARY_NAME in the
|
||||||
|
# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer
|
||||||
|
# work.
|
||||||
|
#
|
||||||
|
# Any new source files that you add to the application should be added here.
|
||||||
|
add_executable(${BINARY_NAME} WIN32
|
||||||
|
"flutter_window.cpp"
|
||||||
|
"main.cpp"
|
||||||
|
"utils.cpp"
|
||||||
|
"win32_window.cpp"
|
||||||
|
"${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc"
|
||||||
|
"Runner.rc"
|
||||||
|
"runner.exe.manifest"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Apply the standard set of build settings. This can be removed for applications
|
||||||
|
# that need different build settings.
|
||||||
|
apply_standard_settings(${BINARY_NAME})
|
||||||
|
|
||||||
|
# Add preprocessor definitions for the build version.
|
||||||
|
target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"")
|
||||||
|
target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}")
|
||||||
|
target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}")
|
||||||
|
target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}")
|
||||||
|
target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}")
|
||||||
|
|
||||||
|
# Disable Windows macros that collide with C++ standard library functions.
|
||||||
|
target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX")
|
||||||
|
|
||||||
|
# Add dependency libraries and include directories. Add any application-specific
|
||||||
|
# dependencies here.
|
||||||
|
target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app)
|
||||||
|
target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib")
|
||||||
|
target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}")
|
||||||
|
|
||||||
|
# Run the Flutter tool portions of the build. This must not be removed.
|
||||||
|
add_dependencies(${BINARY_NAME} flutter_assemble)
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
// Microsoft Visual C++ generated resource script.
|
||||||
|
//
|
||||||
|
#pragma code_page(65001)
|
||||||
|
#include "resource.h"
|
||||||
|
|
||||||
|
#define APSTUDIO_READONLY_SYMBOLS
|
||||||
|
/////////////////////////////////////////////////////////////////////////////
|
||||||
|
//
|
||||||
|
// Generated from the TEXTINCLUDE 2 resource.
|
||||||
|
//
|
||||||
|
#include "winres.h"
|
||||||
|
|
||||||
|
/////////////////////////////////////////////////////////////////////////////
|
||||||
|
#undef APSTUDIO_READONLY_SYMBOLS
|
||||||
|
|
||||||
|
/////////////////////////////////////////////////////////////////////////////
|
||||||
|
// English (United States) resources
|
||||||
|
|
||||||
|
#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
|
||||||
|
LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
|
||||||
|
|
||||||
|
#ifdef APSTUDIO_INVOKED
|
||||||
|
/////////////////////////////////////////////////////////////////////////////
|
||||||
|
//
|
||||||
|
// TEXTINCLUDE
|
||||||
|
//
|
||||||
|
|
||||||
|
1 TEXTINCLUDE
|
||||||
|
BEGIN
|
||||||
|
"resource.h\0"
|
||||||
|
END
|
||||||
|
|
||||||
|
2 TEXTINCLUDE
|
||||||
|
BEGIN
|
||||||
|
"#include ""winres.h""\r\n"
|
||||||
|
"\0"
|
||||||
|
END
|
||||||
|
|
||||||
|
3 TEXTINCLUDE
|
||||||
|
BEGIN
|
||||||
|
"\r\n"
|
||||||
|
"\0"
|
||||||
|
END
|
||||||
|
|
||||||
|
#endif // APSTUDIO_INVOKED
|
||||||
|
|
||||||
|
|
||||||
|
/////////////////////////////////////////////////////////////////////////////
|
||||||
|
//
|
||||||
|
// Icon
|
||||||
|
//
|
||||||
|
|
||||||
|
// Icon with lowest ID value placed first to ensure application icon
|
||||||
|
// remains consistent on all systems.
|
||||||
|
IDI_APP_ICON ICON "resources\\app_icon.ico"
|
||||||
|
|
||||||
|
|
||||||
|
/////////////////////////////////////////////////////////////////////////////
|
||||||
|
//
|
||||||
|
// Version
|
||||||
|
//
|
||||||
|
|
||||||
|
#if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD)
|
||||||
|
#define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD
|
||||||
|
#else
|
||||||
|
#define VERSION_AS_NUMBER 1,0,0,0
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(FLUTTER_VERSION)
|
||||||
|
#define VERSION_AS_STRING FLUTTER_VERSION
|
||||||
|
#else
|
||||||
|
#define VERSION_AS_STRING "1.0.0"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
VS_VERSION_INFO VERSIONINFO
|
||||||
|
FILEVERSION VERSION_AS_NUMBER
|
||||||
|
PRODUCTVERSION VERSION_AS_NUMBER
|
||||||
|
FILEFLAGSMASK VS_FFI_FILEFLAGSMASK
|
||||||
|
#ifdef _DEBUG
|
||||||
|
FILEFLAGS VS_FF_DEBUG
|
||||||
|
#else
|
||||||
|
FILEFLAGS 0x0L
|
||||||
|
#endif
|
||||||
|
FILEOS VOS__WINDOWS32
|
||||||
|
FILETYPE VFT_APP
|
||||||
|
FILESUBTYPE 0x0L
|
||||||
|
BEGIN
|
||||||
|
BLOCK "StringFileInfo"
|
||||||
|
BEGIN
|
||||||
|
BLOCK "040904e4"
|
||||||
|
BEGIN
|
||||||
|
VALUE "CompanyName", "Morris" "\0"
|
||||||
|
VALUE "FileDescription", "GC UI" "\0"
|
||||||
|
VALUE "FileVersion", VERSION_AS_STRING "\0"
|
||||||
|
VALUE "InternalName", "GC-UI" "\0"
|
||||||
|
VALUE "LegalCopyright", "Copyright (C) 2026 Morris. All rights reserved." "\0"
|
||||||
|
VALUE "OriginalFilename", "GC-UI.exe" "\0"
|
||||||
|
VALUE "ProductName", "Morris GC" "\0"
|
||||||
|
VALUE "ProductVersion", VERSION_AS_STRING "\0"
|
||||||
|
END
|
||||||
|
END
|
||||||
|
BLOCK "VarFileInfo"
|
||||||
|
BEGIN
|
||||||
|
VALUE "Translation", 0x409, 1252
|
||||||
|
END
|
||||||
|
END
|
||||||
|
|
||||||
|
#endif // English (United States) resources
|
||||||
|
/////////////////////////////////////////////////////////////////////////////
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
#ifndef APSTUDIO_INVOKED
|
||||||
|
/////////////////////////////////////////////////////////////////////////////
|
||||||
|
//
|
||||||
|
// Generated from the TEXTINCLUDE 3 resource.
|
||||||
|
//
|
||||||
|
|
||||||
|
|
||||||
|
/////////////////////////////////////////////////////////////////////////////
|
||||||
|
#endif // not APSTUDIO_INVOKED
|
||||||