refactor: 全窗口统一 Avalonia,移除 Flutter/Dart,新增 Java 实现
PR 审核 / 后端编译 (pull_request) Waiting to run
PR 审核 / 前端检查(Flutter) (pull_request) Waiting to run
PR 审核 / 安全扫描 (pull_request) Waiting to run

- 恢复同代 GC Avalonia 主界面(主页/下载/设置/关于)替换 Flutter
- 模型窗口统一 Avalonia;HTML 课件用 WebView.Avalonia 内嵌渲染
- 新增 CoursewareServer(回环 HTTP + Range)与 CoursewareWindow
- 彻底移除 Flutter/Dart 前端及构建脚本相关逻辑
- 新增 ./build.sh run 开发运行命令
- 项目源码整理到 C#/ 子目录,新增 Java/ 实现
- 工作日志随项目迁移
This commit is contained in:
Morris committed 2026-11-27 10:09:30 +08:00
1 parent 3f1f48f54c
commit cf05e886ac
405 files changed
+18226 -19263

No files matched your search

+3
View File
@@ -68,3 +68,6 @@ courseware/
# 工具链临时备份
buildsh/cross/*.cmake.bak
# Gradle 全局缓存(不是项目文件)
.gradle-home/
+8
View File
@@ -328,3 +328,11 @@ mingw-w64 14.0.0_3 携带 GCC 16.2,与 Flutter 插件(flutter_inappwebview_w
2. 签到用 DateTime.UtcNow.Date → 东八区早上 8 点才算新一天,7 点前可同日签到两次
- 修:UserService 4 处 + UserPayload 1 处改 DateTime.Today(本地日历日);人品值/二选一跨天计数一并修
- 实测(本地 07:33 / UTC 07-21):last_sign_in=2026-11-22,重复签到被拒,人品值按本地日重置
## build-bot version 参数 + macOS 提速 + XHGit PR #40(11-22 08:00)
- 需求:`@build-bot build mac version=1.1.3` 编指定版本;mac 大小写不敏感;提速 Mac 编译
- build-bot.yml:prepare 解析 `version=x.y.z`(grep -oiE,大小写不敏感)→ 覆盖 props 版本 → 透传给 build.sh/build.ps1;回帖和 Release notes 显示版本
- 提速:两个工作流 mac job 都加 actions/cache(NuGet packages + CocoaPods Pods/Caches),runner 从 macos-latest 固定 macos-14 原生 arm64
- 脚本层已有并行(Flutter ‖ dotnet publish)+ dt_tool 缓存 + _trash,未重复改
- 提交 8b4cabb(分支 ci/buildbot-mac-speed),推 origin2 后经 Gitea API 创建 PR #40 → main(mergeable=true)
- PR 创建方式:git credential fill 拿账号密码 → curl -u basic auth POST /api/v1/repos/Morris/GC/pulls(token 方式 401,basic auth 201)
@@ -15,7 +15,7 @@
<ImplicitUsings>disable</ImplicitUsings>
<MvvmVersion>8.2.2</MvvmVersion>
<!-- 模型窗口仍由 Avalonia 承载(模型契约返回 Avalonia Control),
界面本身是 Flutter。Avalonia.BuildServices 的遥测会向用户目录写日志,
所有界面由 Avalonia 承载。Avalonia.BuildServices 的遥测会向用户目录写日志,
在只读目录 / CI 里会直接让编译失败,build.sh / build.ps1 已默认关闭。 -->
<AvaloniaVersion>11.3.9</AvaloniaVersion>
<Version>1.1.2</Version>
File renamed without changes.
@@ -20,7 +20,6 @@
<ItemGroup>
<ProjectReference Include="..\GC\src\GC.Core.csproj" />
<ProjectReference Include="..\GC-DOWNLOAD\GC-DOWNLOAD.csproj" />
<ProjectReference Include="..\GC-UI\backend\GC.UI.Server\GC.UI.Server.csproj" />
</ItemGroup>
</Project>
+10 -6
View File
@@ -1,4 +1,6 @@
using System;
using Avalonia;
using Avalonia.WebView.Desktop;
using GC.Services;
using GC.Download;
@@ -20,11 +22,13 @@ internal static class Program
// 上次下载的启动器新版,到这次启动才应用
if (DownloadModuleHost.Factory.TryApplyPending(paths)) return;
// 界面只有 Flutter 一套(内置 Avalonia 界面已移除)。
if (FlutterShell.TryRun(args)) return;
// 找不到前端:给出明确提示后退出,不要静默启动一个没有界面的后端进程。
FlutterShell.ReportMissingUi();
Environment.Exit(1);
// 所有界面统一由 Avalonia 承载(主窗口 / 模型窗口 / 课件),不再依赖 Flutter。
BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
}
public static AppBuilder BuildAvaloniaApp()
=> AppBuilder.Configure<App>()
.UsePlatformDetect()
.UseDesktopWebView()
.LogToTrace();
}
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -502,7 +502,7 @@ internal sealed class Applier
/// <summary>
/// 把 <paramref name="stage"/> 的内容替换进 <paramref name="installDir"/>。
///
/// 发布包是「整目录」(启动器 + 后端运行时 + Flutter 前端资源),只搬一个 exe 会留下
/// 发布包是「整目录」(启动器 + 后端运行时 + 课件资源),只搬一个 exe 会留下
/// 旧后端 / 旧界面,所以这里按目录整体替换:
/// 1. 安装目录里「新版没有」的条目 → 移到 backup(旧版本残留,如上一版的旧文件名);
/// 2. 与新版同名的条目 → 先移到 backup,再把新版放进来(覆盖正在被占用的文件会失败,
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
+200
View File
@@ -0,0 +1,200 @@
# GC 多语言完整版统一规范
本文件定义 6 种语言重写版必须遵守的**结构**、**功能**、**模型算法**契约。
源码仓库根目录的 `GC/`、`GC-DOWNLOAD/`、`GC-SAVEDOG/`、`model/` 保持不动。
## 1. 目录结构(6 语言一致)
```
GC-<语言>/
README.md 说明 + 构建方式 + 与原仓库的对应关系
build.sh 一键编译脚本,产出 gcctl 可执行文件
src/
core/ 启动器核心(路径/设置/哈希/JSON/版本/模型扫描/安全/日志)
models/ 5 个教学模型(与 model/ 下模型一一对应)
main.<ext> 统一 CLI 入口,单进程承载全部功能(禁止前后端分离)
gcctl 编译产物(可执行文件)
```
语言与扩展名:C++ → `.cpp`,Rust → `.rs`,Go → `.go`,Java → `.java`,Zig → `.zig`,C → `.c`。
## 2. 功能清单(6 语言一致)
### 2.1 启动器核心 core
| 功能 | 命令 | 行为契约 |
|---|---|---|
| 文件哈希 | `hash-file <path>` | SHA-256 小写十六进制 |
| 目录指纹 | `hash-dir <path>` | 相对路径 `/` 分隔,按 ordinal 升序,拼接 `<path>\0<sha256>\n` 后取 SHA-256;跳过隐藏文件、`bin/`、`obj/`、`*.user` |
| 规范化 JSON | `canonical <file\|->` | 对象键递归升序、无空白、UTF-8、非 ASCII 不转义、移除根级 `signature` |
| 版本规整 | `version-normalize <tag>` | 去 `GCL-/GC-/release-/v/V` 前缀,只留开头数字与点 |
| 版本比较 | `version-compare <a> <b>` | 输出 -1 / 0 / 1 |
| 路径布局 | `paths [root]` | 打印 `.GC/{bin,config,model,cache,update,safedog,logs}` 与 `config/settings.json` |
| 默认设置 | `settings-default` | 输出默认 `settings.json`(language=auto, theme=light, fps=120, mem=2048, source=xhmcl) |
| 模型扫描 | `model-scan <root>` | 扫描 `<root>/<id>/<id>.json`,按 id 排序,输出 `id\tversion\tname\tsize\tdir` |
| 安全路径 | `safezip-name <name>` | 拒绝绝对路径、`../`、盘符、UNC、空名,输出 OK/REJECT |
| 人类体积 | `human-size <bytes>` | B/KB/MB/GB,`1536 → 1.5 KB` |
| 自检 | `selftest` | 运行所有内置断言,全部 PASS 退出码 0 |
### 2.2 教学模型 models(功能一致,下载可不一致)
| 模型 | 对应原仓库 | 必须实现的功能(命令) |
|---|---|---|
| 比例尺 | `model/scale-calculator` | `model scale solve <mode> <mapCm> <realCm> <N>`(mode=real/map/scale)、`model scale human <cm>`、`model scale segment <N> <pxPerCm> <targetPx>`、`model scale grade <N>`、`model scale spectrum <N>`、`model scale quiz <seed>`、`model scale check <answer> <expect>` |
| 等高线 | `model/contour-map` | `model contour build <kind\|landform> [size]`(生成高度场)、`model contour sample <kind> <u> <v>`、`model contour levels <kind>`、`model contour extract <kind> <level>`(Marching Squares 折线数)、`model contour classify <kind> <u> <v>`、`model contour color <height>`、`model contour slope <kind> <u> <v>` |
| 地球自转 | `model/earth-rotation` | `model rotation subsolar <orbitDeg> <tiltDeg>`(太阳直射纬度)、`model rotation date <orbitDeg>`、`model rotation angle <spinDeg> <orbitDeg>` |
| 地球公转 | `model/earth-revolution` | `model revolution subsolar <orbitDeg>`、`model revolution season <orbitDeg>`(最近节气)、`model revolution step <spinDeg> <orbitDeg> <dt> <speed>` |
| 地理 | `model/earth-geography` | `model geo zones`(五带边界)、`model geo declination <lat>`(五带判定)、`model geo latlon <lat> <lon>`(单位向量) |
**模型算法必须与 C# 源码逐字等价**(见 SPEC 附录的公式)。
## 3. 一致性硬性要求
1. **结构一致**:6 个目录的 `src/core`、`src/models`、`main`、`build.sh` 一一对应。
2. **功能一致**:所有 CLI 命令在 6 语言都实现;同一输入必须给出同一输出(允许浮点末位差异)。
3. **禁止前后端分离**:单进程 CLI,无 HTTP 服务、无 Flutter 前端;模型功能直接链接进主程序。
4. **下载可不一致**:`model download` 允许各语言用各自 HTTP 实现,不作为一致性校验项。
5. **模型功能一致**:5 个模型的算法与输出在 6 语言完全一致。
## 4. 统一自检向量(必须全部 PASS)
```
hash-file("hello") = 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
hash-dir(a.txt="hello") = ed54360a4d7244bfcde6dca611fd00dbfbdf508c47ad104b711f8429a6d2604d
version-normalize("GCL-v1.0.6-beta") = 1.0.6
version-compare(v1.0.6, 1.0.7) = -1
canonical({"b":1,"a":"中文"}) = {"a":"中文","b":1}
safezip-name("../x") = REJECT;safezip-name("a/b.txt") = OK
human-size(1536) = 1.5 KB
scale solve(real, 3, 0, 100000) → realCm = 300000
scale human(300000) → 3 km
scale grade(100000) = large;grade(500000) = medium;grade(10000000) = small
contour levels(mountain) 含 100 的倍数;extract 返回折线数 > 0
rotation subsolar(90, 23.5) = 23.5;subsolar(0, 23.5) = 0
revolution season(90) = summerSolstice
geo declination(40) = northTemperate;declination(0) = tropics
```
## 5. 附录:模型核心公式(源自 C# 源码)
### 比例尺 ScaleMath
- `Solve`: real = mapCm*N;map = realCm/N;scale N = realCm/mapCm
- `HumanReal(cm)`: <100 → cm;<100000 → 米(cm/100);否则公里(cm/100000)
- `PickSegment`: 在 `1/2/5×10^k (k=-3..9)` 里选 `|log10(cand)-log10(ideal)|` 最小,`ideal=targetPx*N/(100*pxPerCm)`
- `Grade`: N≤100000 large;≤1000000 medium;else small
- `SpectrumPosition`: clamp((log10(N)-3)/6, 0, 1)
### 等高线 TerrainField / TerrainAnalyzer
- 山峰高度场:`h = 120 + Σ H_i*exp(-d²*1.15)`,d=((u-U)/RU,(v-V)/RV)
- 等高距:plain=5, hill=10, 其他=100
- Marching Squares:角点 h00,h10,h11,h01 组成 4bit 索引,10 种情形连线段,再按端点连通性串折线
- `Classify`: 先查 Tags 标注区,再按 slope>8.5=cliff、局部最大=peak、鞍部、横切曲率 <−0.55=ridge />0.55=valley
- `ColorForHeight`: 200m 一档,9 级固定 RGB
### 地球 CelestialView
- `SubsolarLatitude(revolution) = asin(sin(tilt°)*sin(orbit°)) * 180/π`(tilt 默认 23.5)
- 角度推进:`spin = (spin + dt*speed*60) % 360`;`orbit = (orbit + dt*speed*12) % 360`
- `DateForAngle(deg)`: `2025-01-01 + (79 + deg/360*365.2422) 天`
- 节气:0°春分 / 90°夏至 / 180°秋分 / 270°冬至
- `LatLonToUnit`: `(cosLat*sinLon, sinLat, cosLat*cosLon)`
### 地理 GeoModels
- 五带:热带 |lat|<23.5、温带 23.5≤|lat|<66.5、寒带 |lat|≥66.5
---
## 6. GUI 层规范(追加,用户要求完整图形界面)
所有 6 个语言版本必须提供**真原生图形界面**,单进程、不前后端分离。SDL2 统一图形层(用户选定)。
### 6.1 运行方式
```
./gcctl # 无参数 = 启动 GUI 主窗口(替代原 CLI 的默认 help 行为)
./gcctl gui # 显式启动 GUI
./gcctl <cli命令> # 保留全部 CLI 命令(自检、批处理仍可用)
./gcctl selftest # 自检仍为纯命令行
```
**注意**:为保持与已完成的 20 项 CLI 自检一致,`selftest` 不启动 GUI。GUI 有独立的 `gui-selftest`(可选)。
### 6.2 GUI 窗口结构(6 语言一致)
单窗口、顶部标签页切换 5 个模型 + 启动器首页:
```
┌──────────────────────────────────────────────┐
│ GC 天文教学模型 [首页][比例尺][等高线][自转][公转][地理] │ ← 标签栏
├──────────────────────────────────────────────┤
│ │
│ 模型画布 / 内容区 │ ← 用 SDL2 绘制
│ │
├──────────────────────────────────────────────┤
│ [◀][⏸/▶][▶] 速度:1x 状态栏 │ ← 控制栏(动画模型)
└──────────────────────────────────────────────┘
```
### 6.3 五个模型的 GUI 交互(完整交互,与原仓库对等)
| 标签 | 画面 | 交互 | 调用的 core/models 函数 |
|---|---|---|---|
| 首页 | 模型卡片列表 + 状态 | 点击卡片切换标签 | `ScanModels` |
| 比例尺 | 线段比例尺 + 数字/文字式 | 输入 mapCm/realCm/N,切换求解模式,实时重绘 | `ScaleSolve`, `PickSegment`, `Grade` |
| 等高线 | 高度场分层设色 + 等高线 | 切换 5 种地形/5 种地貌,鼠标悬停显示海拔与判读结果 | `TerrainField`, `ExtractContour`, `Classify` |
| 自转 | 地球球体 + 晨昏线 + 直射点 | 播放/暂停、拖动旋转、速度调节、显示赤纬 | `StepAngles`, `SubsolarLatitude` |
| 公转 | 轨道 + 四季标记 + 地球 | 播放/暂停、跳到节气、显示直射纬度 | `SubsolarLatitude`, `NearestSeason`, `DateForAngle` |
| 地理 | 经纬网 + 五带 | 鼠标悬停经纬度 → 高亮所属温度带 | `LatLonToUnit`, `Declination` |
### 6.4 各语言的 SDL2 接入
SDL2 framework 已安装到 `~/Library/Frameworks/SDL2.framework`(用户目录,未写 Homebrew)。
| 语言 | 接入方式 | 编译参数 |
|---|---|---|
| C | 直接 include | `-F "$HOME/Library/Frameworks" -framework SDL2` |
| C++ | 直接 include | 同 C |
| Zig | `@cImport` | `-F ... -framework SDL2` |
| Rust | `sdl2` crate(link framework) | `SDL2_FRAMEWORK` 环境变量 + build.rs |
| Go | cgo 直接调 SDL2 C API | `#cgo CFLAGS: -F.../Frameworks` `#cgo LDFLAGS: -framework SDL2` |
| Java | Swing(JDK 标准库,SDL2 通过 JNI 可选) | 无需 SDL2,用 Swing 实现同等 GUI |
Java 例外说明:Java 生态原生 GUI 是 Swing/AWT(JDK 自带、跨平台、零依赖),比 JNI 包 SDL2 更稳定,GUI 行为与 SDL2 版一致。
### 6.5 GUI 与 CLI 共享同一套模型算法
GUI 只负责绘制和交互,**所有计算调用 `src/models` 和 `src/core` 的同一函数**,保证 GUI 与 CLI 输出一致(例如 GUI 比例尺窗口显示的数值 == `gcctl model scale solve` 的输出)。禁止在 GUI 里另写一套算法。
### 6.6 动画
- 自转/公转用 SDL2 定时器(约 60 FPS)驱动 `StepAngles`,每帧重绘
- 播放/暂停/速度按钮控制 `speed` 参数
- 全局变量帧计数器显示在状态栏(便于自检)
### 6.7 SDL2 关键编译配置(已验证,直接复用)
SDL2 framework 已装到 `~/Library/Frameworks/SDL2.framework`,头文件软链已建:`~/.local/sdl2inc/SDL2 -> ~/Library/Frameworks/SDL2.framework/Headers`。
**已验证的 Go cgo 配置**(`sdl_probe` 通过,`SDL_Init(VIDEO)=0`):
```go
/*
#cgo CFLAGS: -I/Users/mmm/.local/sdl2inc
#cgo LDFLAGS: -F/Users/mmm/Library/Frameworks -framework SDL2 -Wl,-rpath,/Users/mmm/Library/Frameworks
#include <SDL2/SDL.h>
*/
import "C"
```
要点:
1. framework 内部头用 `SDL2/xxx.h` 互相引用,所以 include 路径必须是 `~/.local/sdl2inc`(其下有 `SDL2/` 软链),不能用 `SDL2.framework/Headers` 直接作为 `-I`。
2. 运行时必须加 `-Wl,-rpath,/Users/mmm/Library/Frameworks`,否则 dyld 报 `Library not loaded: @rpath/SDL2.framework`。
3. C/C++/Zig 编译同样加 `-I/Users/mmm/.local/sdl2inc -F/Users/mmm/Library/Frameworks -framework SDL2 -Wl,-rpath,/Users/mmm/Library/Frameworks`。
4. Rust `sdl2` crate 若走 framework,需设 `SDL2_FRAMEWORK=/Users/mmm/Library/Frameworks/SDL2.framework`,并保证 rpath。若 crate 链接困难,改用 `std::process::Command` 调用一个极简 C shim(但优先 crate)。
### 6.8 macOS 主线程要求(重要)
macOS Cocoa 要求所有 UI 调用发生在主线程,否则崩溃:
`NSInternalInconsistencyException: nextEventMatchingMask should only be called from the Main Thread!`
- **Go**:`RunGUI()` 开头必须 `runtime.LockOSThread()`(已验证)
- **C/C++/Zig/Rust/Java**:原生程序主线程天然是 UI 线程,无此问题
- 冒烟测试:`./gcctl gui` 后台运行 3 秒后 kill,无异常输出即通过
View File
File renamed without changes.
File renamed without changes.
@@ -4,7 +4,7 @@ namespace GC.UI.Server;
// ---------------------------------------------------------------------------
// 前后端之间的数据契约(HTTP + JSON,camelCase)。
// 前端(Flutter)只认这些字段,不认 .NET 类型;后端换实现不影响前端。
// HTTP 客户端只认这些字段,不认 .NET 类型;后端换实现不影响契约。
// ---------------------------------------------------------------------------
public sealed record HealthDto(
@@ -16,9 +16,9 @@ namespace GC.UI.Server;
/// 模型窗口宿主。
///
/// 为什么渲染这一层留在 .NET:模型 dll 通过 <c>IModelRuntime.CreateView</c> 返回的是
/// Avalonia <see cref="Control"/>,这是模型契约的一部分。把渲染栈换成 Flutter 等于换掉契约,
/// Avalonia <see cref="Control"/>,这是模型契约的一部分。换掉渲染栈等于换掉契约,
/// 所有已发布模型都会失效。所以前后端分离的切法是:
/// · 界面(首页 / 下载 / 设置 / 关于)→ Flutter 前端
/// · 界面(首页 / 下载 / 设置 / 关于)→ Avalonia 主窗口
/// · 模型窗口(模型自带界面)→ 仍由 .NET 承载,前端只发一条「启动模型」的指令
///
/// 这里惰性启动一个没有主窗口的 Avalonia 桌面生命周期,之后所有模型窗口都在它的 UI 线程上创建。
@@ -36,7 +36,7 @@ public static class BackendServer
/// 构建后端。返回的 <see cref="WebApplication"/> 尚未启动:
/// 独立进程直接 <c>Run()</c>,启动器用 <c>StartAsync()</c> 之后继续拉起界面。
///
/// 界面是 Flutter,但**模型窗口仍由 Avalonia 承载**(模型契约返回的是 Avalonia Control)。
/// 主界面已是 Avalonia;本后端仅用于独立 HTTP 部署场景。
/// </summary>
public static WebApplication Start(string[] args, int port)
=> Start(args, port, out _);
@@ -73,7 +73,7 @@ public static class BackendServer
});
// 桌面端(Windows/macOS)走原生 HTTP,不需要 CORS;
// 这里放开本机回环来源,方便用 `flutter run -d chrome` 调试界面。
// 这里放开本机回环来源,方便本地调试客户端。
builder.Services.AddCors(options => options.AddDefaultPolicy(policy => policy
.SetIsOriginAllowed(origin =>
Uri.TryCreate(origin, UriKind.Absolute, out var uri) &&
@@ -415,7 +415,7 @@ app.MapGet("/api/health", () => Results.Ok(new HealthDto(
return Results.File(package.PreviewPath, GuessImageContentType(package.PreviewPath));
});
// 模型改为客户端内渲染(Flutter):这里只确认模型存在并把 id 交回去,
// 模型由客户端渲染:这里只确认模型存在并把 id 交回去,
// 不再拉起 Avalonia 窗口。保留接口是为了老客户端不至于 404。
app.MapPost("/api/models/{id}/launch", async (string id) =>
{
@@ -689,7 +689,7 @@ app.MapGet("/api/health", () => Results.Ok(new HealthDto(
contributors,
// 「关于」页展示的技术栈信息:源码语言与前端框架。
SourceLanguage: "C#",
Frontend: "Flutter"));
Frontend: "Avalonia"));
});
// ---- 系统集成 -------------------------------------------------------------
@@ -3,9 +3,9 @@
<!--
GC-UI 后端:把原来「启动器 = UI + 服务」的一体式结构拆成
· 后端(本工程):模型扫描 / 下载 / 更新 / 设置 / 模型窗口宿主,只暴露本地 HTTP API
· 前端(GC-UI/frontend,Flutter):只做界面,通过 HTTP 调后端
· HTTP 客户端:通过 HTTP 调用本后端(可选部署)
模型渲染也已并入 Flutter(lib/models/):模型不再返回 Avalonia Control,
模型渲染由客户端负责:模型不再返回 Avalonia Control,
后端只剩纯 HTTP API,不再依赖任何 UI 框架。
-->
<PropertyGroup>
@@ -4,5 +4,5 @@ using GC.UI.Server;
// 启动器在进程内直接调用 BackendServer.Start,不会走到这里。
var app = BackendServer.StartFromCommandLine(args);
// 纯 HTTP 后端(模型渲染在 Flutter 客户端里),跑起来常驻即可。
// 纯 HTTP 后端(供独立部署 / 外部客户端使用),跑起来常驻即可。
app.Run();
View File
File renamed without changes.
+48
View File
@@ -0,0 +1,48 @@
<Application xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="using:GC.ViewModels"
xmlns:views="using:GC.Views"
x:Class="GC.App"
RequestedThemeVariant="Light">
<Application.DataTemplates>
<DataTemplate DataType="{x:Type vm:HomeViewModel}">
<views:HomeView />
</DataTemplate>
<DataTemplate DataType="{x:Type vm:DownloadViewModel}">
<views:DownloadView />
</DataTemplate>
<DataTemplate DataType="{x:Type vm:SettingsViewModel}">
<views:SettingsView />
</DataTemplate>
<DataTemplate DataType="{x:Type vm:AboutViewModel}">
<views:AboutView />
</DataTemplate>
</Application.DataTemplates>
<Application.Resources>
<Color x:Key="SystemAccentColor">#2F6BFF</Color>
<!--
FluentTheme 的按钮模板在 :pointerover / :pressed 时会用这些主题资源
覆盖 ContentPresenter 的画刷。若与 AppTheme.axaml 里通过 Button 属性
设置的 hover 颜色不一致,两套机制会互相覆盖,导致光标移动时渲染错乱。
这里把它们统一指向与按钮样式相同的颜色。
-->
<SolidColorBrush x:Key="ButtonBackgroundPointerOver">#EDF2FC</SolidColorBrush>
<SolidColorBrush x:Key="ButtonBackgroundPressed">#DDE7F8</SolidColorBrush>
<SolidColorBrush x:Key="ButtonBorderBrushPointerOver">#BAC9E6</SolidColorBrush>
<SolidColorBrush x:Key="ButtonBorderBrushPressed">#9FB4DD</SolidColorBrush>
<SolidColorBrush x:Key="ButtonForegroundPointerOver">#111A2E</SolidColorBrush>
<SolidColorBrush x:Key="ButtonForegroundPressed">#111A2E</SolidColorBrush>
<SolidColorBrush x:Key="AccentButtonBackground">#2F6BFF</SolidColorBrush>
<SolidColorBrush x:Key="AccentButtonBackgroundPointerOver">#1F4FD0</SolidColorBrush>
<SolidColorBrush x:Key="AccentButtonBackgroundPressed">#183FA8</SolidColorBrush>
</Application.Resources>
<Application.Styles>
<FluentTheme />
<StyleInclude Source="avares://GC.Core/Styles/AppTheme.axaml" />
</Application.Styles>
</Application>
+141
View File
@@ -0,0 +1,141 @@
using System;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Markup.Xaml;
using GC.Services;
using GC.ViewModels;
using GC.Views;
namespace GC;
public partial class App : Application
{
public override void Initialize() => AvaloniaXamlLoader.Load(this);
/// <summary>初始化课件 WebView(macOS WKWebView / Windows WebView2 / Linux WebKitGTK)。</summary>
public override void RegisterServices()
{
base.RegisterServices();
AvaloniaWebView.AvaloniaWebViewBuilder.Initialize(default!);
}
public override void OnFrameworkInitializationCompleted()
{
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{
var services = AppServices.Create();
// 诊断模式:只验证模型程序集能否加载(发布包里也用它做冒烟测试)
if (Environment.GetEnvironmentVariable("EMS_SELFTEST") == "1")
{
var code = SelfTest(services);
Avalonia.Threading.Dispatcher.UIThread.Post(
() => desktop.Shutdown(code), Avalonia.Threading.DispatcherPriority.Background);
return;
}
// 启动加速:先建空窗口并显示,再在首帧之后构造 ViewModel。
// MainViewModel 会扫描模型、加载封面、读设置,同步做会让
// 「双击到看见窗口」明显变慢;先出窗口,内容随后填充。
var window = new MainWindow();
window.Show();
// 健康标记:GC-SAVEDOG 正在等这个文件。主窗口能显示出来,
// 就说明「新版本确实能启动」,它据此决定保留新版还是回滚。
StartupHealth.MarkHealthy(services.Paths.UpdateRoot,
LauncherRuntimeInfo.CurrentLauncherVersion);
// 首帧之后再构造 ViewModel:Post 而非依赖 Opened,
// 因为 Opened 在某些情况下不触发(headless / 部分平台),
// 会导致 DataContext 一直是 null、主页面白屏。
// 扫描模型 / 加载封面在后台线程做,UI 线程只负责赋值,
// 这样窗口能立刻响应,不会卡在白屏。
MainViewModel vm = null!;
Task.Run(() => new MainViewModel(services))
.ContinueWith(t =>
{
vm = t.Result;
Avalonia.Threading.Dispatcher.UIThread.Post(() =>
{
window.DataContext = vm;
WireMainViewModel(vm, window, services, desktop);
}, Avalonia.Threading.DispatcherPriority.Background);
}, System.Threading.Tasks.TaskScheduler.Default);
// 应用图标不依赖 ViewModel,先设好让窗口一出现就有图标
try
{
using var iconStream = Avalonia.Platform.AssetLoader.Open(
new Uri("avares://GC.Core/Assets/icon.png"));
window.Icon = new Avalonia.Controls.WindowIcon(iconStream);
}
catch { /* 图标缺失不影响启动 */ }
desktop.MainWindow = window;
desktop.ShutdownMode = ShutdownMode.OnMainWindowClose;
}
base.OnFrameworkInitializationCompleted();
}
/// <summary>
/// 主窗口显示后再接上 ViewModel:绑定对话框、启动后台更新检查。
/// 拆出来是为了让窗口先出现,模型扫描不影响「双击到出窗口」。
/// </summary>
private static void WireMainViewModel(MainViewModel vm, MainWindow window,
AppServices services, IClassicDesktopStyleApplicationLifetime desktop)
{
_ = desktop;
vm.ConfirmHandler = async message =>
{
var dialog = new ConfirmWindow(message);
return await dialog.ShowDialog<bool>(window);
};
// 发现启动器新版本:弹窗询问,用户选「更新」才下载并安排替换
vm.LauncherUpdateHandler = async newVersion =>
{
var dialog = new ConfirmWindow(
title: "发现新版本",
message: $"启动器有新版本 v{newVersion},是否立即更新?\n\n" +
"更新会下载新版程序,下次启动时自动替换当前版本;" +
"选择取消则继续使用当前版本,但模型仍会更新到最新。",
confirmText: "更新",
cancelText: "取消");
return await dialog.ShowDialog<bool>(window);
};
// 主窗口已显示,后台检查模型 / 启动器更新,不阻塞界面
if (Environment.GetEnvironmentVariable("EMS_NO_UPDATE") != "1")
{
Avalonia.Threading.Dispatcher.UIThread.Post(
() => _ = vm.RunStartupUpdateAsync(),
Avalonia.Threading.DispatcherPriority.Background);
}
}
/// <summary>逐个加载模型,打印结果;返回退出码(0 = 全部成功)。</summary>
private static int SelfTest(AppServices services)
{
var packages = services.Models.Scan();
Console.WriteLine($"模型库: {services.Paths.ModelRoot}");
Console.WriteLine($"模型数: {packages.Count}");
var failed = 0;
foreach (var package in packages)
{
try
{
using var loaded = services.ModelHost.Load(package, () => { });
Console.WriteLine($"OK {package.Id} -> {loaded.View.GetType().FullName}");
}
catch (Exception ex)
{
failed++;
Console.WriteLine($"FAIL {package.Id}: {ex.Message}");
}
}
return failed == 0 ? 0 : 1;
}
}
@@ -7,6 +7,7 @@
"nav.download": "Download",
"nav.settings": "Settings",
"nav.about": "About",
"nav.courseware": "Contour Course",
"home.title": "Model library",
"home.subtitle": "Pick a model and explain rotation, revolution and the seasons with an interactive 3D scene.",
"home.launch": "Launch model",
@@ -7,6 +7,7 @@
"nav.download": "下载",
"nav.settings": "设置",
"nav.about": "关于",
"nav.courseware": "等高线课件",
"home.title": "模型库",
"home.subtitle": "选择模型,用可交互的三维演示讲清自转、公转与四季成因。",
"home.launch": "启动模型",
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -9,14 +9,13 @@
</PropertyGroup>
<ItemGroup>
<!-- 界面仍是 Flutter,但模型由 Avalonia 承载(模型契约返回 Avalonia Control),
所以核心库需要 Avalonia + 模型 SDK,并把 GC-DRAW 的窗口一起编译进来。 -->
<!-- 所有界面由 Avalonia 承载(主窗口 / 模型窗口 / 课件 WebView),
核心库包含 UI + 模型 SDK,并把 GC-DRAW 的播放器窗口一起编译进来。 -->
<Compile Include="..\..\GC-DRAW\PlayerWindow.cs" />
<Compile Remove="test\**\*.cs" />
<AvaloniaResource Include="Assets\**" />
<!-- 多语言表原先通过 Avalonia 的 avares:// 读取,改为嵌入资源 -->
<EmbeddedResource Include="Assets\i18n\*.json"
LogicalName="GC.Core.Assets.i18n.%(Filename)%(Extension)" />
<EmbeddedResource Include="Assets\i18n\*.json" LogicalName="GC.Core.Assets.i18n.%(Filename)%(Extension)" />
</ItemGroup>
<ItemGroup>
@@ -24,6 +23,8 @@
<PackageReference Include="Avalonia.Desktop" Version="$(AvaloniaVersion)" />
<PackageReference Include="Avalonia.Themes.Fluent" Version="$(AvaloniaVersion)" />
<PackageReference Include="CommunityToolkit.Mvvm" Version="$(MvvmVersion)" />
<PackageReference Include="WebView.Avalonia" Version="11.0.0.1" />
<PackageReference Include="WebView.Avalonia.Desktop" Version="11.0.0.1" />
</ItemGroup>
<ItemGroup>
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
+158
View File
@@ -0,0 +1,158 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace GC.Services;
/// <summary>
/// 等高线课件本地静态服务器。
///
/// 课件是 HTML+CSS+JS+视频,直接用 file:// 加载会被 WebView 的同源策略拦住
/// (视频 Range 请求、fetch 本地资源都会失败),所以起一个只监听回环地址的
/// 微型 HTTP 服务器,端口自动分配,支持 Range 以便视频拖动。
///
/// 资源根目录优先取「可执行文件旁 courseware/」(发布布局),
/// 回退到用户目录下的 .GC/courseware/,开发时也能用。
/// </summary>
public sealed class CoursewareServer : IDisposable
{
private readonly HttpListener _listener = new();
private readonly string _root;
private bool _disposed;
public int Port { get; }
public string BaseUrl => $"http://127.0.0.1:{Port}/";
public CoursewareServer()
{
_root = FindRoot() ?? throw new DirectoryNotFoundException("找不到课件目录 courseware/");
// 端口 0 = 系统自动分配,避免与用户程序或后端冲突
Port = PickFreePort();
_listener.Prefixes.Add($"http://127.0.0.1:{Port}/");
_listener.Start();
_ = Task.Run(ServeLoop);
}
private static int PickFreePort()
{
var probe = new System.Net.Sockets.TcpListener(IPAddress.Loopback, 0);
probe.Start();
var port = ((IPEndPoint)probe.LocalEndpoint).Port;
probe.Stop();
return port;
}
private static string? FindRoot()
{
var candidates = new List<string>
{
Environment.GetEnvironmentVariable("GC_COURSEWARE_DIR") ?? "",
Path.Combine(AppContext.BaseDirectory, "courseware"),
Path.Combine(Directory.GetCurrentDirectory(), "courseware"),
};
try
{
var home = AppPaths.Discover().HomeRoot;
candidates.Add(Path.Combine(home, "courseware"));
}
catch { /* 目录探测失败时只看前两个候选 */ }
foreach (var dir in candidates)
if (File.Exists(Path.Combine(dir, "index.html"))) return dir;
return null;
}
private async Task ServeLoop()
{
while (!_disposed)
{
HttpListenerContext ctx;
try { ctx = await _listener.GetContextAsync(); }
catch { break; }
_ = Task.Run(() => Handle(ctx));
}
}
private void Handle(HttpListenerContext ctx)
{
try
{
var rel = Uri.UnescapeDataString(ctx.Request.Url!.AbsolutePath.TrimStart('/'));
if (string.IsNullOrEmpty(rel)) rel = "index.html";
rel = rel.Replace('/', Path.DirectorySeparatorChar);
// 规范化 + 越界检查:只允许读课件目录内的文件
var full = Path.GetFullPath(Path.Combine(_root, rel));
var rootFull = Path.GetFullPath(_root) + Path.DirectorySeparatorChar;
if (!full.StartsWith(rootFull, StringComparison.OrdinalIgnoreCase) ||
!File.Exists(full))
{
ctx.Response.StatusCode = 404;
ctx.Response.Close();
return;
}
var bytes = File.ReadAllBytes(full);
ctx.Response.ContentType = GuessMime(full);
ctx.Response.Headers.Add("Accept-Ranges", "bytes");
var range = ctx.Request.Headers["Range"];
if (!string.IsNullOrEmpty(range) &&
range.StartsWith("bytes=", StringComparison.OrdinalIgnoreCase) &&
range.Contains('-'))
{
var parts = range[6..].Split('-', 2);
long start = 0;
long end = bytes.Length - 1;
if (!string.IsNullOrEmpty(parts[0])) long.TryParse(parts[0], out start);
if (parts.Length > 1 && !string.IsNullOrEmpty(parts[1])) long.TryParse(parts[1], out end);
if (start >= 0 && start <= end && start < bytes.Length)
{
if (end >= bytes.Length) end = bytes.Length - 1;
var len = (int)(end - start + 1);
ctx.Response.StatusCode = 206;
ctx.Response.Headers.Add("Content-Range", $"bytes {start}-{end}/{bytes.Length}");
ctx.Response.ContentLength64 = len;
ctx.Response.OutputStream.Write(bytes, (int)start, len);
ctx.Response.Close();
return;
}
}
ctx.Response.ContentLength64 = bytes.Length;
ctx.Response.OutputStream.Write(bytes, 0, bytes.Length);
ctx.Response.Close();
}
catch
{
try { ctx.Response.Close(); } catch { /* 客户端已断开 */ }
}
}
private static string GuessMime(string path) => Path.GetExtension(path).ToLowerInvariant() switch
{
".html" or ".htm" => "text/html; charset=utf-8",
".css" => "text/css; charset=utf-8",
".js" => "application/javascript; charset=utf-8",
".json" => "application/json; charset=utf-8",
".jpg" or ".jpeg" => "image/jpeg",
".png" => "image/png",
".webp" => "image/webp",
".gif" => "image/gif",
".mp4" => "video/mp4",
_ => "application/octet-stream"
};
public void Dispose()
{
if (_disposed) return;
_disposed = true;
try { _listener.Stop(); _listener.Close(); } catch { /* 已关闭 */ }
}
}
@@ -156,10 +156,9 @@ public static class LauncherRuntimeInfo
}
/// <summary>
/// 界面(Flutter)与后端(GC.UI.Server)之间的约定:端口、环境变量名。
/// HTTP 后端(GC.UI.Server)的端口与令牌约定,供独立部署 / 外部客户端使用。
///
/// 之前这个端口在 GC-BOOT、后端、Flutter 前端各写了一遍 17890,改一处就断链;
/// 现在统一由这里定义,启动器选好端口后通过环境变量传给另外两边。
/// 主界面已改为进程内 Avalonia,不经过 HTTP;这些常量仅用于可选的独立后端进程。
/// </summary>
public static class GcUiContract
{
@@ -174,9 +173,9 @@ public static class GcUiContract
public const string PortEnvVar = "GC_UI_PORT";
/// <summary>
/// 启动器为本次会话生成的一次性令牌,经环境变量同时传给进程内后端与 Flutter 前端。
/// 前端每个请求都要带该令牌,后端据此确认对方是自己拉起的那个前端;
/// 同机伪装进程即便占了端口,也没有令牌,无法被前端当成后端复用。
/// 独立后端进程的一次性令牌,经环境变量传给 HTTP 客户端。
/// 客户端每个请求都要带该令牌,后端据此确认对方是自己拉起的;
/// 同机伪装进程即便占了端口,也没有令牌,无法被当成后端复用。
/// </summary>
public const string TokenEnvVar = "GC_UI_TOKEN";
File renamed without changes.
File renamed without changes.
+124
View File
@@ -0,0 +1,124 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Threading;
using GC.Views;
namespace GC.Services;
/// <summary>
/// 启动器更新的完整交互流程(「检查更新」与「重新下载启动器」共用):
/// 1. 关闭主窗口与所有模型窗口;
/// 2. 弹出圆角进度窗;
/// 3. 下载最新版到当前目录(与旧版并列);
/// 4. 安排替换脚本、关进度窗、退出进程。
/// 失败时恢复主窗口,继续使用当前版本。
/// </summary>
public static class LauncherUpdateFlow
{
private static bool _running;
public static bool IsRunning => _running;
public static async Task RunAsync(AppServices services, string title)
{
if (_running) return;
_running = true;
var desktop = Application.Current?.ApplicationLifetime
as IClassicDesktopStyleApplicationLifetime;
var mainWindow = desktop?.MainWindow;
var progressWindow = new UpdaterWindow(title);
try
{
// 1. 关闭所有窗口
if (desktop != null) desktop.MainWindow = null;
try { mainWindow?.Close(); } catch { }
foreach (var w in OpenWindows().ToList())
{
try { w.Close(); } catch { }
}
// 2. 进度窗
progressWindow.Show();
progressWindow.Report(0, "准备更新…");
await Dispatcher.UIThread.InvokeAsync(() => { }, DispatcherPriority.Render);
// 3. 下载
var progress = new Progress<UpdateProgressInfo>(p =>
progressWindow.Report(p.Value, p.Stage));
var result = await services.LauncherUpdates.DownloadAsync(
services.Paths, services.Updates.Remote, progress);
if (result.State == UpdateRunState.Failed)
{
progressWindow.Report(0, "更新失败", result.Message);
await Task.Delay(2200);
_running = false;
progressWindow.Close();
RestoreMainWindow(desktop, mainWindow);
return;
}
progressWindow.Report(1, $"v{result.Version} 下载完成,正在重启…");
// 4. 安排替换(下次启动生效 / 脚本接管重启)
var scheduled = services.LauncherUpdates.ScheduleApply(
services.Paths, result.PackageName ?? "");
if (!scheduled)
{
progressWindow.Report(0, "无法安排更新", "请检查安装目录是否可写");
await Task.Delay(2200);
_running = false;
progressWindow.Close();
RestoreMainWindow(desktop, mainWindow);
return;
}
await Task.Delay(400);
progressWindow.Close();
desktop?.Shutdown();
}
catch (Exception ex)
{
Console.Error.WriteLine($"更新流程异常: {ex}");
_running = false;
try { progressWindow.Close(); } catch { }
RestoreMainWindow(desktop, mainWindow);
}
}
private static void RestoreMainWindow(
IClassicDesktopStyleApplicationLifetime? desktop, Window? mainWindow)
{
if (desktop == null || mainWindow == null) return;
try
{
desktop.MainWindow = mainWindow;
mainWindow.Show();
mainWindow.Activate();
}
catch (Exception ex)
{
Console.Error.WriteLine($"恢复主窗口失败: {ex.Message}");
}
}
private static IEnumerable<Window> OpenWindows()
{
if (Application.Current?.ApplicationLifetime
is not IClassicDesktopStyleApplicationLifetime d)
yield break;
foreach (var w in d.Windows)
{
if (w is UpdaterWindow) continue;
yield return w;
}
}
}
@@ -4,6 +4,8 @@ using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Text.Json;
using Avalonia.Data;
using Avalonia.Markup.Xaml;
namespace GC.Services;
@@ -72,7 +74,7 @@ public sealed class L : INotifyPropertyChanged
{
try
{
// 界面已迁到 Flutter,这里不能再依赖 Avalonia 的 avares:// 资源加载
// 多语言表以嵌入资源方式加载(不依赖 avares:// 的外部文件)
var asm = typeof(L).Assembly;
using var stream = asm.GetManifestResourceStream($"GC.Core.Assets.i18n.{code}.json");
if (stream == null) return null;
@@ -130,3 +132,14 @@ public sealed class LocalizedString : INotifyPropertyChanged
internal void Refresh() => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Value)));
}
/// <summary>XAML 用法:Text="{loc:Loc nav.home}"</summary>
public sealed class LocExtension : MarkupExtension
{
public LocExtension() { }
public LocExtension(string key) => Key = key;
public string Key { get; set; } = "";
public override object ProvideValue(IServiceProvider serviceProvider)
=> new Binding(nameof(LocalizedString.Value)) { Source = L.I.For(Key) };
}
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
+325
View File
@@ -0,0 +1,325 @@
<Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Styles.Resources>
<SolidColorBrush x:Key="AppBg" Color="#F4F6FB" />
<SolidColorBrush x:Key="Surface" Color="#FFFFFF" />
<SolidColorBrush x:Key="SurfaceAlt" Color="#F7F9FE" />
<SolidColorBrush x:Key="Line" Color="#E3E8F3" />
<SolidColorBrush x:Key="LineStrong" Color="#D2DAEA" />
<SolidColorBrush x:Key="Ink" Color="#111A2E" />
<SolidColorBrush x:Key="InkDim" Color="#5B6A86" />
<SolidColorBrush x:Key="InkFaint" Color="#8A97B1" />
<SolidColorBrush x:Key="Accent" Color="#2F6BFF" />
<SolidColorBrush x:Key="AccentDark" Color="#1F4FD0" />
<SolidColorBrush x:Key="AccentSoft" Color="#EAF1FF" />
<SolidColorBrush x:Key="SideBg" Color="#0D1526" />
<SolidColorBrush x:Key="SideLine" Color="#1B2740" />
<SolidColorBrush x:Key="SideInk" Color="#A9B8D4" />
<SolidColorBrush x:Key="Success" Color="#1F9D6B" />
<SolidColorBrush x:Key="Danger" Color="#D64545" />
<SolidColorBrush x:Key="Warn" Color="#D98613" />
<LinearGradientBrush x:Key="HeroBg" StartPoint="0%,0%" EndPoint="100%,100%">
<GradientStop Color="#12203C" Offset="0" />
<GradientStop Color="#1A3057" Offset="0.55" />
<GradientStop Color="#0E1A31" Offset="1" />
</LinearGradientBrush>
<LinearGradientBrush x:Key="TitleBarBg" StartPoint="0%,0%" EndPoint="100%,100%">
<GradientStop Color="#101C33" Offset="0" />
<GradientStop Color="#0B1322" Offset="1" />
</LinearGradientBrush>
<LinearGradientBrush x:Key="SideBgBrush" StartPoint="0%,0%" EndPoint="0%,100%">
<GradientStop Color="#0E1729" Offset="0" />
<GradientStop Color="#0A1120" Offset="1" />
</LinearGradientBrush>
</Styles.Resources>
<Style Selector="Window">
<Setter Property="FontSize" Value="13" />
<Setter Property="Foreground" Value="{DynamicResource Ink}" />
</Style>
<!-- 文本 -->
<Style Selector="TextBlock.h1">
<Setter Property="FontSize" Value="26" />
<Setter Property="FontWeight" Value="SemiBold" />
<Setter Property="Foreground" Value="{DynamicResource Ink}" />
</Style>
<Style Selector="TextBlock.h2">
<Setter Property="FontSize" Value="16" />
<Setter Property="FontWeight" Value="SemiBold" />
<Setter Property="Foreground" Value="{DynamicResource Ink}" />
</Style>
<Style Selector="TextBlock.h3">
<Setter Property="FontSize" Value="13.5" />
<Setter Property="FontWeight" Value="SemiBold" />
<Setter Property="Foreground" Value="{DynamicResource Ink}" />
</Style>
<Style Selector="TextBlock.muted">
<Setter Property="FontSize" Value="12" />
<Setter Property="Foreground" Value="{DynamicResource InkDim}" />
</Style>
<Style Selector="TextBlock.faint">
<Setter Property="FontSize" Value="11.5" />
<Setter Property="Foreground" Value="{DynamicResource InkFaint}" />
</Style>
<Style Selector="TextBlock.eyebrow">
<Setter Property="FontSize" Value="11" />
<Setter Property="FontWeight" Value="SemiBold" />
<Setter Property="Foreground" Value="{DynamicResource InkFaint}" />
</Style>
<Style Selector="TextBlock.onDark">
<Setter Property="Foreground" Value="#EAF1FF" />
</Style>
<Style Selector="TextBlock.onDarkDim">
<Setter Property="Foreground" Value="#9DB0D0" />
</Style>
<!-- 容器 -->
<!-- 容器:卡片悬停浮起,阴影与位移都有过渡 -->
<Style Selector="Border.card">
<Setter Property="Background" Value="{DynamicResource Surface}" />
<Setter Property="BorderBrush" Value="{DynamicResource Line}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="CornerRadius" Value="16" />
<Setter Property="Transitions">
<Transitions>
<BoxShadowsTransition Property="BoxShadow" Duration="0:0:0.2" />
<BrushTransition Property="BorderBrush" Duration="0:0:0.2" />
<TransformOperationsTransition Property="RenderTransform" Duration="0:0:0.2" />
</Transitions>
</Setter>
</Style>
<Style Selector="Border.card:pointerover">
<Setter Property="BoxShadow" Value="0 10 26 0 #1A213C70" />
<Setter Property="BorderBrush" Value="{DynamicResource LineStrong}" />
<Setter Property="RenderTransform" Value="translateY(-2px)" />
</Style>
<Style Selector="Border.panel">
<Setter Property="Background" Value="{DynamicResource SurfaceAlt}" />
<Setter Property="BorderBrush" Value="{DynamicResource Line}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="CornerRadius" Value="12" />
</Style>
<Style Selector="Border.hero">
<Setter Property="Background" Value="{DynamicResource HeroBg}" />
<Setter Property="CornerRadius" Value="20" />
<Setter Property="BoxShadow" Value="0 12 32 0 #1A0B1A3A" />
</Style>
<Style Selector="Border.chip">
<Setter Property="Background" Value="{DynamicResource AccentSoft}" />
<Setter Property="CornerRadius" Value="999" />
<Setter Property="Padding" Value="8,2" />
</Style>
<Style Selector="Border.tag">
<Setter Property="Background" Value="#F0F3FA" />
<Setter Property="CornerRadius" Value="6" />
<Setter Property="Padding" Value="7,2" />
</Style>
<!-- ===================================================================
按钮(重写版)
原则:只通过 Button 自身的 Background/Foreground/BorderBrush + 伪类
设置来换色,一律不覆盖 /template/ ContentPresenter 的属性,也不使用
RenderTransform 动画。FluentTheme 的按钮模板通过 TemplateBinding 读取
这些属性,混用「Button 属性」与「模板内部元素属性」会在 hover 状态
切换时互相覆盖,造成光标移动时的渲染错乱。
所有过渡都是纯画刷过渡(BrushTransition),类型固定,不会转换失败。
=================================================================== -->
<Style Selector="Button">
<Setter Property="FontSize" Value="13" />
<Setter Property="Padding" Value="14,7" />
<Setter Property="MinHeight" Value="34" />
<Setter Property="CornerRadius" Value="9" />
<Setter Property="Background" Value="{DynamicResource Surface}" />
<Setter Property="BorderBrush" Value="{DynamicResource LineStrong}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="Foreground" Value="{DynamicResource Ink}" />
<Setter Property="HorizontalContentAlignment" Value="Center" />
<Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="Cursor" Value="Hand" />
<Setter Property="Transitions">
<Transitions>
<BrushTransition Property="Background" Duration="0:0:0.13" />
<BrushTransition Property="BorderBrush" Duration="0:0:0.13" />
<BrushTransition Property="Foreground" Duration="0:0:0.13" />
</Transitions>
</Setter>
</Style>
<!-- 通用 hover / pressed(纯色,无变换) -->
<Style Selector="Button:pointerover">
<Setter Property="Background" Value="#EDF2FC" />
<Setter Property="BorderBrush" Value="#BAC9E6" />
</Style>
<Style Selector="Button:pressed">
<Setter Property="Background" Value="#DDE7F8" />
<Setter Property="BorderBrush" Value="#9FB4DD" />
</Style>
<!-- 主要按钮 -->
<Style Selector="Button.primary">
<Setter Property="Background" Value="{DynamicResource Accent}" />
<Setter Property="BorderBrush" Value="{DynamicResource Accent}" />
<Setter Property="Foreground" Value="White" />
</Style>
<Style Selector="Button.primary:pointerover">
<Setter Property="Background" Value="{DynamicResource AccentDark}" />
<Setter Property="BorderBrush" Value="{DynamicResource AccentDark}" />
<Setter Property="Foreground" Value="White" />
</Style>
<Style Selector="Button.primary:pressed">
<Setter Property="Background" Value="#183FA8" />
<Setter Property="BorderBrush" Value="#183FA8" />
<Setter Property="Foreground" Value="White" />
</Style>
<!-- 幽灵按钮 -->
<Style Selector="Button.ghost">
<Setter Property="Background" Value="Transparent" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="BorderBrush" Value="Transparent" />
<Setter Property="Foreground" Value="{DynamicResource InkDim}" />
</Style>
<Style Selector="Button.ghost:pointerover">
<Setter Property="Background" Value="#EEF2FA" />
<Setter Property="Foreground" Value="{DynamicResource Ink}" />
</Style>
<Style Selector="Button.ghost:pressed">
<Setter Property="Background" Value="#E2E9F6" />
</Style>
<!-- 危险按钮 -->
<Style Selector="Button.danger">
<Setter Property="Foreground" Value="{DynamicResource Danger}" />
</Style>
<Style Selector="Button.danger:pointerover">
<Setter Property="Background" Value="#FDECEC" />
<Setter Property="Foreground" Value="{DynamicResource Danger}" />
</Style>
<Style Selector="Button.danger:pressed">
<Setter Property="Background" Value="#F8DADA" />
</Style>
<!-- 深色背景上的按钮 -->
<Style Selector="Button.onDark">
<Setter Property="Background" Value="#1B2740" />
<Setter Property="BorderBrush" Value="#2A3A57" />
<Setter Property="Foreground" Value="#DCE7FA" />
</Style>
<Style Selector="Button.onDark:pointerover">
<Setter Property="Background" Value="#233351" />
<Setter Property="BorderBrush" Value="#3A4E75" />
</Style>
<Style Selector="Button.onDark:pressed">
<Setter Property="Background" Value="#2B3D60" />
</Style>
<Style Selector="Button.onDark.active">
<Setter Property="Background" Value="{DynamicResource Accent}" />
<Setter Property="BorderBrush" Value="{DynamicResource Accent}" />
<Setter Property="Foreground" Value="White" />
</Style>
<Style Selector="Button.small">
<Setter Property="FontSize" Value="12" />
<Setter Property="Padding" Value="10,4" />
<Setter Property="MinHeight" Value="28" />
<Setter Property="CornerRadius" Value="8" />
</Style>
<!-- 侧栏导航(主页 / 下载 / 设置) -->
<Style Selector="Button.nav">
<Setter Property="HorizontalAlignment" Value="Stretch" />
<Setter Property="HorizontalContentAlignment" Value="Left" />
<Setter Property="Background" Value="Transparent" />
<Setter Property="BorderBrush" Value="Transparent" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="Foreground" Value="{DynamicResource SideInk}" />
<Setter Property="Padding" Value="14,10" />
<Setter Property="CornerRadius" Value="10" />
<Setter Property="FontSize" Value="13.5" />
<Setter Property="MinHeight" Value="40" />
</Style>
<Style Selector="Button.nav:pointerover">
<Setter Property="Background" Value="#16213A" />
<Setter Property="Foreground" Value="#E8EFFF" />
</Style>
<Style Selector="Button.nav:pressed">
<Setter Property="Background" Value="#1E2C49" />
</Style>
<Style Selector="Button.nav.active">
<Setter Property="Background" Value="#1C2C4C" />
<Setter Property="Foreground" Value="#FFFFFF" />
<Setter Property="BorderBrush" Value="{DynamicResource Accent}" />
<Setter Property="BorderThickness" Value="3,0,0,0" />
</Style>
<Style Selector="Button.nav.active:pointerover">
<Setter Property="Background" Value="#22355A" />
<Setter Property="Foreground" Value="#FFFFFF" />
</Style>
<!-- 输入 -->
<Style Selector="TextBox">
<Setter Property="CornerRadius" Value="9" />
<Setter Property="Padding" Value="11,8" />
<Setter Property="MinHeight" Value="36" />
<Setter Property="FontSize" Value="12.5" />
<Setter Property="Background" Value="{DynamicResource Surface}" />
<Setter Property="BorderBrush" Value="{DynamicResource LineStrong}" />
</Style>
<Style Selector="ComboBox">
<Setter Property="CornerRadius" Value="9" />
<Setter Property="MinHeight" Value="34" />
<Setter Property="FontSize" Value="12.5" />
<Setter Property="Padding" Value="10,4" />
</Style>
<Style Selector="ProgressBar">
<Setter Property="Height" Value="5" />
<Setter Property="CornerRadius" Value="3" />
<Setter Property="MinHeight" Value="5" />
</Style>
<Style Selector="CheckBox">
<Setter Property="FontSize" Value="12.5" />
</Style>
<!-- ===================================================================
自建标题栏按钮(最小化 − / 关闭 ✕)
同样只用纯画刷换色,绝不设置 RenderTransform;
且用更高优先级覆盖上面通用的 :pointerover / :pressed,
避免深色标题栏上出现浅色 hover 背景。
=================================================================== -->
<Style Selector="Button.titlebtn">
<Setter Property="Width" Value="38" />
<Setter Property="Height" Value="30" />
<Setter Property="Background" Value="Transparent" />
<Setter Property="Foreground" Value="#A9B8D4" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="BorderBrush" Value="Transparent" />
<Setter Property="FontSize" Value="13" />
<Setter Property="HorizontalContentAlignment" Value="Center" />
<Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="CornerRadius" Value="7" />
<Setter Property="Margin" Value="2,0" />
</Style>
<Style Selector="Button.titlebtn:pointerover">
<Setter Property="Background" Value="#223252" />
<Setter Property="BorderBrush" Value="Transparent" />
<Setter Property="Foreground" Value="#FFFFFF" />
</Style>
<Style Selector="Button.titlebtn:pressed">
<Setter Property="Background" Value="#2C4270" />
<Setter Property="Foreground" Value="#FFFFFF" />
</Style>
<Style Selector="Button.titlebtn.close:pointerover">
<Setter Property="Background" Value="#D64545" />
<Setter Property="Foreground" Value="#FFFFFF" />
</Style>
<Style Selector="Button.titlebtn.close:pressed">
<Setter Property="Background" Value="#B93737" />
<Setter Property="Foreground" Value="#FFFFFF" />
</Style>
</Styles>
+104
View File
@@ -0,0 +1,104 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using GC.Services;
namespace GC.ViewModels;
/// <summary>「关于」页面:版本号 + 开发者(读取仓库 contributors)。</summary>
public partial class AboutViewModel : ObservableObject
{
private readonly AppServices _services;
private bool _loaded;
public ObservableCollection<ContributorItem> Contributors { get; } = new();
[ObservableProperty] private bool _isLoading = true;
[ObservableProperty] private string _statusText = "";
[ObservableProperty] private bool _hasContributors;
public AboutViewModel(AppServices services)
{
_services = services;
LoadCommand = new AsyncRelayCommand(() => LoadAsync(force: true));
}
public string AppName => "Morris GC";
/// <summary>启动器版本号,如 v1.0.2。</summary>
public string VersionText => "v" + LauncherRuntimeInfo.CurrentLauncherVersion;
/// <summary>当前平台标识,如 win-x64 / osx-arm64。</summary>
public string PlatformText => LauncherRuntimeInfo.CurrentRid;
public string RepositoryText => _services.Settings.Current.UpdateRepository;
public string ContributorsTitle => "开发者";
public IAsyncRelayCommand LoadCommand { get; }
/// <summary>每次进入页面时调用(首次才真正联网拉取)。</summary>
public void OnShown()
{
if (_loaded) return;
_ = LoadAsync(force: false);
}
private async Task LoadAsync(bool force)
{
if (_loaded && !force) return;
_loaded = true;
IsLoading = true;
StatusText = "正在读取贡献者…";
try
{
var list = await ContributorsService.FetchAsync(_services.Settings.Current.UpdateRepository);
Contributors.Clear();
foreach (var c in list)
Contributors.Add(new ContributorItem(c));
HasContributors = Contributors.Count > 0;
StatusText = HasContributors ? $"{Contributors.Count} 位贡献者" : "暂无贡献者信息";
}
catch (Exception ex)
{
StatusText = "读取失败:" + ex.Message;
}
finally
{
IsLoading = false;
}
}
[RelayCommand]
private void OpenRepository() => Shell.OpenUrl(RepositoryText);
/// <summary>重新下载启动器:关闭所有窗口,进度窗下载新版,完成后重启。</summary>
[RelayCommand]
private async System.Threading.Tasks.Task ReinstallLauncher()
{
if (LauncherUpdateFlow.IsRunning) return;
await LauncherUpdateFlow.RunAsync(_services, "正在重新下载启动器");
}
}
/// <summary>一位贡献者的展示项。</summary>
public sealed class ContributorItem
{
public ContributorItem(Contributor c)
{
Name = c.DisplayName;
Contributions = c.Contributions;
AvatarUrl = c.AvatarUrl;
}
public string Name { get; }
public int Contributions { get; }
public string? AvatarUrl { get; }
public string ContributionsText => $"{Contributions} 次提交";
public bool HasAvatar => !string.IsNullOrWhiteSpace(AvatarUrl);
}
+411
View File
@@ -0,0 +1,411 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using GC.Models;
using GC.Services;
namespace GC.ViewModels;
public partial class DownloadViewModel : ObservableObject
{
private readonly AppServices _services;
private readonly MainViewModel _main;
private bool _initialized;
// 每次切源取消上一次加载,并用 generation 序号丢弃过期结果,避免并发写 Models 集合
private CancellationTokenSource? _loadCts;
private int _loadGeneration;
public ObservableCollection<SourceItemViewModel> Sources { get; } = new();
public ObservableCollection<RemoteModelRowViewModel> Models { get; } = new();
public ObservableCollection<IDownloadJob> Jobs => _services.Downloads.Jobs;
[ObservableProperty] private SourceItemViewModel? _selectedSource;
[ObservableProperty] private string _importUrl = "";
[ObservableProperty] private bool _isBusy;
[ObservableProperty] private string _statusMessage = "";
[ObservableProperty] private bool _hasModels;
[ObservableProperty] private bool _isBackgroundOpen = true;
[ObservableProperty] private string _jobSummary = "";
[ObservableProperty] private bool _hasJobs;
[ObservableProperty] private bool _isSourceEmpty;
public DownloadViewModel(AppServices services, MainViewModel main)
{
_services = services;
_main = main;
Jobs.CollectionChanged += OnJobsChanged;
foreach (var job in Jobs) job.PropertyChanged += OnJobPropertyChanged;
L.I.LanguageChanged += RefreshLanguage;
RebuildSources();
UpdateJobState();
}
public string BackgroundTitle => L.I["dl.background"];
public string ImportHint => L.I["dl.hint"];
// ------------------------------------------------------------ 页面生命周期
public void OnShown()
{
if (_initialized) return;
_initialized = true;
if (SelectedSource == null)
SelectedSource = Sources.FirstOrDefault(s => s.Model.Enabled && !string.IsNullOrWhiteSpace(s.Model.Url))
?? Sources.FirstOrDefault();
}
// ------------------------------------------------------------ 模型源
private void RebuildSources()
{
var keepId = SelectedSource?.Model.Id;
Sources.Clear();
foreach (var source in _services.Settings.Current.Sources)
Sources.Add(new SourceItemViewModel(source, this, _services));
SelectedSource = Sources.FirstOrDefault(s => s.Model.Id == keepId) ?? SelectedSource;
}
partial void OnSelectedSourceChanged(SourceItemViewModel? value)
{
if (value == null) return;
if (string.IsNullOrWhiteSpace(value.Model.Url))
{
Models.Clear();
HasModels = false;
IsSourceEmpty = true;
StatusMessage = L.I["dl.pickSource"];
return;
}
_ = LoadAsync(value, force: false);
}
internal void OnSourceEnabledChanged(SourceItemViewModel source)
{
if (!source.Model.Enabled && SelectedSource == source) Models.Clear();
}
internal void RemoveSource(SourceItemViewModel source)
{
if (source.Model.BuiltIn) return; // 内置默认源不允许删除
_services.Settings.Current.Sources.Remove(source.Model);
_services.Settings.Save();
var wasSelected = SelectedSource == source;
Sources.Remove(source);
if (wasSelected)
{
SelectedSource = Sources.FirstOrDefault();
if (SelectedSource == null)
{
Models.Clear();
HasModels = false;
}
}
}
/// <summary>
/// 只允许两个内置源(Xhmcl / GitCode),不再接受任意地址。
/// 旧的「自定义源」入口统一改为:按测速结果切换到更快的那个源。
/// </summary>
[RelayCommand]
private async Task ImportAsync()
{
var fastest = await _services.Selector.PickFastestAsync(force: true);
var target = Sources.FirstOrDefault(x =>
SourcePreset.Find(fastest.Id) != null &&
SourcePreset.Detect(x.Model.Url).Id == fastest.Id);
if (target == null)
{
StatusMessage = "没有可用的下载源";
return;
}
SelectedSource = target;
var lat = _services.Selector.LastLatency;
StatusMessage = $"已切换到 {fastest.Name}" +
(lat.Count > 0 ? "(" + string.Join(",", lat.Select(kv =>
$"{SourcePreset.Find(kv.Key)?.Name ?? kv.Key} {kv.Value}ms")) + ")" : "");
await LoadAsync(target, force: true);
}
private static string DeriveName(string url)
{
var trimmed = url.TrimEnd('/', '\\');
var slash = trimmed.LastIndexOfAny(new[] { '/', '\\' });
var name = slash >= 0 ? trimmed[(slash + 1)..] : trimmed;
if (name.EndsWith(".git", StringComparison.OrdinalIgnoreCase)) name = name[..^4];
if (name.EndsWith(".zip", StringComparison.OrdinalIgnoreCase)) name = name[..^4];
return string.IsNullOrWhiteSpace(name) ? url : name;
}
[RelayCommand]
private async Task RefreshAsync()
{
if (SelectedSource == null) return;
await LoadAsync(SelectedSource, force: true);
}
internal async Task RefreshFromSource(SourceItemViewModel source)
{
SelectedSource = source;
await LoadAsync(source, force: true);
}
private async Task LoadAsync(SourceItemViewModel source, bool force)
{
if (!source.Model.Enabled) return;
// 取消上一次尚未完成的加载,避免快速切换源时并发 Clear/写入同一集合
_loadCts?.Cancel();
_loadCts?.Dispose();
_loadCts = new CancellationTokenSource();
var ct = _loadCts.Token;
var generation = ++_loadGeneration;
IsBusy = true;
StatusMessage = L.I["dl.syncing"];
try
{
// 第 6 项:下载页与启动更新用同一个源、同一种下载方式。
// 每次加载前先让选择器给出最快源(有缓存,不会真的每次都测)。
try
{
var fastest = await _services.Selector.PickFastestAsync(false, ct);
if (fastest.Id != SourcePreset.Detect(source.Model.Url).Id)
{
var prefer = Sources.FirstOrDefault(x =>
SourcePreset.Detect(x.Model.Url).Id == fastest.Id && x.Model.Enabled);
if (prefer != null && prefer != source)
{
SelectedSource = prefer;
source = prefer;
}
}
}
catch { /* 测速失败就沿用当前源 */ }
var index = await _services.Sources.FetchAsync(source.Model, force, null, ct);
// 只有「仍是当前选中源 + 仍是最新一次加载」才可以写 UI 集合
if (ct.IsCancellationRequested || generation != _loadGeneration || SelectedSource != source)
return;
if (index.Error != null)
{
Models.Clear();
HasModels = false;
IsSourceEmpty = true;
StatusMessage = DescribeError(index.Error);
return;
}
var installedIds = new HashSet<string>(
_services.Models.Scan().Select(p => p.Id), StringComparer.OrdinalIgnoreCase);
Models.Clear();
foreach (var model in index.Models)
{
Models.Add(new RemoteModelRowViewModel(model, source,
installedIds.Contains(model.Id), DownloadCommand));
}
HasModels = Models.Count > 0;
IsSourceEmpty = Models.Count == 0;
StatusMessage = index.FromCache
? $"{L.I.F("dl.ready", Models.Count)} · {L.I["dl.fromCache"]}"
: L.I.F("dl.ready", Models.Count);
}
catch (OperationCanceledException)
{
// 被更新的加载取代或页面关闭:忽略,不覆盖新结果
}
catch (Exception ex)
{
if (!ct.IsCancellationRequested) StatusMessage = ex.Message;
}
finally
{
// 只有最后一次加载才复位 Busy,避免旧任务把新任务的忙碌状态清掉
if (generation == _loadGeneration) IsBusy = false;
}
}
private static string DescribeError(string error)
{
if (error.StartsWith("dl.", StringComparison.Ordinal))
{
var text = L.I[error];
return text == error ? error : text;
}
return error;
}
// ------------------------------------------------------------ 下载
[RelayCommand]
private async Task DownloadAsync(RemoteModelRowViewModel row)
{
if (row == null) return;
row.RowOpacity = 0;
row.RowHeight = 0;
IsBackgroundOpen = true;
_services.Downloads.Enqueue(row.Model);
await Task.Delay(240);
Models.Remove(row);
HasModels = Models.Count > 0;
IsSourceEmpty = Models.Count == 0;
}
[RelayCommand]
private void CancelJob(IDownloadJob? job)
{
if (job != null) _services.Downloads.Cancel(job);
}
[RelayCommand]
private void RetryJob(IDownloadJob? job)
{
if (job != null) _services.Downloads.Retry(job);
}
[RelayCommand]
private void RemoveJob(IDownloadJob? job)
{
if (job != null) _services.Downloads.Remove(job);
}
[RelayCommand]
private void ClearFinished() => _services.Downloads.ClearFinished();
[RelayCommand]
private void ToggleBackground() => IsBackgroundOpen = !IsBackgroundOpen;
// ------------------------------------------------------------ 任务展示
private void OnJobsChanged(object? sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null)
foreach (IDownloadJob job in e.NewItems) job.PropertyChanged += OnJobPropertyChanged;
if (e.OldItems != null)
foreach (IDownloadJob job in e.OldItems) job.PropertyChanged -= OnJobPropertyChanged;
UpdateJobState();
}
private void OnJobPropertyChanged(object? sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(IDownloadJob.State))
{
if (sender is IDownloadJob { State: DownloadState.Completed })
_services.Models.NotifyChanged();
}
UpdateJobState();
}
private void UpdateJobState()
{
HasJobs = Jobs.Count > 0;
JobSummary = $"{L.I["dl.background"]} ({Jobs.Count})";
OnPropertyChanged(nameof(JobSummary));
}
private void RefreshLanguage()
{
foreach (var source in Sources) source.RefreshLanguage();
foreach (var model in Models) model.RefreshLanguage();
foreach (var job in Jobs) job.RefreshText();
OnPropertyChanged(nameof(BackgroundTitle));
OnPropertyChanged(nameof(ImportHint));
UpdateJobState();
}
}
public partial class SourceItemViewModel : ObservableObject
{
private readonly DownloadViewModel _owner;
private readonly AppServices _services;
public ModelSource Model { get; }
public SourceItemViewModel(ModelSource model, DownloadViewModel owner, AppServices services)
{
Model = model;
_owner = owner;
_services = services;
RemoveCommand = new RelayCommand(() => _owner.RemoveSource(this));
RefreshCommand = new AsyncRelayCommand(async () => await _owner.RefreshFromSource(this));
}
public string Name => string.IsNullOrWhiteSpace(Model.Name) ? Model.Id : Model.Name;
public string HostText => string.IsNullOrWhiteSpace(Model.Url) ? L.I["dl.noSource"] : Model.DisplayHost;
public bool HasUrl => !string.IsNullOrWhiteSpace(Model.Url);
/// <summary>内置默认源不可删除(下载页隐藏删除按钮)。</summary>
public bool CanRemove => !Model.BuiltIn;
public bool Enabled
{
get => Model.Enabled;
set
{
if (Model.Enabled == value) return;
Model.Enabled = value;
_services.Settings.Save();
OnPropertyChanged();
_owner.OnSourceEnabledChanged(this);
}
}
public ICommand RemoveCommand { get; }
public ICommand RefreshCommand { get; }
public void RefreshLanguage()
{
OnPropertyChanged(nameof(Name));
OnPropertyChanged(nameof(HostText));
}
}
public partial class RemoteModelRowViewModel : ObservableObject
{
public RemoteModel Model { get; }
public SourceItemViewModel Source { get; }
public RemoteModelRowViewModel(RemoteModel model, SourceItemViewModel source, bool installed, ICommand downloadCommand)
{
Model = model;
Source = source;
Installed = installed;
DownloadCommand = downloadCommand;
}
public string Name => Model.LocalizedName;
public string Description => Model.LocalizedDescription;
public string VersionText => "v" + Model.Manifest.Version;
public string SizeText => ModelScanner.HumanSize(Model.SizeBytes);
public string MetaText => $"{VersionText} · {SizeText}";
public string TagsText => string.Join(" · ", Model.Manifest.Tags ?? new List<string>());
public bool HasTags => !string.IsNullOrWhiteSpace(TagsText);
[ObservableProperty] private bool _installed;
[ObservableProperty] private double _rowHeight = 92;
[ObservableProperty] private double _rowOpacity = 1;
public string ButtonText => Installed ? L.I["dl.reinstall"] : L.I["dl.download"];
public ICommand DownloadCommand { get; }
partial void OnInstalledChanged(bool value) => OnPropertyChanged(nameof(ButtonText));
public void RefreshLanguage()
{
OnPropertyChanged(nameof(Name));
OnPropertyChanged(nameof(Description));
OnPropertyChanged(nameof(MetaText));
OnPropertyChanged(nameof(TagsText));
OnPropertyChanged(nameof(ButtonText));
}
}
+148
View File
@@ -0,0 +1,148 @@
using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Input;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using GC.Models;
using Avalonia.Media.Imaging;
using GC.Services;
namespace GC.ViewModels;
public partial class HomeViewModel : ObservableObject
{
private readonly AppServices _services;
private readonly MainViewModel _main;
public ObservableCollection<ModelCardViewModel> Models { get; } = new();
[ObservableProperty] private ModelCardViewModel? _selected;
[ObservableProperty] private bool _isEmpty;
public string CountText => L.I.F("home.count", Models.Count);
public string SourceCountText => _services.Settings.Current.Sources
.Count(s => s.Enabled && !string.IsNullOrWhiteSpace(s.Url)).ToString();
public string MemoryText => $"{_services.Memory.BudgetMb} MB";
public string SelectedHint => Selected == null ? L.I["home.recent"] : L.I["home.launchHint"];
public HomeViewModel(AppServices services, MainViewModel main)
{
_services = services;
_main = main;
_services.Models.Changed += Refresh;
L.I.LanguageChanged += RefreshLanguage;
Refresh();
}
public void Refresh()
{
var keepId = Selected?.Package.Id;
Models.Clear();
foreach (var package in _services.Models.Scan())
Models.Add(new ModelCardViewModel(package, _services, this));
Selected = Models.FirstOrDefault(m => m.Package.Id == keepId) ?? Models.FirstOrDefault();
IsEmpty = Models.Count == 0;
RefreshLanguage();
}
private void RefreshLanguage()
{
OnPropertyChanged(nameof(CountText));
OnPropertyChanged(nameof(SourceCountText));
OnPropertyChanged(nameof(MemoryText));
OnPropertyChanged(nameof(SelectedHint));
foreach (var model in Models) model.RefreshLanguage();
}
public void LaunchModel(ModelCardViewModel card)
{
Selected = card;
_main.PlayModel(card.Package);
}
public async Task DeleteAsync(ModelCardViewModel card)
{
if (!await _main.ConfirmAsync(L.I.F("home.deleteConfirm", card.Name))) return;
_services.Models.Delete(card.Package.Id);
_services.Models.NotifyChanged();
Refresh();
}
[RelayCommand]
private void Launch()
{
var card = Selected ?? Models.FirstOrDefault();
if (card != null) _main.PlayModel(card.Package);
}
[RelayCommand]
private void OpenDownload() => _main.GoDownload();
[RelayCommand]
private void OpenSettings() => _main.GoSettings();
[RelayCommand]
private void OpenFolder() => Shell.OpenFolder(_services.Paths.ModelRoot);
}
public partial class ModelCardViewModel : ObservableObject
{
private readonly AppServices _services;
private Bitmap? _preview;
public ModelPackage Package { get; }
public ModelCardViewModel(ModelPackage package, AppServices services, HomeViewModel home)
{
Package = package;
_services = services;
LaunchCommand = new RelayCommand(() => home.LaunchModel(this));
DeleteCommand = new AsyncRelayCommand(() => home.DeleteAsync(this));
OpenFolderCommand = new RelayCommand(() => Shell.OpenFolder(package.Directory));
}
public string Name => Package.LocalizedName;
public string Description => Package.LocalizedDescription;
public string VersionText => "v" + Package.Manifest.Version;
public string SizeText => ModelScanner.HumanSize(Package.SizeBytes);
public string MetaText => $"{VersionText} · {SizeText}";
public string TagsText => string.Join(" · ", Package.Manifest.Tags ?? new());
public bool HasTags => !string.IsNullOrWhiteSpace(TagsText);
public string AuthorText => string.IsNullOrWhiteSpace(Package.Manifest.Author) ? "" : Package.Manifest.Author;
/// <summary>封面图来自模型包自带的 preview.png —— 启动器只显示,不渲染。</summary>
public Bitmap? Preview
{
get
{
if (_preview != null) return _preview;
try
{
if (File.Exists(Package.PreviewPath)) _preview = new Bitmap(Package.PreviewPath);
}
catch (Exception ex)
{
Console.Error.WriteLine($"读取模型封面失败 {Package.Id}: {ex.Message}");
}
return _preview;
}
}
public bool HasPreview => Preview != null;
public ICommand LaunchCommand { get; }
public ICommand DeleteCommand { get; }
public ICommand OpenFolderCommand { get; }
public void RefreshLanguage()
{
OnPropertyChanged(nameof(Name));
OnPropertyChanged(nameof(Description));
OnPropertyChanged(nameof(MetaText));
OnPropertyChanged(nameof(TagsText));
}
}
+228
View File
@@ -0,0 +1,228 @@
using System;
using System.Linq;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using GC.Models;
using GC.Services;
namespace GC.ViewModels;
public partial class MainViewModel : ObservableObject
{
private readonly AppServices _services;
private bool _updateRunning;
public HomeViewModel Home { get; }
public DownloadViewModel Download { get; }
public SettingsViewModel Settings { get; }
public AboutViewModel About { get; }
/// <summary>模型宿主:按清单加载模型自带的功能程序集。</summary>
public ModelHost Models { get; }
[ObservableProperty] private ObservableObject _current = null!;
[ObservableProperty] private bool _isHomeActive = true;
[ObservableProperty] private bool _isDownloadActive;
[ObservableProperty] private bool _isSettingsActive;
[ObservableProperty] private bool _isAboutActive;
// 启动更新状态条
[ObservableProperty] private bool _updateBarVisible;
[ObservableProperty] private bool _updateBusy;
[ObservableProperty] private double _updateProgress;
[ObservableProperty] private string _updateStatus = "";
[ObservableProperty] private string _updateDetail = "";
[ObservableProperty] private string _launcherNotice = "";
/// <summary>由主窗口注入的确认对话框。</summary>
public Func<string, Task<bool>>? ConfirmHandler { get; set; }
/// <summary>
/// 由主窗口注入的「发现启动器新版本」对话框。
/// 参数为新版本号,返回 true 表示用户选择更新。
/// </summary>
public Func<string, Task<bool>>? LauncherUpdateHandler { get; set; }
public event Action<ModelPackage>? PlayerRequested;
/// <summary>打开等高线课件窗口(由主窗口接线)。</summary>
public event Action? CoursewareRequested;
public string VersionText => "v" + LauncherRuntimeInfo.CurrentLauncherVersion;
public string PlatformText => LauncherRuntimeInfo.CurrentRid;
public MainViewModel(AppServices services)
{
_services = services;
Models = services.ModelHost;
Home = new HomeViewModel(services, this);
Download = new DownloadViewModel(services, this);
Settings = new SettingsViewModel(services);
About = new AboutViewModel(services);
Current = Home;
}
partial void OnCurrentChanged(ObservableObject value)
{
IsHomeActive = value is HomeViewModel;
IsDownloadActive = value is DownloadViewModel;
IsSettingsActive = value is SettingsViewModel;
IsAboutActive = value is AboutViewModel;
}
[RelayCommand]
public void GoHome()
{
Home.Refresh();
Current = Home;
}
[RelayCommand]
public void GoDownload()
{
Current = Download;
Download.OnShown();
}
[RelayCommand]
public void GoSettings()
{
Settings.Refresh();
Current = Settings;
}
[RelayCommand]
public void GoAbout()
{
About.OnShown();
Current = About;
}
/// <summary>打开等高线课件(独立 Avalonia WebView 窗口)。</summary>
[RelayCommand]
public void OpenCourseware() => CoursewareRequested?.Invoke();
/// <summary>启动模型:交给模型自己的程序集,在独立窗口中运行。</summary>
public void PlayModel(ModelPackage package)
{
_services.Memory.Refresh();
PlayerRequested?.Invoke(package);
}
public async Task<bool> ConfirmAsync(string message)
=> ConfirmHandler == null || await ConfirmHandler(message);
// ---- 自动更新 ----------------------------------------------------------
/// <summary>启动后由 App 调用:后台检查更新,不阻塞主界面。</summary>
public Task RunStartupUpdateAsync() => RunUpdateAsync(false);
/// <summary>状态条 / 设置页的「检查更新」,忽略自动开关强制检查。</summary>
[RelayCommand]
private Task CheckUpdate() => RunUpdateAsync(true);
private async Task RunUpdateAsync(bool force)
{
if (_updateRunning) return;
_updateRunning = true;
try
{
UpdateBarVisible = true;
UpdateBusy = true;
UpdateProgress = 0;
UpdateStatus = L.I["update.checking"];
UpdateDetail = "";
LauncherNotice = "";
// 在 UI 线程构造,进度回调自动回到 UI 线程
var progress = new Progress<UpdateProgress>(p =>
{
UpdateProgress = Math.Clamp(p.Value, 0, 1);
UpdateStatus = p.Message;
UpdateDetail = p.Detail ?? "";
});
// 双源测速:Xhmcl / GitCode 取快的那个(第 5 项)。
// 启动更新与下载页共用同一个选择器,保证两处用同一个源、同一种下载方式。
UpdateStatus = "正在选择最快的下载源…";
try
{
var fastest = await _services.Selector.PickFastestAsync(
force, default);
_services.Updates.UseRemote(_services.DownloadModule.CreateRemote(fastest));
var lat = _services.Selector.LastLatency;
UpdateDetail = "源:" + fastest.Name +
(lat.Count > 0 ? "(" + string.Join(",", lat.Select(kv =>
$"{SourcePreset.Find(kv.Key)?.Name ?? kv.Key} {kv.Value}ms")) + ")" : "");
}
catch (Exception ex)
{
Console.Error.WriteLine($"[update] 测速失败,沿用当前源: {ex.Message}");
}
// 启动器:读 Release latest 版本号,与当前运行版本不同就弹窗询问
var latest = await _services.LauncherUpdates.CheckAsync(_services.Updates.Remote);
if (latest != null)
{
var agreed = LauncherUpdateHandler != null &&
await LauncherUpdateHandler(latest);
if (agreed)
{
// 走完整更新流程(关窗 -> 进度窗下载 -> 重启)
UpdateBusy = false;
_updateRunning = false;
UpdateBarVisible = false;
await LauncherUpdateFlow.RunAsync(_services, "正在更新启动器");
return;
}
UpdateStatus = $"启动器有新版本 v{latest}(已跳过)";
UpdateDetail = "点击「检查更新」可再次更新,模型仍会同步到最新";
}
// 模型:同步到最新版
var result = await _services.Updates.RunAsync(force, progress, default);
UpdateStatus = result.Message;
UpdateDetail = result.Error ?? "";
LauncherNotice = result.LauncherMessage ?? "";
// 首次启动 + 断网:本地一个模型都没有,这时候不能只留一个空页面。
// 明确告诉用户「没坏、可以怎么办」,并保留状态条(不自动隐藏)。
if (result.Outcome == UpdateOutcome.Unavailable && Home.Models.Count == 0)
{
UpdateStatus = "暂时连不上模型源,模型库为空";
UpdateDetail = "可以到「下载」页点重试,或把模型文件夹放进 .GC/model/ 后重新打开";
return;
}
// 模型下载完成后本次启动就刷新列表,立刻可用
if (result.UpdatedModels > 0) Home.Refresh();
if ((result.Outcome == UpdateOutcome.NoChange || result.Outcome == UpdateOutcome.Applied) &&
string.IsNullOrEmpty(LauncherNotice))
_ = AutoHideAsync();
}
catch (Exception ex)
{
UpdateStatus = L.I["update.offline"];
UpdateDetail = ex.Message;
}
finally
{
UpdateBusy = false;
_updateRunning = false;
}
}
private async Task AutoHideAsync()
{
try
{
await Task.Delay(6000);
if (!_updateRunning && string.IsNullOrEmpty(LauncherNotice)) UpdateBarVisible = false;
}
catch { /* 忽略 */ }
}
}
+217
View File
@@ -0,0 +1,217 @@
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Input;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using GC.Models;
using GC.Services;
namespace GC.ViewModels;
public sealed class LanguageOption
{
public string Code { get; init; } = "auto";
public string Label { get; set; } = "";
public override string ToString() => Label;
}
public partial class SettingsViewModel : ObservableObject
{
private readonly AppServices _services;
private bool _loading = true;
public ObservableCollection<SettingsSourceViewModel> Sources { get; } = new();
public ObservableCollection<LanguageOption> Languages { get; } = new();
public int[] FrameRates { get; } = { 24, 30, 60, 90, 120 };
[ObservableProperty] private LanguageOption? _selectedLanguage;
[ObservableProperty] private int _selectedFps = 120;
[ObservableProperty] private double _memoryValue = 2048;
[ObservableProperty] private bool _memoryAuto = true;
[ObservableProperty] private string _statusMessage = "";
[ObservableProperty] private bool _autoUpdate = true;
public string UpdateSourceText => _services.Updates.Remote.DisplayName;
public string LastCheckText
{
get
{
var value = _services.Settings.Current.LastUpdateCheck;
if (string.IsNullOrWhiteSpace(value)) return L.I["update.never"];
return DateTimeOffset.TryParse(value, out var time)
? time.ToLocalTime().ToString("yyyy-MM-dd HH:mm") : value!;
}
}
public string PendingText => string.IsNullOrWhiteSpace(_services.Settings.Current.PendingLauncherVersion)
? L.I["update.none"] : _services.Settings.Current.PendingLauncherVersion!;
public string MemoryValueText => MemoryAuto
? $"{L.I["set.memory.auto"]} ({_services.Memory.BudgetMb} MB)"
: $"{(int)Math.Round(MemoryValue)} MB";
public string UsageText => _services.Memory.UsageText;
public string ModelRoot => _services.Paths.ModelRoot;
public string DataRoot => _services.Paths.DataRoot;
public string PlatformText => $"{RuntimeInformation.OSDescription} · {RuntimeInformation.RuntimeIdentifier}";
public string VersionText => "v1.0.0";
public string MemoryHint => L.I["set.memory.hint"];
public SettingsViewModel(AppServices services)
{
_services = services;
L.I.LanguageChanged += OnLanguageChanged;
Refresh();
_loading = false;
}
public void Refresh()
{
_loading = true;
BuildLanguages();
var settings = _services.Settings.Current;
SelectedFps = settings.RenderFps;
MemoryValue = settings.MemoryMb;
MemoryAuto = settings.MemoryAuto;
AutoUpdate = settings.AutoUpdateOnStartup;
Sources.Clear();
foreach (var source in settings.Sources)
Sources.Add(new SettingsSourceViewModel(source, _services, this));
_loading = false;
OnPropertyChanged(nameof(UsageText));
OnPropertyChanged(nameof(MemoryValueText));
OnPropertyChanged(nameof(MemoryHint));
OnPropertyChanged(nameof(ModelRoot));
OnPropertyChanged(nameof(DataRoot));
OnPropertyChanged(nameof(UpdateSourceText));
OnPropertyChanged(nameof(LastCheckText));
OnPropertyChanged(nameof(PendingText));
}
partial void OnAutoUpdateChanged(bool value)
{
if (_loading) return;
_services.Settings.Apply(s => s.AutoUpdateOnStartup = value);
}
private void BuildLanguages()
{
var current = _services.Settings.Current.Language;
Languages.Clear();
Languages.Add(new LanguageOption { Code = "auto", Label = L.I["set.language.auto"] });
foreach (var (code, label) in L.Supported)
Languages.Add(new LanguageOption { Code = code, Label = label });
SelectedLanguage = Languages.FirstOrDefault(l => l.Code == current) ?? Languages[0];
}
private void OnLanguageChanged()
{
_loading = true;
BuildLanguages();
_loading = false;
Refresh();
}
partial void OnSelectedLanguageChanged(LanguageOption? value)
{
if (_loading || value == null) return;
_services.Settings.Apply(s => s.Language = value.Code);
L.I.SetLanguage(value.Code);
}
partial void OnSelectedFpsChanged(int value)
{
if (_loading) return;
_services.Settings.Apply(s => s.RenderFps = Math.Clamp(value, 12, 120));
}
partial void OnMemoryValueChanged(double value)
{
if (_loading) return;
var mb = (int)Math.Round(value);
_services.Settings.Apply(s => s.MemoryMb = mb);
_services.Memory.Apply(mb);
OnPropertyChanged(nameof(MemoryValueText));
OnPropertyChanged(nameof(UsageText));
}
partial void OnMemoryAutoChanged(bool value)
{
if (_loading) return;
_services.Settings.Apply(s => s.MemoryAuto = value);
_services.Memory.ApplyAuto(value, (int)Math.Round(MemoryValue));
OnPropertyChanged(nameof(MemoryValueText));
OnPropertyChanged(nameof(UsageText));
}
[RelayCommand]
private void OpenModelFolder() => Shell.OpenFolder(_services.Paths.ModelRoot);
[RelayCommand]
private void OpenDataFolder() => Shell.OpenFolder(_services.Paths.DataRoot);
[RelayCommand]
private void ClearCache()
{
// 模型数据由模型自己管理;这里只回收启动器侧托管内存
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
_services.Memory.Refresh();
StatusMessage = L.I["set.cacheCleared"];
OnPropertyChanged(nameof(UsageText));
}
[RelayCommand]
private void ApplyMemory()
{
_services.Memory.Apply((int)Math.Round(MemoryValue));
StatusMessage = L.I["common.applied"];
OnPropertyChanged(nameof(UsageText));
}
internal void RemoveSource(SettingsSourceViewModel source)
{
if (source.Model.BuiltIn) return; // 内置默认源不允许删除
_services.Settings.Current.Sources.Remove(source.Model);
_services.Settings.Save();
Sources.Remove(source);
_services.Settings.Notify();
}
}
public partial class SettingsSourceViewModel : ObservableObject
{
private readonly AppServices _services;
private readonly SettingsViewModel _owner;
public ModelSource Model { get; }
public SettingsSourceViewModel(ModelSource model, AppServices services, SettingsViewModel owner)
{
Model = model;
_services = services;
_owner = owner;
RemoveCommand = new RelayCommand(() => _owner.RemoveSource(this));
}
public string Name => string.IsNullOrWhiteSpace(Model.Name) ? Model.Id : Model.Name;
public string UrlText => string.IsNullOrWhiteSpace(Model.Url) ? L.I["dl.noSource"] : Model.Url;
/// <summary>内置默认源不可删除。</summary>
public bool CanRemove => !Model.BuiltIn;
public bool Enabled
{
get => Model.Enabled;
set
{
if (Model.Enabled == value) return;
Model.Enabled = value;
_services.Settings.Save();
OnPropertyChanged();
}
}
public ICommand RemoveCommand { get; }
}
+147
View File
@@ -0,0 +1,147 @@
<UserControl xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:loc="using:GC.Services"
xmlns:vm="using:GC.ViewModels"
x:Class="GC.Views.AboutView"
x:DataType="vm:AboutViewModel">
<ScrollViewer>
<StackPanel Margin="28,24" Spacing="16" MaxWidth="880" HorizontalAlignment="Left">
<StackPanel Spacing="4">
<TextBlock Classes="h1" Text="关于" />
<TextBlock Classes="muted" Text="版本信息与开发者" />
</StackPanel>
<!-- 应用信息 -->
<Border Classes="card" Padding="22,20">
<Grid ColumnDefinitions="Auto,*">
<Border Width="62" Height="62" CornerRadius="16" Background="#1C2C4C"
VerticalAlignment="Top">
<TextBlock Text="◎" FontSize="32" Foreground="#8FB6FF"
HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border>
<StackPanel Grid.Column="1" Margin="18,0,0,0" Spacing="10">
<StackPanel Spacing="2">
<TextBlock Text="{Binding AppName}" FontSize="19" FontWeight="SemiBold" />
<TextBlock Classes="faint" Text="{Binding PlatformText}" />
</StackPanel>
<Grid ColumnDefinitions="96,*" RowDefinitions="Auto,Auto,Auto">
<TextBlock Classes="h3" Text="版本" />
<TextBlock Grid.Column="1" Classes="muted" Text="{Binding VersionText}"
FontWeight="SemiBold" />
<TextBlock Grid.Row="1" Classes="h3" Text="仓库" Margin="0,8,0,0" />
<Button Grid.Row="1" Grid.Column="1" Classes="ghost small" Margin="0,6,0,0"
HorizontalAlignment="Left" Padding="0"
Command="{Binding OpenRepositoryCommand}"
Content="{Binding RepositoryText}" />
<TextBlock Grid.Row="2" Classes="h3" Text="Git 服务" Margin="0,8,0,0" />
<TextBlock Grid.Row="2" Grid.Column="1" Classes="muted" Text="itxiaohui"
FontWeight="SemiBold" Margin="0,8,0,0" />
</Grid>
</StackPanel>
</Grid>
</Border>
<!-- 维护 -->
<Border Classes="card" Padding="22,20">
<StackPanel Spacing="12">
<TextBlock Classes="h2" Text="启动器维护" />
<TextBlock Classes="muted" TextWrapping="Wrap"
Text="重新下载会关闭所有窗口,显示下载进度,完成后自动启动新版本并删除旧版本。" />
<Button Classes="primary" Content="重新下载启动器"
HorizontalAlignment="Left" Padding="18,8"
Command="{Binding ReinstallLauncherCommand}" />
</StackPanel>
</Border>
<!-- 感谢(样式抄「开发者」卡片,内容写死,不读取数据) -->
<Border Classes="card" Padding="22,20">
<StackPanel Spacing="14">
<TextBlock Classes="h2" Text="感谢" />
<StackPanel Orientation="Horizontal" Spacing="10">
<Border Background="{DynamicResource SurfaceAlt}"
BorderBrush="{DynamicResource Line}" BorderThickness="1"
CornerRadius="12" Padding="12,10" MinWidth="190">
<StackPanel Orientation="Horizontal" Spacing="10">
<Border Width="34" Height="34" CornerRadius="17"
Background="{DynamicResource AccentSoft}">
<TextBlock Text="◉" FontSize="15" Foreground="{DynamicResource Accent}"
HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border>
<StackPanel VerticalAlignment="Center" Spacing="1">
<TextBlock Text="地理洪老师" FontSize="12.5" FontWeight="SemiBold" />
<TextBlock Classes="faint" Text="地理学科内容指导" />
</StackPanel>
</StackPanel>
</Border>
<Border Background="{DynamicResource SurfaceAlt}"
BorderBrush="{DynamicResource Line}" BorderThickness="1"
CornerRadius="12" Padding="12,10" MinWidth="190">
<StackPanel Orientation="Horizontal" Spacing="10">
<Border Width="34" Height="34" CornerRadius="17"
Background="{DynamicResource AccentSoft}">
<TextBlock Text="◉" FontSize="15" Foreground="{DynamicResource Accent}"
HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border>
<StackPanel VerticalAlignment="Center" Spacing="1">
<TextBlock Text="itxiaohui" FontSize="12.5" FontWeight="SemiBold" />
<TextBlock Classes="faint" Text="Git 服务与部署支持" />
</StackPanel>
</StackPanel>
</Border>
</StackPanel>
</StackPanel>
</Border>
<!-- 开发者 -->
<Border Classes="card" Padding="22,20">
<StackPanel Spacing="14">
<Grid ColumnDefinitions="*,Auto">
<TextBlock Classes="h2" Text="{Binding ContributorsTitle}" />
<Button Grid.Column="1" Classes="ghost small" Content="刷新"
Command="{Binding LoadCommand}" IsEnabled="{Binding !IsLoading}" />
</Grid>
<TextBlock Classes="faint" Text="{Binding StatusText}" />
<ProgressBar IsIndeterminate="True" Height="3" IsVisible="{Binding IsLoading}" />
<ItemsControl ItemsSource="{Binding Contributors}" IsVisible="{Binding HasContributors}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border Background="{DynamicResource SurfaceAlt}"
BorderBrush="{DynamicResource Line}" BorderThickness="1"
CornerRadius="12" Padding="12,10" Margin="0,0,10,10" MinWidth="190">
<StackPanel Orientation="Horizontal" Spacing="10">
<Border Width="34" Height="34" CornerRadius="17"
Background="{DynamicResource AccentSoft}">
<TextBlock Text="◉" FontSize="15" Foreground="{DynamicResource Accent}"
HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border>
<StackPanel VerticalAlignment="Center" Spacing="1">
<TextBlock Text="{Binding Name}" FontSize="12.5" FontWeight="SemiBold" />
<TextBlock Classes="faint" Text="{Binding ContributionsText}" />
</StackPanel>
</StackPanel>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</Border>
</StackPanel>
</ScrollViewer>
</UserControl>
+11
View File
@@ -0,0 +1,11 @@
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
namespace GC.Views;
public partial class AboutView : UserControl
{
public AboutView() => InitializeComponent();
private void InitializeComponent() => AvaloniaXamlLoader.Load(this);
}
+21
View File
@@ -0,0 +1,21 @@
<Window xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:loc="using:GC.Services"
x:Class="GC.Views.ConfirmWindow"
Title="{loc:Loc app.name}"
Width="440" SizeToContent="Height"
CanResize="False" ShowInTaskbar="False"
WindowStartupLocation="CenterOwner"
Background="Transparent"
SystemDecorations="None"
TransparencyLevelHint="Transparent">
<StackPanel Margin="24,20,24,20" Spacing="14">
<TextBlock x:Name="TitleText" Classes="h2" Text="{loc:Loc common.confirmTitle}" />
<TextBlock x:Name="MessageText" Classes="muted" TextWrapping="Wrap" />
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Spacing="8" Margin="0,6,0,0">
<Button x:Name="CancelButton" Content="{loc:Loc common.cancel}" Click="OnCancel" />
<Button x:Name="ConfirmButton" Classes="primary" Content="{loc:Loc common.confirm}" Click="OnConfirm" />
</StackPanel>
</StackPanel>
</Window>
+66
View File
@@ -0,0 +1,66 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using Avalonia.Media;
namespace GC.Views;
public partial class ConfirmWindow : Window
{
public ConfirmWindow() : this("") { }
public ConfirmWindow(string message) : this(null, message, null, null) { }
/// <summary>
/// 可定制标题与按钮文案的确认窗。
/// </summary>
public ConfirmWindow(string? title, string message, string? confirmText, string? cancelText)
{
AvaloniaXamlLoader.Load(this);
TransparencyLevelHint = new[] { WindowTransparencyLevel.Transparent };
Background = Brushes.Transparent;
if (this.Content is Control content)
{
// 先把 content 从 Window 上摘下来,否则再赋给 Border.Child 会抛
// "The Control already has a parent."
this.Content = null;
this.Content = new Border
{
CornerRadius = new CornerRadius(14),
BorderBrush = (this.FindResource("Line") as IBrush) ?? Brushes.Gray,
BorderThickness = new Thickness(1),
Background = (this.FindResource("Surface") as IBrush) ?? Brushes.White,
ClipToBounds = true,
Child = content
};
}
var text = this.FindControl<TextBlock>("MessageText");
if (text != null) text.Text = message;
if (!string.IsNullOrWhiteSpace(title))
{
var titleBlock = this.FindControl<TextBlock>("TitleText");
if (titleBlock != null) titleBlock.Text = title;
}
if (!string.IsNullOrWhiteSpace(confirmText))
{
var ok = this.FindControl<Button>("ConfirmButton");
if (ok != null) ok.Content = confirmText;
}
if (!string.IsNullOrWhiteSpace(cancelText))
{
// 取消按钮是第一个("取消"),这里按名查找更稳
var cancel = this.FindControl<Button>("CancelButton");
if (cancel != null) cancel.Content = cancelText;
}
}
private void OnCancel(object? sender, RoutedEventArgs e) => Close(false);
private void OnConfirm(object? sender, RoutedEventArgs e) => Close(true);
}
+50
View File
@@ -0,0 +1,50 @@
using System;
using Avalonia;
using Avalonia.Controls;
using AvaloniaWebView;
using GC.Services;
namespace GC.Views;
/// <summary>
/// 等高线地形课件窗口:内嵌 WebView 渲染本地 HTML 课件。
/// 课件资源由 <see cref="CoursewareServer"/> 通过回环 HTTP 提供,
/// 解决 file:// 下的同源策略与视频拖动问题。
/// </summary>
public sealed class CoursewareWindow : Window
{
private readonly CoursewareServer? _server;
public CoursewareWindow()
{
Title = "等高线地形课件";
Width = 1180;
Height = 780;
MinWidth = 760;
MinHeight = 520;
WindowStartupLocation = WindowStartupLocation.CenterOwner;
try
{
_server = new CoursewareServer();
var webView = new WebView();
webView.Url = new Uri(_server.BaseUrl + "index.html");
Content = webView;
}
catch (Exception ex)
{
Content = new TextBlock
{
Text = $"课件加载失败:{ex.Message}",
Margin = new Thickness(24),
TextWrapping = Avalonia.Media.TextWrapping.Wrap,
};
}
}
protected override void OnClosed(EventArgs e)
{
_server?.Dispose();
base.OnClosed(e);
}
}
+154
View File
@@ -0,0 +1,154 @@
<UserControl xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:loc="using:GC.Services"
x:Class="GC.Views.DownloadView">
<Grid ColumnDefinitions="316,*" Margin="24,22,24,24">
<!-- 模型源 -->
<Border Grid.Column="0" Classes="card" Padding="18" Margin="0,0,16,0">
<Grid RowDefinitions="Auto,Auto,Auto,*,Auto">
<TextBlock Classes="h2" Text="{loc:Loc dl.sources}" />
<!-- 只允许 Xhmcl / GitCode 两个内置源;这里是对比测速并自动切换 -->
<StackPanel Grid.Row="1" Margin="0,12,0,0" Spacing="8">
<Button Classes="primary" Content="测速并切换到最快源"
Command="{Binding ImportCommand}" HorizontalAlignment="Stretch" />
</StackPanel>
<TextBlock Grid.Row="2" Classes="faint" Text="{loc:Loc dl.hint}"
TextWrapping="Wrap" Margin="0,9,0,12" />
<ScrollViewer Grid.Row="3" VerticalScrollBarVisibility="Auto">
<ListBox ItemsSource="{Binding Sources}" SelectedItem="{Binding SelectedSource}"
Background="Transparent" BorderThickness="0" Padding="0">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid ColumnDefinitions="*,Auto" Margin="0,3">
<StackPanel Spacing="2" VerticalAlignment="Center">
<TextBlock Text="{Binding Name}" FontSize="12.5" FontWeight="SemiBold"
TextTrimming="CharacterEllipsis" />
<TextBlock Text="{Binding HostText}" Classes="faint" TextTrimming="CharacterEllipsis" />
</StackPanel>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</ScrollViewer>
<Border Grid.Row="4" Classes="panel" Padding="12,9" Margin="0,10,0,0">
<StackPanel Spacing="3">
<TextBlock Classes="eyebrow" Text="{loc:Loc dl.available}" />
<TextBlock Classes="faint" Text="{Binding StatusMessage}" TextWrapping="Wrap" />
</StackPanel>
</Border>
</Grid>
</Border>
<!-- 可用模型 + 后台任务 -->
<Border Grid.Column="1" Classes="card" Padding="20">
<Grid RowDefinitions="Auto,*,Auto">
<Grid ColumnDefinitions="*,Auto,Auto">
<StackPanel>
<TextBlock Classes="h2" Text="{loc:Loc dl.available}" />
<TextBlock Classes="muted" Text="{Binding StatusMessage}" Margin="0,3,0,0" />
</StackPanel>
<ProgressBar Grid.Column="1" IsIndeterminate="True" Width="90" Height="4"
IsVisible="{Binding IsBusy}" VerticalAlignment="Center" Margin="12,0" />
<Button Grid.Column="2" Classes="small" Content="{loc:Loc dl.refresh}"
Command="{Binding RefreshCommand}" VerticalAlignment="Center" />
</Grid>
<ScrollViewer Grid.Row="1" Margin="0,14,0,0" VerticalScrollBarVisibility="Auto">
<ItemsControl ItemsSource="{Binding Models}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border Height="{Binding RowHeight}" Opacity="{Binding RowOpacity}"
ClipToBounds="True" Margin="0,0,0,10">
<Border.Transitions>
<Transitions>
<DoubleTransition Property="Height" Duration="0:0:0.24" Easing="CubicEaseOut" />
<DoubleTransition Property="Opacity" Duration="0:0:0.18" />
</Transitions>
</Border.Transitions>
<Border Classes="panel" Padding="14,11">
<Grid ColumnDefinitions="*,Auto">
<StackPanel Spacing="3" VerticalAlignment="Center">
<StackPanel Orientation="Horizontal" Spacing="8">
<TextBlock Text="{Binding Name}" FontSize="13" FontWeight="SemiBold" />
<Border Classes="tag" VerticalAlignment="Center">
<TextBlock Text="{Binding VersionText}" Classes="faint" />
</Border>
<TextBlock Text="{Binding SizeText}" Classes="faint" VerticalAlignment="Center" />
</StackPanel>
<TextBlock Text="{Binding Description}" Classes="muted"
MaxLines="1" TextTrimming="CharacterEllipsis" MaxWidth="520" />
<TextBlock Text="{Binding TagsText}" Classes="faint" IsVisible="{Binding HasTags}" />
</StackPanel>
<Button Grid.Column="1" Classes="primary small" Content="{Binding ButtonText}"
Command="{Binding DownloadCommand}" CommandParameter="{Binding}"
VerticalAlignment="Center" Margin="12,0,0,0" />
</Grid>
</Border>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
<!-- 后台任务(下载时折叠到这里) -->
<Border Grid.Row="2" Classes="panel" Margin="0,12,0,0" Padding="6" IsVisible="{Binding HasJobs}">
<StackPanel>
<Grid ColumnDefinitions="*,Auto">
<Button Classes="ghost" Content="{Binding JobSummary}" Command="{Binding ToggleBackgroundCommand}"
HorizontalContentAlignment="Left" FontSize="12" FontWeight="SemiBold" Padding="10,7" />
<Button Grid.Column="1" Classes="ghost small" Content="{loc:Loc dl.clearDone}"
Command="{Binding ClearFinishedCommand}" VerticalAlignment="Center" Margin="0,0,6,0" />
</Grid>
<ScrollViewer MaxHeight="200" IsVisible="{Binding IsBackgroundOpen}">
<ItemsControl ItemsSource="{Binding Jobs}" Margin="6,0,6,6">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border Background="{DynamicResource Surface}" CornerRadius="9" Padding="10,8" Margin="0,4,0,0">
<Grid ColumnDefinitions="*,Auto">
<StackPanel Spacing="4">
<Grid ColumnDefinitions="*,Auto">
<TextBlock Text="{Binding Name}" FontSize="12" FontWeight="SemiBold" />
<TextBlock Grid.Column="1" Text="{Binding StatusText}" Classes="faint" />
</Grid>
<ProgressBar Value="{Binding Progress}" Maximum="1" IsVisible="{Binding IsActive}" />
<TextBlock Text="{Binding DetailText}" Classes="faint" TextTrimming="CharacterEllipsis" />
</StackPanel>
<StackPanel Grid.Column="1" Orientation="Horizontal" Spacing="2"
VerticalAlignment="Center" Margin="10,0,0,0">
<Button Classes="ghost small" Content="{loc:Loc dl.cancel}"
IsVisible="{Binding IsActive}"
Command="{Binding $parent[ItemsControl].DataContext.CancelJobCommand}"
CommandParameter="{Binding}" />
<Button Classes="ghost small" Content="{loc:Loc dl.retry}"
IsVisible="{Binding CanRetry}"
Command="{Binding $parent[ItemsControl].DataContext.RetryJobCommand}"
CommandParameter="{Binding}" />
<Button Classes="ghost small" Content="{loc:Loc dl.removeTask}"
Command="{Binding $parent[ItemsControl].DataContext.RemoveJobCommand}"
CommandParameter="{Binding}" />
</StackPanel>
</Grid>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
</StackPanel>
</Border>
</Grid>
</Border>
</Grid>
</UserControl>
+9
View File
@@ -0,0 +1,9 @@
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
namespace GC.Views;
public partial class DownloadView : UserControl
{
public DownloadView() => AvaloniaXamlLoader.Load(this);
}
+111
View File
@@ -0,0 +1,111 @@
<UserControl xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:loc="using:GC.Services"
xmlns:controls="using:GC.Controls"
x:Class="GC.Views.HomeView">
<ScrollViewer VerticalScrollBarVisibility="Auto">
<StackPanel Margin="26,24,26,28" Spacing="18">
<!-- 主视觉 -->
<Border Classes="hero" Padding="26,24">
<Grid ColumnDefinitions="*,Auto">
<StackPanel Spacing="9" MaxWidth="560">
<TextBlock Classes="h1 onDark" Text="{loc:Loc home.title}" />
<TextBlock Text="{loc:Loc home.subtitle}" Foreground="#A9BEDF" FontSize="12.5"
TextWrapping="Wrap" MaxWidth="500" />
<StackPanel Orientation="Horizontal" Spacing="10" Margin="0,12,0,0">
<Button Classes="primary" Content="{loc:Loc home.launch}" Command="{Binding LaunchCommand}" />
<Button Classes="onDark" Content="{loc:Loc home.download}" Command="{Binding OpenDownloadCommand}" />
<Button Classes="onDark" Content="{loc:Loc home.settings}" Command="{Binding OpenSettingsCommand}" />
</StackPanel>
<TextBlock Text="{Binding SelectedHint}" Foreground="#7E93B8" FontSize="11" Margin="2,2,0,0" />
</StackPanel>
<StackPanel Grid.Column="1" Orientation="Horizontal" Spacing="10" VerticalAlignment="Center">
<Border Background="#16233C" CornerRadius="14" Padding="16,12" Width="96">
<StackPanel Spacing="2">
<TextBlock Text="{Binding Models.Count}" Foreground="#FFFFFF" FontSize="22" FontWeight="SemiBold" />
<TextBlock Text="{loc:Loc home.stats.models}" Foreground="#7E93B8" FontSize="10.5" />
</StackPanel>
</Border>
<Border Background="#16233C" CornerRadius="14" Padding="16,12" Width="96">
<StackPanel Spacing="2">
<TextBlock Text="{Binding SourceCountText}" Foreground="#FFFFFF" FontSize="22" FontWeight="SemiBold" />
<TextBlock Text="{loc:Loc home.stats.sources}" Foreground="#7E93B8" FontSize="10.5" />
</StackPanel>
</Border>
<Border Background="#16233C" CornerRadius="14" Padding="16,12" Width="112">
<StackPanel Spacing="2">
<TextBlock Text="{Binding MemoryText}" Foreground="#FFFFFF" FontSize="16" FontWeight="SemiBold" />
<TextBlock Text="{loc:Loc home.stats.memory}" Foreground="#7E93B8" FontSize="10.5" />
</StackPanel>
</Border>
</StackPanel>
</Grid>
</Border>
<!-- 列表标题 -->
<Grid ColumnDefinitions="*,Auto" Margin="2,4,2,0">
<TextBlock Classes="h2" Text="{loc:Loc home.installed}" />
<TextBlock Grid.Column="1" Classes="muted" Text="{Binding CountText}" VerticalAlignment="Center" />
</Grid>
<!-- 模型卡片 -->
<ItemsControl ItemsSource="{Binding Models}" IsVisible="{Binding !IsEmpty}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border Classes="card" Width="336" Margin="0,0,16,16" ClipToBounds="True">
<StackPanel>
<Border Height="138" Background="#0B1226" ClipToBounds="True">
<Panel>
<TextBlock Text="◎" FontSize="34" Foreground="#1B2A47"
HorizontalAlignment="Center" VerticalAlignment="Center" />
<Image Source="{Binding Preview}" Stretch="UniformToFill" />
</Panel>
</Border>
<StackPanel Margin="16,13,16,15" Spacing="7">
<Grid ColumnDefinitions="*,Auto">
<TextBlock Classes="h3" Text="{Binding Name}" TextTrimming="CharacterEllipsis" />
<TextBlock Grid.Column="1" Classes="faint" Text="{Binding MetaText}"
VerticalAlignment="Center" Margin="8,0,0,0" />
</Grid>
<TextBlock Classes="muted" Text="{Binding Description}" TextWrapping="Wrap"
MaxLines="2" Height="32" TextTrimming="CharacterEllipsis" />
<TextBlock Classes="faint" Text="{Binding TagsText}" IsVisible="{Binding HasTags}" />
<Grid ColumnDefinitions="Auto,*,Auto,Auto" Margin="0,6,0,0">
<Button Classes="primary small" Content="{loc:Loc home.launch}"
Command="{Binding LaunchCommand}" />
<Button Grid.Column="2" Classes="ghost small" Content="{loc:Loc home.open}"
Command="{Binding OpenFolderCommand}" Margin="0,0,4,0" />
<Button Grid.Column="3" Classes="ghost small danger" Content="{loc:Loc home.delete}"
Command="{Binding DeleteCommand}" />
</Grid>
</StackPanel>
</StackPanel>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<!-- 空状态 -->
<Border Classes="card" Padding="30,34" IsVisible="{Binding IsEmpty}">
<StackPanel Spacing="10" HorizontalAlignment="Center">
<TextBlock Classes="h2" Text="{loc:Loc home.empty}" HorizontalAlignment="Center" />
<TextBlock Classes="muted" Text="{loc:Loc home.emptyHint}" TextWrapping="Wrap"
MaxWidth="420" TextAlignment="Center" />
<Button Classes="primary" Content="{loc:Loc home.emptyAction}"
Command="{Binding OpenDownloadCommand}" HorizontalAlignment="Center" Margin="0,6,0,0" />
</StackPanel>
</Border>
</StackPanel>
</ScrollViewer>
</UserControl>
+9
View File
@@ -0,0 +1,9 @@
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
namespace GC.Views;
public partial class HomeView : UserControl
{
public HomeView() => AvaloniaXamlLoader.Load(this);
}
+107
View File
@@ -0,0 +1,107 @@
using System;
using Avalonia;
using Avalonia.Animation;
using Avalonia.Animation.Easings;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Layout;
using Avalonia.Media;
using Avalonia.Threading;
namespace GC.Views;
/// <summary>
/// 模型启动进度窗:加载模型程序集、生成地表纹理、构建界面的真实进度。
/// 只显示进度,不做任何渲染。
/// </summary>
public sealed class LoadingWindow : Window
{
private readonly ProgressBar _bar;
private readonly TextBlock _stage;
private readonly TextBlock _percent;
public LoadingWindow(string modelName)
{
Title = modelName;
Width = 460;
Height = 172;
CanResize = false;
ShowInTaskbar = false;
WindowStartupLocation = WindowStartupLocation.CenterOwner;
Background = new SolidColorBrush(Color.Parse("#0B1226"));
SystemDecorations = SystemDecorations.BorderOnly;
var title = new TextBlock
{
Text = modelName,
Foreground = new SolidColorBrush(Color.Parse("#F2F6FF")),
FontSize = 15,
FontWeight = FontWeight.SemiBold
};
_stage = new TextBlock
{
Text = "正在准备模型…",
Foreground = new SolidColorBrush(Color.Parse("#8CA0C4")),
FontSize = 12
};
_bar = new ProgressBar
{
Minimum = 0,
Maximum = 1,
Value = 0,
Height = 6,
IsIndeterminate = true,
CornerRadius = new CornerRadius(3),
Foreground = new SolidColorBrush(Color.Parse("#3B7BFF")),
Background = new SolidColorBrush(Color.Parse("#1B2740")),
Transitions = new Transitions
{
// 进度平滑增长,不会一跳一跳
new DoubleTransition
{
Property = RangeBase.ValueProperty,
Duration = TimeSpan.FromMilliseconds(240),
Easing = new CubicEaseOut()
}
}
};
_percent = new TextBlock
{
Text = "",
Foreground = new SolidColorBrush(Color.Parse("#6E86AD")),
FontSize = 11,
HorizontalAlignment = HorizontalAlignment.Right
};
var panel = new StackPanel
{
Margin = new Thickness(22, 20),
Spacing = 12
};
panel.Children.Add(title);
panel.Children.Add(_bar);
panel.Children.Add(_stage);
panel.Children.Add(_percent);
Content = panel;
}
/// <summary>任意线程调用都可以。</summary>
public void Report(double value, string? message)
{
if (!Dispatcher.UIThread.CheckAccess())
{
Dispatcher.UIThread.Post(() => Report(value, message));
return;
}
var clamped = Math.Clamp(value, 0, 1);
_bar.IsIndeterminate = false;
_bar.Value = clamped;
_percent.Text = $"{clamped * 100:0}%";
if (!string.IsNullOrWhiteSpace(message)) _stage.Text = message;
}
}
Loaded 100 of 405 files, more files were not shown because too many files have changed in this diff. Show more